动态SQL中的循环

Chr*_*ris 8 sql sql-server

我有代码,我想应用于许多表,而不是简单地复制和替换表名,我想使用某种循环或光标来简化事情.

我设想设置一个表名的数组,并使用索引迭代列表,检索每个表名,并使用动态SQL在我的代码中散布表名.

因为据我所知,在SQL中没有"数组"构造,所以我不确定这是如何工作的.

关于如何解决这个问题的任何想法?

leg*_*ess 11

这是一种方法:

--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+' = '+<value>+' where '+@columnName +' = '+<someothervalue>
    exec @sql

    fetch next from @tableCursor into @tableName, @columnName
end

close @tableCursor
deallocate @tableCursor
Run Code Online (Sandbox Code Playgroud)