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