Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 Transact-SQL (2000)
 Loop over column names

Author  Topic 

scootermcfly
Yak Posting Veteran

66 Posts

Posted - 2001-09-26 : 11:34:43
I have a table that has some repeating columns that are named with a underscore character and then a number, such as col001_1, col001_2, etc.

I want to loop over these to insert the values into a another table that has a single col001. I am trying to construct some sql that will allow me to use a while loop and execute the sql.

Here is a sample of what i am trying to do:

Create table sp_temp(
col001 int NULL)

Declare @count int,@var_1 int,@var_2 int,@var_3 int,@sql varchar(100)
Select @count = 1,@var_1 = 1,@var_2 = 2,@var_3 = 6,@sql = ''

Select @sql = "Insert into sp_temp Select Col001 = @var_"

WHILE (@count <= 3)
BEGIN
Select @sql = @sql + convert(varchar,@count)

PRINT @sql

EXEC (@sql)

Select @sql = "Insert into sp_temp Select Col001 = @var_"

Select @count = @count + 1

END

This returns errors about must declare variable @var_1, etc

Any ideas?
Thanks, Scooter

   

- Advertisement -