我需要一些sql statemen的帮助。 我有不同的模式和相同的表名。 通过以下选择,我可以获得所有表格:
select name from sys.tables where QUOTENAME(name) = '[Table_1]'
现在我想循环遍历所有表,并对此进行类似的查询:
delete from tablename where condition1 > condition2
我怎样才能实现这个目标?
答案 0 :(得分:0)
试试这个
declare @count int, @i int = 1, @sql nvarchar(max), @tablename varchar(1000)
select @count = count(*) from sys.tables where QUOTENAME(name) = '[Table_1]'
create table #temp(id int identity(1,1), table varchar(1000))
insert into #temp
select name from sys.tables where QUOTENAME(name) = '[Table_1]'
while(@i<=@count)
begin
select @tablename = (select table from #temp where id = @i)
set @sql = 'delete from '+@tablename+' where condition1>condition2'
execute sp_executesql @sql
set @i = @i+1
end