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',... ...'
这个参数是限制此存储过程的操作用于哪些表
mssql里sp_MSforeachtable和sp_MSforeachdb的用法
最新推荐文章于 2024-09-22 11:17:00 发布