sp_msforeachtable @command1='delete from ?'
sp_msforeachtable使用方法1)說明
系統儲存過程sp_msforeachtable和sp_msforeachdb,是微軟提供的兩個不公開的儲存過程,從ms sql 6.5開始。
存放在sql server的master資料庫中。
2)引數說明:
@command1 nvarchar(2000), --第一條執行的sql指令
@replacechar nchar(1) = n'?', --指定的佔位符號
@command2 nvarchar(2000)= null, --第二條執行的sql指令
@command3 nvarchar(2000)= null, --第三條執行的sql指令
@whereand nvarchar(2000)= null, --可選條件來選擇表
@precommand nvarchar(2000)= null, --執行指令前的操作(類似控制項的觸發前的操作)
@postcommand nvarchar(2000)= null --執行指令後的操作(類似控制項的觸發後的操作)
3)舉例
--統計資料庫裡每個表的詳細情況
exec sp_msforeachtable @command1="sp_spaceused '?'"
--獲得每個表的記錄數和容量:
exec sp_msforeachtable @command1="print '?'",
@command2="sp_spaceused '?'",
@command3= "select count(*) from ? "
--獲得所有的資料庫的儲存空間:
exec sp_msforeachdb @command1="print '?'",
@command2="sp_spaceused "
--檢查所有的資料庫
exec sp_msforeachdb @command1="print '?'",
@command2="dbcc checkdb (?) "
--更新pubs資料庫中已t開頭的所有表的統計:
exec sp_msforeachtable @whereand="and name like 't%'",
@replacechar='*',
@precommand="print 'updating statistics.....' print ''",
@command1="print '*' update statistics * ",
@postcommand= "print''print 'complete update statistics!'"
--刪除當前資料庫所有表中的資料
sp_msforeachtable @command1='delete from ?'
sp_msforeachtable @command1 = "truncate table ?"
4)引數@whereand的用法
@whereand引數在儲存過程中起到指令條件限制的作用,具體的寫法如下:
@whereend,可以這麼寫 @whereand=' and o.name in (''table1'',''table2'',.......)'
例如:我想更新table1/table2/table3中note列為null的值
sp_msforeachtable @command1='update ? set note='''' where note is null',@whereand=' and o.name in (''table1'',''table2'',''table3'')'
5)"?"在儲存過程的特殊用法,造就了這兩個功能強大的儲存過程
這裡"?"的作用,相當於dos命令中、以及我們在windows下搜尋檔案時的萬用字元的作用。
清空SQL Server資料庫中所有表資料的方法
原文 清空sql server資料庫中所有表資料的方法 其實刪除資料庫中資料的方法並不複雜,為什麼我還要多此一舉呢,一是我這裡介紹的是刪除資料庫的所有資料,因為資料之間可能形成相互約束關係,刪除操作可能陷入死迴圈,二是這裡使用了微軟未正式公開的sp msforeachtable儲存過程。也許很多讀者...
Sqlserver清空資料庫中所有表資料
指令碼 1 create procedure sp deletealldata2as 3exec sp msforeachtable alter table nocheck constraint all 4 exec sp msforeachtable alter table disable tri...
清空SQL Server資料庫中所有表資料的方法
其實刪除資料庫中資料的方法並不複雜,為什麼我還要多此一舉呢,一是我這裡介紹的是刪除資料庫的所有資料,因為資料之間可能形成相互約束關係,刪除操作可能陷入死迴圈,二是這裡使用了微軟未正式公開的sp msforeachtable儲存過程。也許很多讀者朋友都經歷過這樣的事情 要在開發資料庫基礎上清理乙個空庫...