2012-01-18 58 views
0

我有10個表,比如Table_1,Table_2,Table_3,Table_4 ...,Table_10 ..我必須從除Table_4以外的所有表中刪除數據。 (使用'LIKE','IN'等)「從Tablename中刪除*表,如Table NOT IN('Table_4')」..從SQL表中刪除數據

+2

你使用哪個sql server? – 2012-01-18 11:59:42

+0

什麼數據庫?我還沒有想到它,但你可能能夠從模式中獲取表名,然後做...與他們的東西。 – cha0site 2012-01-18 11:59:59

+0

我的鏈接對你有幫助嗎? – 2012-01-18 16:36:58

回答

1

如果表的數量超過10,你不想列出刪除語句中的所有表。你應該堅持到目錄和使用遊標:

declare @table nvarchar(max) 
delcare @cur cursor 

set @cur = cursor fast_forward for 
    select name 
    from sys.tables 
    where name like 'Table_%' 
    and name not like 'Table_4' 

open @cur 
fetch next from @cur into @table 

while(@@fetch_status = 0) 
begin 
    sp_executesql 'DELETE FROM ' + @table 

    fetch next from @cur into @table 

end 
close @cur 
deallocate @cur 

編輯:這個答案是MS SQL只:)

+0

這不是你的「**錯誤**」,但似乎寫表名更好......寫得少,閱讀性更強,適用於每個數據庫。 =) – gdoron 2012-01-18 12:19:45

+0

如果有10000個表? :-) – Matten 2012-01-18 12:27:48

+1

所以你會有更多的問題,然後刪除他們的數據...... **大聲笑** – gdoron 2012-01-18 12:29:46

-1

寫一個刪除查詢與出TABLE_4

delete from Table_1,Table_2,Table_3,Table_5,......Table10 
+0

如果你有成千上萬的表?你會繼續手動寫嗎? – 2012-01-18 16:25:12

+0

這裏只有十張桌子,所以我建議 – Nighil 2012-01-18 18:03:07

+0

如果我說我有1000張桌子,並說出你的建議是什麼? – 2012-01-19 03:09:14

0
use [db_name] 

declare @sql nvarchar(max) 

select @SQL = 
(select '; 
DELETE FROM ' + quotename(TABLE_SCHEMA) + '.' + 
quotename(TABLE_NAME) from INFORMATION_SCHEMA.TABLES where TABLE_TYPE = 'BASE TABLE' 
and TABLE_NAME not in ('mytab1', 'mytab2') 

ORDER BY Table_Schema, TABLE_NAME 
FOR XML PATH(''), type).value ('.','nvarchar(max)') 

print @SQL -- verify 

它將創建刪除查詢並使用此查詢刪除所需的表,並跳過您不需要的。