SQL Server – Executing Same SQL Statement for Different Tables

sql serversql-server-2008-r2t-sql

I have a stored procedure that deletes data from multiple tables. The SQL is all the same, except for the name of the table.

UPDATE desttable
SET desttable.reportarea = esz2reportarea.reportarea
FROM table1 AS desttable JOIN esz2reportarea ON desttable.subdivisn = esz2reportarea.esz
WHERE desttable.reportarea = ''

UPDATE desttable
SET desttable.reportarea = esz2reportarea.reportarea
FROM table2 AS desttable JOIN esz2reportarea ON desttable.subdivisn = esz2reportarea.esz
WHERE desttable.reportarea = ''

...

UPDATE desttable
SET desttable.reportarea = esz2reportarea.reportarea
FROM table10 AS desttable JOIN esz2reportarea ON desttable.subdivisn = esz2reportarea.esz
WHERE desttable.reportarea = ''

I'd like to rewrite this to use some kind of loop, so that the SQL is only written once. (This is for SQL Server 2008R2.)

The list of tables that need to be updated will remain static; if there are any changes to the list of tables to be updated, it would be due to an application upgrade, and I'd have to redetermine which tables need to be modified at that time. The list of tables to be updated will be placed into a temporary table.

SELECT * INTO #tablenames
FROM (VALUES ('table1'), ('table2'), ('table3')) AS tables(tablename)

Best Answer

You dont need a loop for what you want. Dynamic SQL will help you want you want to achieve.

SELECT * INTO #tablenames
FROM (VALUES ('table1'), ('table2'), ('table3')) AS tables(tablename)

--select * from #tablenames



declare @sqltext nvarchar(max) = N''
select @sqltext += 'UPDATE  desttable
SET desttable.reportarea = esz2reportarea.reportarea
FROM '+quotename(tablename)+ ' table1 AS desttable JOIN esz2reportarea ON desttable.subdivisn = esz2reportarea.esz
WHERE desttable.reportarea = '''';'+char(10)
from #tablenames  
order by tablename

print @sqltext

-- once you review the above print statement and are HAPPY, uncomment the below part. 
-- Below part will actually RUN the UPDATE statement ... 
-- exec sp_executesql @sqltext

Note: I agree with @AaronBertrand that you should create a physical table - that will be a driver table for the update statement and just update the table when you want to modify or insert more values if you want other tables to be updated.