【推荐】(sqlServer)不公开存储过程
sp_Msforeachtable与sp_Msforeachdb详解
——通过知识共享树立个人品牌。
一.简要介绍:
系统存储过程sp_MSforeachtable和sp_MSforeachdb,是微软提供的两个不公开的存储过程。从mssql6.5开始,存放在sql Server的MASTER@R_502_6274@中。可以用来对某个@R_502_6274@的所有表或某个sql服务器上的所有@R_502_6274@进行管理,下面将对此进行详细介绍。
作为@R_502_6274@管理者或开发者等经常会检查整个@R_502_6274@或用户表。
如:检查整个@R_502_6274@的容量,看指定@R_502_6274@所有用户表的容量,所有表的记录数等等,我们一般处理这样的问题都是通过游标来达到要求。
如果我们用sp_MSforeachtable就可以非常方便的达到相同的目的,
如: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
我们在master@R_502_6274@里执行下面的语句可以看到两个proc详细的代码
exec sp_helptext sp_MSforeachtable
exec sp_helptext sp_Msforeachdb
三、使用举例:
-- 获得每个表的记录数和容量:
EXEC sp_MSforeachtable @command1 =" print ' ? '",
@command2 ="sp_spaceused ' ? '",
@command3 = " SELECT count( *) FROM ? "
-- 获得所有的@R_502_6274@的存储空间:
EXEC sp_MSforeachdb @command1 =" print ' ? '",
@command2 ="sp_spaceused "
-- 检查所有的@R_502_6274@
EXEC sp_MSforeachdb @command1 =" print ' ? '",
@command2 =" DBCC CHECKDB (?) "
-- 更新PUBS@R_502_6274@中已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! '"
-- 删除当前@R_502_6274@所有表中的数据
sp_MSforeachtable @command1 = ' Delete from ? '
sp_MSforeachtable @command1 = " TruncATE TABLE ?"
-- 查询@R_502_6274@所有表的记录总数
CREATE TABLE # temp (TableName VARCHAR ( 255), RowCnt INT)
EXEC sp_MSforeachtable ' INSERT INTO #temp SELECT '' ? '' , COUNT(*) FROM ? '
SELECT TableName, RowCnt FROM # temp ORDER BY TableName
DROP TABLE # temp
-- 检查数据库里每个表或索引视图的数据、索引及text、ntext 和image 页的完整性
-- 下列语句需在单用户模式下执行(sp_dboption 'db_name', 'single user', 'true')
-- ,将true改成false就又变成多用户了
exec sp_msforeachtable " dbcc checktable( ' ? ',repair_rebuild)"
4.参数@whereand的用法:
@whereand参数在存储过程中起到指令条件限制的作用,具体的写法如下:
@whereend,可以这么写
又如:
我想更新Table1/Table2/Table3中NOTE列为NULL的值
,@whereand = ' AND o.name in ( '' Table1 '' , '' Table3 '' ) '