• 点击这里给我发消息
  • 点击这里给我发消息
设为首页 \ 加入收藏    
您现在的位置: 主页 > 技术支持 >
技术支持
新闻资讯
产品中心
解决方案
成功案例
技术支持
关于我们
联系我们
联系我们
西安卓识信息科技有限公司
电话:029-88190617
地址:陕西省西安市科技路1号
主页:http://www.soft-zs.com
联系人:刘女士
电话:13379501476
QQ:408472479
 
技术支持
标题: 浅析SQL SERVER一个没有公开的存储过程
[发表时间: 2013-05-25 19:19 ] |[浏览:次]

从SQLSERVER6.5开始,MS提供了一个非常有用的系统存储过程sp_MSforeachtable和sp_MSforeachDB;作为DBA 会经常需要检查所有的数据库或用户表,比如:检查所有数据库的容量;看看指定数据库所有用户表的容量,所有表的记录数...,我们一般处理这样的问题都是用游标分别处理处理,比如:在数据库检索效率非常慢时,我们想检查数据库所有的用户表,我们就必须这样写游标:
DECLARE @TableName varchar(255)
DECLARE @ExeSQL varchar(4000)

DECLARE Table_Cursor CURSOR FOR SELECT [name] FROM sysobjects WHERE xtype=''U''

OPEN Table_Cursor
FETCH NEXT FROM   Table_Cursor INTO @TableName

WHILE(@@FETCH_STATUS=0)
BEGIN
PRINT @TableName
SELECT @ExeSQL=''DBCC CHECKTABLE(''''+@TableName+'''')''
EXEC(@EXESQL)
FETCH NEXT FROM   Table_Cursor INTO @TableName
END

CLOSE Table_Cursor
DEALLOCATE Table_Cursor
GO

     如果我们用sp_MSforeachtable就可以非常方便的达到相同的目的:
EXEC sp_MSforeachtable @command1="print ''?'' DBCC CHECKTABLE(''?'')"
大家可以看出这样就更加简洁(虽然在后台也是通过游标来处理的),下面我们就仔细分析一下sp_MSforeachtable这个存储过程:

我们看看sp_MSforeachtable详细的CODE:
USE MASTER
GO
SP_HELPTEXT sp_MSforeachtable

--下面时sp_MSforeachtable的原始代码

CREATE proc sp_MSforeachtable
@command1 nvarchar(2000), @replacechar nchar(1) = N''?'', @command2 nvarchar(2000) = null,
    @command3 nvarchar(2000) = null, @whereand nvarchar(2000) = null,
@precommand nvarchar(2000) = null, @postcommand nvarchar(2000) = null
as
/* This proc returns one or more rows for each table (optionally, matching @where), with each table defaulting to its

own result set */
/* @precommand and @postcommand may be used to force a single result set via a temp table. */

/* Preprocessor won''t replace within quotes so have to use str(). */
declare @mscat nvarchar(12)
select @mscat = ltrim(str(convert(int, 0x0002)))

if (@precommand is not null)
   exec(@precommand)

/* Create the select */
    exec(N''declare hCForEach cursor global for select ''['' + REPLACE(user_name(uid), N'']'', N'']]'') + '']'' + ''.'' + ''[''

+ REPLACE(object_name(id), N'']'', N'']]'') + '']'' from dbo.sysobjects o ''
          + N'' where OBJECTPROPERTY(o.id, N''IsUserTable'') = 1 '' + N'' and o.category & '' + @mscat + N'' = 0 ''
          + @whereand)
declare @retval int
select @retval = @@error
if (@retval = 0)
   exec @retval = sp_MSforeach_worker @command1, @replacechar, @command2, @command3

if (@retval = 0 and @postcommand is not null)
   exec(@postcommand)

return @retval

这个系统存储过程有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 --在表后执行的指令


所以上面的语句也可以这样写:
EXEC sp_MSforeachtable @command1="print ''?''",
          @command2= "DBCC CHECKTABLE(''?'')"

了解参数以后,就让我们做几个实列吧:
1.获得每个表的记录数和容量:
EXEC sp_MSforeachtable @command1="print ''?''",
          @command2="sp_spaceused ''?''",
          @command3= "SELECT count(*) FROM ? "

2.更新PUBS数据库中已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!''"


sp_MSforeachDB除了@whereand外,和sp_MSforeachtable的参数是一样的,我们可以通过这个存储过程检测所有的数据库,比如:
1.获得所有的数据库的存储空间:
        EXEC sp_MSforeachdb   @command1="print ''?''",
                                          @command2="sp_spaceused "
2.检查所有的数据库
        EXEC sp_MSforeachdb   @command1="print ''?''",
                                            @command2="DBCC CHECKDB (?) "

有了上面的分析,我们可以建立自己的sp_MSforeachObject:
USE MASTER
GO
CREATE proc sp_MSforeachObject
@objectType int=1,
@command1 nvarchar(2000),
@replacechar nchar(1) = N''?'',
@command2 nvarchar(2000) = null,
     @command3 nvarchar(2000) = null,
