Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Dynamic Columns in Temp Table

Status
Not open for further replies.

Lbob

Programmer
May 23, 2003
157
GB
Hi

I'm trying to create a temporary table that's made up of a number of dynamic columns, but I can't get it working.

This is what I've got so far

DECLARE @LT varchar(100)

SET NOCOUNT ON

CREATE TABLE #AdminSummary
(
UserID int null
)


DECLARE cursor_lt CURSOR FOR
SELECT lt_name FROM lt WHERE loc_id = @LocID

OPEN cursor_lt
FETCH NEXT FROM cursor_lt INTO @LT
WHILE @@fetch_status = 0
BEGIN
ALTER TABLE #AdminSummary ADD @LT varchar(100) NULL
GO

FETCH NEXT FROM cursor_lt INTO @LT
END
CLOSE cursor_lt
DEALLOCATE cursor_lt


Can anyone help?
Cheers
Lbob
 
Ok, is there another way of creating dynamic columns ?
 
What do you mean? The problem is I don't know how many columns there are going to be?
 
I've worked it out.....
Here's how to do it

DECLARE @LT varchar(100)

SET NOCOUNT ON

CREATE TABLE #AdminSummary
(
UserID int null
)


DECLARE cursor_lt CURSOR FOR
SELECT lt_name FROM lt WHERE loc_id = @LocID

OPEN cursor_lt
FETCH NEXT FROM cursor_lt INTO @LT
WHILE @@fetch_status = 0
BEGIN
EXEC( 'ALTER TABLE #AdminSummary ADD [' + @LT + '] varchar(100)' )

FETCH NEXT FROM cursor_lt INTO @LT
END
CLOSE cursor_lt
DEALLOCATE cursor_lt

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top