今天需要篩選出來庫中行數不為零的表,於是動手寫下了如下存儲過程。
CREATE PROCEDURE TableCount AS BEGIN SET NOCOUNT ON DECLARE @t1 AS TABLE(id INT IDENTITY,NAME NVARCHAR(50),RowsCount INT) DECLARE @indexid AS INT DECLARE @maxid AS INT DECLARE @count AS INT DECLARE @name AS VARCHAR(50) DECLARE @sqlstr AS NVARCHAR(500) INSERT INTO @t1 SELECT NAME,0 FROM dbo.sysobjects WHERE type='U' SELECT @maxid=MAX(id),@indexid=1 FROM @t1 WHILE(@maxid>=@indexid) BEGIN SELECT @name = name FROM @t1 WHERE id=@indexid SET @sqlstr = 'SELECT @Count1=COUNT(0) FROM '+@name exec sp_executesql @sqlstr,N'@Count1 int output',@count output UPDATE @t1 SET RowsCount=@count WHERE id=@indexid SET @indexid=@indexid+1 END SET NOCOUNT OFF SELECT * FROM @t1 WHERE RowsCount>0 END GO EXEC TableCount GO
這樣大功告成!
事后上網查閱相關資料發現有更簡便的方法,貼在這里供大家參考吧。
CREATE TABLE #temp (Name VARCHAR (255), RowsCount INT) EXEC sp_MSforeachtable 'INSERT INTO #temp SELECT ''?'', COUNT(0) FROM ?' SELECT Name, RowsCount FROM #temp WHERE RowsCount>0 ORDER BY Name DROP TABLE #temp
注: 系統存儲過程sp_MSforeachtable和sp_MSforeachdb,用於遍歷每個表和遍歷每個數據庫。
總結,遇到問題還是先查一下有沒有現成的方法能省不少的時間的,而且還可以學習到新的知識。
@空紫竹 提供的更快捷的方法: (2015-03-27編輯)
select rows,OBJECT_NAME(id) as TABLENAME from sysindexes where indid=0
