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.
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.