Using While Loop for SQL Server Update

后端 未结 3 1899
青春惊慌失措
青春惊慌失措 2021-01-16 12:49

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.

3条回答
  •  南笙
    南笙 (楼主)
    2021-01-16 13:03

    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.

提交回复
热议问题