遍历所有表、遍历所有数据库


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58
系统存储过程sp_MSforeachtable和sp_MSforeachdb,是微软提供的两个不公开的存储过程,从mssql6.5开始。存放在SQL Server的MASTER数据库中。可以用来对某个数据库的所有表或某个SQL服务器上的所有数据库进行管理
参数说明:

   @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       --执行指令后的操作(类似控件的触发后的操作)

   以后为sp_MSforeachtable的参数,sp_MSforeachdb不包括参数@whereand

如:查询当前数据库中所有以bd开头的表的容量

查询一条用:sp_spaceused

多条用:
CREATE TABLE #TableSpaceUsed(
TableName SYSNAME,
Rows INT,
Reserved VARCHAR(20),
DataSize VARCHAR(20),
IndexSize VARCHAR(20),
UnUsed VARCHAR(20))

EXEC sp_MSForEachTable
@command1=N'insert into #TableSpaceUsed exec sp_spaceused ''?''',@whereand='and o.name like ''%'''

SELECT * FROM #TableSpaceUsed
ORDER BY CONVERT(INT,REPLACE(Reserved,' KB','')) DESC
--更新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!'" --遍历数据库文件

--遍历数据库文件
CREATE TABLE #DataBaseFiles(
DB SYSNAME,
LogicName SYSNAME,
physical_name nvarchar(260),
FILENAME nvarchar(260),
FileSize DECIMAL(18,1)
)

--要用user ? 否则返回的结果仍是当前库的数据
EXEC sp_MSforeachdb 'USE ?  insert into #DataBaseFiles SELECT ''?'',name, substring(filename,len(filename) - charindex(''\'', reverse(filename))+2,charindex(''\'', reverse(filename))),filename, CONVERT(DECIMAL(18,1),(size*8.0/(1024*1024))) AS Size_GB FROM sys.sysfiles '

SELECT *
FROM #DataBaseFiles

Run same command on all SQL Server databases without cursors