【问题标题】:SQL Select rows and delete/update from dynamic multiple tablesSQL 选择行并从动态多个表中删除/更新
【发布时间】:2014-09-30 11:24:43
【问题描述】:

我需要一些关于 sql 语句的帮助。 我有不同的模式和相同的表名。 通过以下选择,我可以获得所有表格:

select name from sys.tables where QUOTENAME(name) = '[Table_1]'

现在我想遍历所有表,并有一些类似的查询:

delete from tablename where condition1 > condition2

我怎样才能做到这一点?

【问题讨论】:

标签: sql


【解决方案1】:

试试这个

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

【讨论】:

  • 第一个错误是,消息 156,级别 15,状态 1,行 5 关键字“表”附近的语法不正确。所以我将表更改为 tbl 第二个错误是:Msg 207, Level 16, State 1, Line 12 Invalid column name 'name'.
  • 之后我有消息 207,级别 16,状态 1,第 12 行无效的列名称“名称”。在行(从#temp 中选择名称,其中 id = @i)
  • 修改后,这是错误:这是错误:Msg 214,Level 16,State 2,Procedure sp_execute,Line 1Procedures 需要'int'类型的参数'@handle'。消息 214,级别 16,状态 2,过程 sp_execute,第 1 行过程需要类型为“int”的参数“@handle”。
  • 修改后的行是:select QUOTENAME(SCHEMA_NAME(schema_id))+'.'+QUOTENAME(name) from sys.tables where QUOTENAME(name) = '[Table_1]'
  • 你的修改没有问题,现在试试上面的查询
猜你喜欢
  • 2014-03-03
  • 1970-01-01
  • 2015-09-19
  • 1970-01-01
  • 1970-01-01
  • 2021-12-09
  • 1970-01-01
  • 1970-01-01
  • 2021-09-28
相关资源
最近更新 更多