SQL Loop Through Comma Separated Variable?
Posted on 2014-01-27
I need to Update a table having dynamically created column names. I have the names in a comma-delimited @Columns variable, filled by a cursor during column creation. I don't know MS SQL can use a 'For' or 'Foreach' against a comma-delimited variable string. I have some code below, it's missing the column-name-extraction syntax... Help
Note: columns names are 4-digit part numbers
Note: update appends a plus(+) to the column data which shows a price increase
Declare @ID = 1201
Declare @Columns varchar(max) = '1495, 1579, 4578, 9147, 17493, 6482'
Declare @Column varchar(30)
Declare @i int = 1
Declare @Sql varchar(max)
While (@i < @Count)
@Column = ??????
Set @Sql = 'Update a Set a.' + @Column + ' = ' + @Column + '' +''
+ ' From #PartNumbers a
where ID = ' + CAST(@ID AS VARCHAR) ;
Set @i = @i + 1