2009-10-16 79 views
0

所以,我有一個數據庫大約有100個審計表,我想清空它們,最好在1個sql查詢中。該數據庫有兩組表[audit]和[dbo]。我甚至不知道我應該怎麼稱呼這些表格,所以從谷歌中找到任何類型的結果都很困難。刪除集[DB]中的所有表數據[審計]。[表]

有什麼建議嗎?

回答

4

你可以找到像某個模式名稱的所有表:

select name from sys.tables where schema_name(schema_id) = 'audit' 

使用遊標,你遍歷這些表,並使用TRUNCATE TABLE清空他們:

use db 
declare @query nvarchar(max) 
declare @tablename nvarchar(max) 
declare @curs cursor 
set @curs = cursor for select name from sys.tables 
    where schema_name(schema_id) = 'audit' 
open @curs 
fetch next from @curs into @tablename 
while @@FETCH_STATUS = 0 
begin 
set @query = N'truncate table audit.' + @tablename 
exec sp_executesql @query 
fetch next from @curs into @tablename 
end 
close @curs 
deallocate @curs 

如果你想請刪除表格,使用:

set @query = N'drop table audit.' + @tablename 
+0

+1但我永遠不會跑它:)太可怕了。 – Andrew 2009-10-16 13:18:39

+2

您可以打印出所有的sql語句,而不是執行它們,並在運行之前直觀地檢查它們。 – 2009-10-16 13:22:47

2

您也可以使用sp_msfore achtable存儲過程。 它允許您在當前數據庫中的每個用戶表上執行查詢。

例如下面將截斷所有用戶表在你的數據庫

Use YourDB 
Exec sp_msforeachtable 'TRUNCATE TABLE ?' 

,這將截斷屬於審計模式在指定的數據庫中的所有用戶表。

Use YourDB 
Exec sp_msforeachtable @command1 = ' 
    if (Select Object_Schema_name(object_id(''?''))) = ''dbo'' 
    Begin 
     TRUNCATE TABLE ? 
     print ''truncated '' + ''?'' 
    End 
    ' 

另外Here是一個博客條目,該存儲過程有更多的用途。

相關問題