2014-09-30 99 views
0

我需要一些幫助與SQL狀態人。 我有不同的架構和相同的表名。 用下面的選擇我能得到的所有表:SQL選擇行並從動態多個表中刪除/更新

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

現在我想遍歷所有的表格,並有一些類似的查詢到這一點:

delete from tablename where condition1 > condition2 

我怎樣才能做到這一點?

+2

這'DBMS'?! – 2014-09-30 11:37:30

+0

你可能需要這樣的東西http://stackoverflow.com/a/25780596/3682599 – 2014-09-30 11:39:17

回答

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<[email protected]) 
begin 
    select @tablename = (select table from #temp where id = @i) 
    set @sql = 'delete from '[email protected]+' where condition1>condition2' 
    execute sp_executesql @sql 
    set @i = @i+1 
end 
+0

第一個錯誤是, 消息156,級別15,狀態1,行5 關鍵字'表'附近的語法不正確。 因此,我將表更改爲tbl 第二個錯誤是: 消息207,級別16,狀態1,行12 無效的列名稱'名稱'。 – user3057678 2014-09-30 11:54:01

+0

你現在可以檢查 – Azar 2014-09-30 11:59:41

+0

之後,我有消息207,級別16,狀態1,行12 無效的列名稱'名稱'。在該行(從#temp中選擇名稱,其中id = @i) – user3057678 2014-09-30 11:59:57