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'