一个值得研究的系统存储过程 sp_MSforeachtable

来源:互联网 发布:电子系单片机毕业设计 编辑:程序博客网 时间:2024/06/05 23:16

它的应用:

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

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',... ...'

这个参数是限制此存储过程的操作用于哪些表