獲取 多個數據庫 下的所有表的 數據條數

目的:
給定一些數據庫的名字,執行該SQL將得到這些數據庫下面的表的記錄條數

設計:
     1.首先將所有數據庫下的所有的表明 存放在一個臨時表中(#tmp)
     2.然後使用遊標對#tmp進行遍歷


具體SQL如下:

IF OBJECT_ID ('tempdb..#tmp' ) IS NOT NULL
       DROP TABLE #tmp


CREATE TABLE #tmp(
            tableName varchar(50 )
)

--catalog Cur
Declare @catalogName varchar (50)
Declare catalogCur Cursor For select t. catalogName from
(
select 'INVOICE' as catalogName union all
select 'PROP' as catalogName union all
select 'CORP' as catalogName union all
select 'GENOME' as catalogName ) as t   --注意:這裏需要使用別名
 

Open catalogCur
Fetch next From catalogCur Into @catalogName
While @@fetch_status =0    
       Begin
            exec('USE ' +@catalogName+ '
            insert into #tmp
            SELECT  TABLE_CATALOG+''.''+TABLE_SCHEMA+''.''+TABLE_NAME
            FROM information_schema.tables where TABLE_TYPE <> ''VIEW''' )
			--注意:TABLE_TYPE有兩種類型:BASE TABLE和VIEW,這裏我們就不需要View,所以將它過濾掉

              
             Fetch Next From catalogCur Into @catalogName
       End  
Close catalogCur  
Deallocate catalogCur


-----------tableCur
declare @tablename varchar (100)
Declare @sql varchar (max) = ''
Declare tableCur Cursor for select * from #tmp
open tableCur
fetch next from tableCur into @tablename
While @@fetch_status =0
BEGIN
       set @sql = @sql + 'select COUNT(1) as recordCount,'''+@tablename+ ''' as tableName from '+@tablename +' union all'+char( 13)
       fetch next from tableCur into @tablename
END
close tableCur
deallocate tableCur
set @sql = SUBSTRING( @sql,1 ,len( @sql)-10 )
--print @sql
exec (@sql )   --注意:這裏需要用括號將@sql括起來,否則會報類似下面的錯誤:The name '' is not a valid identifier.






發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章