@whereand nvarchar(2000) = null,
@precommand nvarchar(2000) = null,
@postcommand nvarchar(2000) = null
as
/* This proc returns one or more rows for each table (optionally, matching @where), with each table defaulting to its

own result set */
/* @precommand and @postcommand may be used to force a single result set via a temp table. */

/* Preprocessor won''t replace within quotes so have to use str(). */
declare @mscat nvarchar(12)
select @mscat = ltrim(str(convert(int, 0x0002)))

if (@precommand is not null)
   exec(@precommand)

/* Defined   @isobject for save object type */
Declare @isobject varchar(256)

select @isobject= case @objectType when 1 then ''IsUserTable''
          when 2 then ''IsView''
          when 3 then ''IsTrigger''
          when 4 then ''IsProcedure''
          when 5 then ''IsDefault''  
          when 6 then ''IsForeignKey''
          when 7 then ''IsScalarFunction''
          when 8 then ''IsInlineFunction''
          when 9 then ''IsPrimaryKey''
          when 10 then ''IsExtendedProc''   
          when 11 then ''IsReplProc''
          when 12 then ''IsRule''
                   end

/* Create the select */
/* Use @isobject variable isstead of IsUserTable string */
EXEC(N''declare hCForEach cursor global for select ''['' + REPLACE(user_name(uid), N'']'', N'']]'') + '']'' + ''.'' + ''['' +

REPLACE(object_name(id), N'']'', N'']]'') + '']'' from dbo.sysobjects o ''
         + N'' where OBJECTPROPERTY(o.id, N''''+@isobject+'''') = 1 ''+N'' and o.category & '' + @mscat + N'' = 0 ''
        + @whereand)

declare @retval int
select @retval = @@error
if (@retval = 0)
   exec @retval = sp_MSforeach_worker @command1, @replacechar, @command2, @command3

if (@retval = 0 and @postcommand is not null)
   exec(@postcommand)

return @retval

GO
这样我们来测试一下:
1.获得所有的存储过程的脚本:
          EXEc sp_MSforeachObject @command1="sp_helptext ''?'' ",@objectType=4
2.获得所有的视图的脚本:
          EXEc sp_MSforeachObject @command1="sp_helptext ''?'' ",@objectType=2
3.比如在开发过程中,没一个用户都是自己的OBJECT OWNER,所以在真实的数据库时都要改为DBO:
            EXEc sp_MSforeachObject @command1="sp_changeobjectowner ''?'', ''dbo''",@objectType=1
            EXEc sp_MSforeachObject @command1="sp_changeobjectowner ''?'', ''dbo''",@objectType=2
             EXEc sp_MSforeachObject @command1="sp_changeobjectowner ''?'', ''dbo''",@objectType=3
               EXEc sp_MSforeachObject @command1="sp_changeobjectowner ''?'', ''dbo''",@objectType=4
   这样就非常方便的将每一个数据库对象改为DBO.

当然还要很多非常好的功能,大家可以自己深入研究吧:-)

 

系统未公开的存储过程sp_msforeachtable 的用法

   如何清空SQL数据库里的数据
1、打开“服务管理器”,选中你要处理的数据库,然后打开“工具”里的“SQL查分析器”,运行下面语句:

--先禁用所有外键约束 
exec sp_msforeachtable "alter table ? nocheck CONSTRAINT all" 
--然后删除数据 
exec sp_msforEachTable "TRUNCATE TABLE?" 

--再启用所有外键约束 
exec sp_msforeachtable "alter table ? check constraint all"

2、成功。然后导入你的数据或重新填写数据。

 

它的应用:

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

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 里面那个问号指代数据库中所有的表

对所有表进行类似处理
eg1:

大家知道,如果将一个表所有者改为dbo,只需

sp_changeobjectowner ''表名'',''dbo''即可

但要将所有的表的所有者都改为dbo,可以用循环处理,此处略

其实用SQL的系统存储过程sp_MSForEachTable可以轻松搞定

只需exec sp_MSForEachTable ''sp_changeobjectowner ''''?'''', ''''dbo''''''

当然,可能运行时会有错(比如有些表的所有者原先就是dbo),不用理它,运行一遍就行了。

eg2:

所有表都加上一个自增长的字段

大家知道对一个表加的话只需: alter table 表名 add iid int identity(1,1)

若需对所有的表都加的话只需: sp_MSForEachTable ''alter table ? add iid int identity(1,1)''

同理,删除所有表中的iid字段只需 sp_MSForEachTable ''alter table ? drop column iid''


当然,可能运行时会有错(比如加字段时该表中已有该字段,删除字段时没有该字段),不用理它,运行一遍就行了。

eg3:

对所有表中的num字段进行四舍五入处理

sp_MSForEachTable ''update ? set num = round(num,2)''

当然,可能运行时会有错(比如有些表中没有num字段),不用理它,运行一遍就行了。

+ 上一篇:sp_MSforeachtable使用方法
+ 下一篇:删除WINDOWS用户时提示:删除用户“XX”时,出现了以下错误:无法
 
西安卓识信息科技有限公司 版权所有【陕ICP备11007810号】