mssql里sp_MSforeachtable和sp_MSforeachdb的用法

sql查询所有用户表的列表,详细信息,如:记录数,表占用大小等 

EXEC  sp_MSforeachtable  "EXECUTE  sp_spaceused  '?'"


mssql里sp_MSforeachtable和sp_MSforeachdb的用法
从mssql6.5开始,微软提供了两个不公开,非常有用的系统存储过程sp_MSforeachtable和sp_MSforeachdb,用于遍历某个数据库的每个表和遍历DBMS管理下的每个数据库。

mssql里sp_MSforeachtable和sp_MSforeachdb的用法

我们在master数据库里执行下面的语句可以看到两个proc详细的代码


use master


exec sp_helptext sp_MSforeachtable


exec sp_helptext sp_Msforeachdb


sp_MSforeachtable系统存储过程有7个参数,解释如下:


@command1 nvarchar(2000),  --第一条运行的T-SQL指令


@replacechar nchar(1) = N'?',  --指定的占位符号


@command2 nvarchar(2000)= null,--第二条运行的T-SQL指令


@command3 nvarchar(2000)= null, --第三条运行的T-SQL指令


@whereand nvarchar(2000)= null, --可选条件来选择表


@precommand nvarchar(2000)= null, --在表前执行的指令


@postcommand nvarchar(2000)= null --在表后执行的指令



mssql里sp_MSforeachtable和sp_MSforeachdb的用法- -

sp_MSforeachdb除了@whereand外,和sp_MSforeachtable的参数是一样的。




--我们来看看sp_MSforeachtable的用法(sp_MSforeachdb的用法类似):

--统计数据库里每个表的详细情况:

exec sp_MSforeachtable @command1="sp_spaceused '?'"




--检查数据库里每个表或索引视图的数据、索引及text、ntext 和image 页的完整性

--下列语句需在单用户模式下执行(sp_dboption 'db_name', 'single user', 'true'),将true改成false就又变成多用户了

exec sp_msforeachtable "dbcc checktable('?',repair_rebuild)"


sp_MSforeachtable @command1='Delete from ?'
这样可以删除所有表中的数据

也可以这样写

sp_MSforeachtable @command1 = "TRUNCATE TABLE ?"

----------------------------------------------------------------------

创建一个新表AAA,表中包含其它表的名称和记录数量:

create table AAA(id int identity(1,1),tablename varchar(50),[rowcount] int)

delete from AAA

exec sp_msforeachtable 'insert AAA(tablename, [rowcount]) select N''?'', count(*) from ?'

select * from AAA where AAA.[rowcount]>0

----------------------------------------------------------------------

1。在sql server2000下一个数据库中有建立了几十个表,现在要给每个表增加同样的列。可以用"alter table"语句,但是这么多表一个一个的操作太麻烦,有什么方法可以操作循环每一个表呢?
方法:sp_msforeachtable 'alter table ? add 列名 int'



2。假设所有表中的'note' 字段不能为空,如果为空则要改为"。
方法:sp_msforeachtable 'update ? set note='''' where note is null'

----------------------------------------------------------------------

结论: 看了很多例子以后发现sp_msforeachtable 里面那个问号指代数据库中所有的表

此存储过程还有一个参数为@whereend,可以这么写 @whereend='name in 'table1','table2',... ...'

这个参数是限制此存储过程的操作用于哪些表
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值