开发者

Accessing 400 tables in a single query

开发者 https://www.devze.com 2023-04-13 02:29 出处:网络
I want to delete rows with a condition from mu开发者_如何学编程ltiple tables. DELETE FROM table_1

I want to delete rows with a condition from mu开发者_如何学编程ltiple tables.

DELETE
FROM table_1
WHERE lst_mod_ymdt = '2011-01-01'

The problem is that, the number of table is 400, from table_1 to table_400. Can I apply the query to all the tables in a single query?


If you're using SQL Server 2005 and later you can try something like this (other versions and RDMS also have similar ways to do this):

DECLARE @sql VARCHAR(MAX)

SET @sql = (SELECT 'DELETE FROM [' + REPLACE(Name, '''','''''') + '] WHERE lst_mod_ymdt = ''' + @lst_mod_ymdt + ''';' FROM sys.tables WHERE Name LIKE 'table_%' FOR XML PATH(''))

--PRINT @sql;
EXEC ( @sql );

And as always with dynamic sql, remember to escape the ' character.

This will likely fall over if you have say table_341 which doesn't have a lst_mod_ymdt column.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号