加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

SQLServer sp_MSforeachtable和sp_MSforeachdb用法

发布时间:2020-12-12 12:58:24 所属栏目:MsSql教程 来源:网络整理
导读:sp_MSforeachtable 和 sp_MSforeachdb 都是SQLserver 未正式公布(Undocumented)的存储过程,对管理员来说,经常需要在多库多表执行sql命令或者统计数据库信息都是比较方便的。 当前将用2个示例说明这2个存储过程是怎么使用的: 存储过程参数说明: exec @r

sp_MSforeachtable 和 sp_MSforeachdb 都是SQLserver 未正式公布(Undocumented)的存储过程,对管理员来说,经常需要在多库多表执行sql命令或者统计数据库信息都是比较方便的。

当前将用2个示例说明这2个存储过程是怎么使用的:


存储过程参数说明:

exec @return_value=sp_MSforeachtable @command1,@replacechar,@command2,@command3,@whereand,@precommand,@postcommand
exec @return_value=sp_MSforeachdb    @command1,@postcommand

@return_value int					--返回值:0成功;其他失败
@command1 nvarchar(2000)			--第一个执行的命令
@replacechar nchar(1) = N'?'		--自定义表名称的符号,默认'?'
@command2 nvarchar(2000) = null		--第二个执行的命令
@command3 nvarchar(2000) = null		--第三个执行的命令
@whereand nvarchar(2000) = null		--过滤表名称的条件(sp_MSforeachdb 无此参数)
@precommand nvarchar(2000) = null	--执行存储过程前的命令
@postcommand nvarchar(2000) = null	--执行存储过程后的命令


sp_MSforeachtable 统计数据库中各表的空间分配情况:

--	drop  table #TabSpaceused
CREATE TABLE #TabSpaceused
(
	name sysname,rows int,reserved sysname,data sysname,index_size sysname,unused sysname,)
GO

EXEC sp_MSforeachtable 
 @replacechar='?',@command1 = "insert into #TabSpaceused exec sp_spaceused '?'",@command2 = "update statistics ?",@command3 = "print '?'",@whereand = "and o.name not like 'conflict%' and o.name not like 'sys%' ",@precommand="print 'Begin Time: '+convert(varchar(30),getdate(),121)",@postcommand="print 'End Time: '+convert(varchar(30),121)"
GO

SELECT * FROM #TabSpaceused


;WITH TabSpaceused AS(
	SELECT name,rows,CONVERT(INT,LEFT(reserved,CHARINDEX(' ',reserved))) AS reserved,LEFT(data,data))) AS data,LEFT(index_size,index_size))) AS index_size,LEFT(unused,unused))) AS unused
	FROM #TabSpaceused
)
SELECT * FROM TabSpaceused

sp_MSforeachdb 统计数据库的空间分配情况:

--	select * from [master].[sys].[master_files]


--	drop  table #DBSpaceused
CREATE TABLE #DBSpaceused
(
	datebase sysname,fileid smallint,groupid smallint,size bigint,maxsize bigint,growth float,status int,perf int,name sysname,filename sysname
)
GO

EXEC sp_MSforeachdb 
 @replacechar='?',@command1 = "if '?' not in('master','model','msdb','tempdb') begin insert into #DBSpaceused select '?',* from ?.[dbo].[sysfiles] end",@command2 = "select count(0) as ?的表数量 from ?.sys.sysobjects where xtype='U'",121)"
GO


select * from #DBSpaceused

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读