Sql – Using While Loop for SQL Server Update

loopssqlsql-server-2005

I am trying to become more efficient in my SQL programming.
I am trying to run a loop to repeat an update command on field names that only change by a numerical suffix.

For example, instead of writing out x_1, y_1, then x_2, y_2 for each update:

DECLARE @a INT 
DECLARE @b VARCHAR 

SET @a = 1
WHILE @a < 30
set @b = @a
  BEGIN
       UPDATE source set h = h + "x_"+@b
           where "y_"+@b = 'Sold'
    SET @a = @a + 1
  END

Let me know if I can clarify. I'm using SQL Server 2005.

Thanks for any guidance.


I'm trying to apply Adams's solution and need to understand what is proper usage of N' in the following:

exec sp_executesql update source_temp set pmt_90_day = pmt_90_day + convert(money,'trans_total_'+@b'')
    where convert(datetime,'effective_date_'+@b) <= dateadd(day,90,ORSA_CHARGE_OFF_DATE)
    and DRC_FLAG_'+@b = 'C'

Best Answer

This won't actually work, as you can't have the column name in quotes. What you're essentially doing is having SQL compare two strings that will always be different, meaning you'll never perform an update.

If you must do it this way, you'd have to have something like...

DECLARE @a INT 
DECLARE @b VARCHAR 
SET @a = 1

WHILE @a < 30
BEGIN
set @b = @a  
exec sp_executesql N'UPDATE source set h = h + 'x_'+@b + N'
           where y_'+@b + N' = ''Sold'''   

SET @a = @a + 1
END

In general, however, I'd discourage this practice. I'm not a fan of dynamic SQL being generated inside another SQL statement for any sort of production code. Very useful for doing one-off development tasks, but I don't like it for code that could get executed by a user.