Loops within dynamic SQL

前端 未结 2 1410
长发绾君心
长发绾君心 2021-02-15 05:26

I have code that I\'d like to apply to a number of tables but rather than simply copy and replace table names, I\'d like to use some kind of loop or cursor to simplify things.

2条回答
  •  闹比i
    闹比i (楼主)
    2021-02-15 05:51

    Here is one way of doing it:

    --Declare a table variable to hold your table names (and column names in case needed)
    declare @listOfTablesToUpdate table (tableName varchar(100), columnNameToUpdate varchar(50))
    
    --insert the tables that you want to work with.
    insert into @listOfTablesToUpdate values ('Table1', 'column2')
    insert into @listOfTablesToUpdate values ('Table2', 'column3')
    insert into @listOfTablesToUpdate values ('Table3', 'column4')
    
    --Cursor for iterating
    declare @tableCursor cursor,
            @tableName varchar(100),
            @columnName varchar(50)
    
    set @tableCursor = cursor for select * from @listOfTablesToUpdate
    
    open @tableCursor
    fetch next from @tableCursor into @tableName, @columnName
    while(@@fetch_status = 0)
    begin
        --dynamic sql
        declare @sql varchar(max)
    
        --Your logic here...this is just an example
        set @sql = 'update '+@tableName+' set '+@columnName+' = '++' where '+@columnName +' = '+
        exec @sql
    
        fetch next from @tableCursor into @tableName, @columnName
    end
    
    close @tableCursor
    deallocate @tableCursor
    

提交回复
热议问题