Solved

use ALTER TABLE on a Table Variable

Posted on 2003-11-07
4
770 Views
Last Modified: 2012-05-04
Hey folks,

Im stumped.  I have a table variable that I need to alter dynamically:

DELCARE @tDate smalldatetime
DECLARE @BeginDate smalldatetime
DECLARE @EndDate smalldatetime

SET @BeginDate = '1/1/03'
SET @EndDate = '12/31/03'
SET @tDate = @Begindate

DECLARE @Scores TABLE (StudentName varchar(100))

WHILE (@tDate < @EndDate)  BEGIN
  SET @tVar = dbo.MonthName(Month(@tDate),1) + ' ' +  convert(varchar,year(@tDate))
  ALTER TABLE @Scores ADD @tVar VARCHAR(20) NULL
  SET @tDate = DATEADD(month,1,@tDate)
END

If the answer is you cant use ALTER TABLE for Table Variables, then how can I change my table variable after its been declared

I also tried DECLARE @Scores TABLE (@fieldNames) and that didn't work at all.

HELP!!
0
Comment
Question by:DialM4Monkey
4 Comments
 
LVL 15

Accepted Solution

by:
namasi_navaretnam earned 250 total points
ID: 9703225
If you need to dynamicaly add column you will need to use traditional temp tables.

drop table #test

create table #test
(
col1 int
)

alter table #test
add col2 int

select * from #test
0
 
LVL 22

Expert Comment

by:CJ_S
ID: 9704079
Just like you cannot place constraints on a table variable.

create table x(id smalldatetime constraint t_id default getdate())
and
declare @t table (id smalldatetime constraint t_id default getdate())


Use temporary tables instead like namasi pointed out. Just don't forget to remove them once you're finished.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

When you hear the word proxy, you may become apprehensive. This article will help you to understand Proxy and when it is useful. Let's talk Proxy for SQL Server. (Not in terms of Internet access.) Typically, you'll run into this type of problem w…
This article explains how to reset the password of the sa account on a Microsoft SQL Server.  The steps in this article work in SQL 2005, 2008, 2008 R2, 2012, 2014 and 2016.
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.

910 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now