SQL:如何跨多个表更新相同的列?

时间:2018-04-24 00:00:18

标签: sql

我有一个查询可以获取我需要更新的所有表格,这些表格都包含一个列foo:

select table_name from information_schema.tables where table_name like 'Filter%'

如何将它与将更新列foo的UPDATE命令结合使用?

1 个答案:

答案 0 :(得分:2)

SQL SERVER版本:

--Test Data
create table [Filter]  ( foo int)
create table [Filter2]  ( foo int)
create table [Filter3]  ( foo int)
insert into [Filter] (foo) values (1)
insert into [Filter2] (foo) values (1)
insert into [Filter3] (foo) values (1)

--use exec and update
declare @sql nvarchar(max) = '';
SELECT @sql=@sql+' update '+table_name+' set foo = 2 where foo = 1 ;' 
FROM INFORMATION_SCHEMA.TABLES where table_name like 'Filter%'
and TABLE_TYPE = 'BASE TABLE';
select @sql;
exec(@sql);

--result
select * from [Filter]

数据库测试链接:  sql-how-to-update-same-column-across-multiple-tables