我希望将代码应用于多个表,而不是简单地复制和替换表名,而是使用些循环或游标来简化代码。4 J# o7 K/ _' W* n% J2 }" W
我设想设置一个表名数组,并使用索引遍历该列表,检索每个表名,并在适用于我的代码的情况下使用动态SQL散布表名。/ r: |6 c% j3 V$ G$ L! ]4 G! Y* E0 s
据我所知,因为在SQL没有数组结构,所以我不确定会怎么工作。: e; ~4 P( Q3 V1 ~1 Q3 }
任何关于如何解决这个问题的想法?1 B8 j- {+ b ~5 w* }
% S" A/ Y# q4 Q) C7 g4 J- I4 Q7 C 解决方案: * J: [& f& V$ Q8 @
这是一种实现方法:' R1 h* e( R" m$ B( o
--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 iteratingdeclare @tableCursor cursor, @tableName varchar(100) @columnName varchar(50)set @tableCursor = cursor for select * from @listOfTablesToUpdateopen @tableCursorfetch next from @tableCursor into @tableName,@columnNamewhile(@@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,@columnNameendclose @tableCursordeallocate @tableCursor