淺析sql server一個沒有公開的存儲過程
   從sqlserver6.5開始,ms提供了一個非常有用的系統存儲過程sp_msforeachtable和sp_msforeachdb;作為dba會經常需要檢查所有的數據庫或用戶表,比如:檢查所有數據庫的容量;看看指定數據庫所有用戶表的容量,所有表的記錄數...,我們一般處理這樣的問題都是用游標分別處理處理,比如:在數據庫檢索效率非常慢時,我們想檢查數據庫所有的用戶表,我們就必須這樣寫游標:
declare @tablename varchar(255)
declare @exesql varchar(4000)
declare table_cursor cursor for select [name] from sysobjects where xtype='u'
open table_cursor
fetch next from  table_cursor into @tablename
while(@@fetch_status=0)
begin
 print @tablename
 select @exesql='dbcc checktable('''[email protected]+''')'
 exec(@exesql)
fetch next from  table_cursor into @tablename
end
close table_cursor
deallocate table_cursor
go
    如果我們用sp_msforeachtable就可以非常方便的達到相同的目的:
exec sp_msforeachtable @command1="print '?' dbcc checktable('?')"
大家可以看出這樣就更加簡潔(雖然在后臺也是通過游標來處理的),下面我們就仔細分析一下sp_msforeachtable這個存儲過程:
我們看看sp_msforeachtable詳細的code:
use master 
go
sp_helptext sp_msforeachtable
--下面時sp_msforeachtable的原始代碼
create proc sp_msforeachtable
 @command1 nvarchar(2000), @replacechar nchar(1) = n'?', @command2 nvarchar(2000) = null,
   @command3 nvarchar(2000) = null, @whereand nvarchar(2000) = null,
 @precommand nvarchar(2000) = null, @postcommand nvarchar(2000) = null
as
 /* this proc returns one or more rows for each table (optionally, matching @where), with each table defaulting to its 
own result set */
 /* @precommand and @postcommand may be used to force a single result set via a temp table. */
 /* preprocessor won't replace within quotes so have to use str(). */
 declare @mscat nvarchar(12)
 select @mscat = ltrim(str(convert(int, 0x0002)))
 if (@precommand is not null)
  exec(@precommand)
 /* create the select */
   exec(n'declare hcforeach cursor global for select ''['' + replace(user_name(uid), n'']'', n'']]'') + '']'' + ''.'' + ''['' 
+ replace(object_name(id), n'']'', n'']]'') + '']'' from dbo.sysobjects o '
         + n' where objectproperty(o.id, n''isusertable'') = 1 ' + n' and o.category & ' + @mscat + n' = 0 '
         + @whereand)
 declare @retval int
 select @retval = @@error
 if (@retval = 0)
  exec @retval = sp_msforeach_worker @command1, @replacechar, @command2, @command3
 if (@retval = 0 and @postcommand is not null)
  exec(@postcommand)
 return @retval
這個系統存儲過程有7個參數:
 @command1 nvarchar(2000),  --第一條運行的t-sql指令
 @replacechar nchar(1) = n'?',   --指定的占位符號 
 @command2 nvarchar(2000) = null,--第二條運行的t-sql指令
    @command3 nvarchar(2000) = null, --第三條運行的t-sql指令
 @whereand nvarchar(2000) = null, --可選條件來選擇表
 @precommand nvarchar(2000) = null, --在表前執行的指令
 @postcommand nvarchar(2000) = null --在表后執行的指令
所以上面的語句也可以這樣寫:
exec sp_msforeachtable @command1="print '?'",
         @command2= "dbcc checktable('?')"
了解參數以后,就讓我們做幾個實列吧:
1.獲得每個表的記錄數和容量:
exec sp_msforeachtable @command1="print '?'",
         @command2="sp_spaceused '?'",
         @command3= "select count(*) from ? "
2.更新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_msforeachdb除了@whereand外,和sp_msforeachtable的參數是一樣的,我們可以通過這個存儲過程檢測所有的數據庫,比如:
1.檢查所有的數據庫
       exec sp_msforeachdb  @command1="print '?'",
                                           @command2="dbcc checkdb (?) "
有了上面的分析,我們可以建立自己的sp_msforeachobject:
use master
go
create proc sp_msforeachobject
 @objecttype int=1,
 @command1 nvarchar(2000), 
 @replacechar nchar(1) = n'?', 
 @command2 nvarchar(2000) = null,
    @command3 nvarchar(2000) = null, 
 @whereand nvarchar(2000) = null,
 @precommand nvarchar(2000) = null, 
 @postcommand nvarchar(2000) = null
as
 /* this proc returns one or more rows for each table (optionally, matching @where), with each table defaulting to its 
own result set */
 /* @precommand and @postcommand may be used to force a single result set via a temp table. */
 /* preprocessor won't replace within quotes so have to use str(). */
 declare @mscat nvarchar(12)
 select @mscat = ltrim(str(convert(int, 0x0002)))
 if (@precommand is not null)
  exec(@precommand)
 /* defined  @isobject for save object type */
 declare @isobject varchar(256)
 select @isobject= case @objecttype when 1 then 'isusertable'
         when 2 then 'isview'
         when 3 then 'istrigger'
         when 4 then 'isprocedure' 
         when 5 then 'isdefault'   
         when 6 then 'isforeignkey'
         when 7 then 'isscalarfunction'
         when 8 then 'isinlinefunction'
         when 9 then 'isprimarykey'
         when 10 then 'isextendedproc'    
         when 11 then 'isreplproc'
         when 12 then 'isrule'
                  end
 /* create the select */
 /* use @isobject variable isstead of isusertable string */
exec(n'declare hcforeach cursor global for select ''['' + replace(user_name(uid), n'']'', n'']]'') + '']'' + ''.'' + ''['' + 
replace(object_name(id), n'']'', n'']]'') + '']'' from dbo.sysobjects o '
        + n' where objectproperty(o.id, n'''[email protected]+''') = 1 '+n' and o.category & ' + @mscat + n' = 0 '
       + @whereand)
 declare @retval int
 select @retval = @@error
 if (@retval = 0)
  exec @retval = sp_msforeach_worker @command1, @replacechar, @command2, @command3
 if (@retval = 0 and @postcommand is not null)
  exec(@postcommand)
 return @retval
go
這樣我們來測試一下:
1.獲得所有的存儲過程的腳本:
         exec sp_msforeachobject @command1="sp_helptext '?' ",@objecttype=4
2.獲得所有的視圖的腳本:
         exec sp_msforeachobject @command1="sp_helptext '?' ",@objecttype=2
3.比如在開發過程中,沒一個用戶都是自己的object owner,所以在真實的數據庫時都要改為dbo:
           exec sp_msforeachobject @command1="sp_changeobjectowner '?', 'dbo'",@objecttype=1
           exec sp_msforeachobject @command1="sp_changeobjectowner '?', 'dbo'",@objecttype=2
            exec sp_msforeachobject @command1="sp_changeobjectowner '?', 'dbo'",@objecttype=3
              exec sp_msforeachobject @command1="sp_changeobjectowner '?', 'dbo'",@objecttype=4
  這樣就非常方便的將每一個數據庫對象改為dbo.
當然還要很多非常好的功能,大家可以自己深入研究吧:-)