Home Database Mysql Tutorial 【推荐】(SqlServer)不公开存储过程sp

【推荐】(SqlServer)不公开存储过程sp

Jun 07, 2016 pm 03:40 PM
sqlserver public storage recommend process

【 推荐 】 (SqlServer) 不公开存储过程 sp_Msforeachtable 与 sp_Msforeachdb 详解 通过知识共享树立个人品牌。 一.简要介绍: 系统存储过程 sp_MSforeachtable 和 sp_MSforeachdb , 是微软提供的两个不公开的存储过程。从mssql6.5开始,存放在SQL Server的M

 

推荐(SqlServer)不公开存储过程


sp_Msforeachtablesp_Msforeachdb详解


——通过知识共享树立个人品牌。

 

 

一.简要介绍:

系统存储过程sp_MSforeachtablesp_MSforeachdb,是微软提供的两个不公开的存储过程。从mssql6.5开始,存放在SQL Server的MASTER数据库中。可以用来对某个数据库的所有表或某个SQL服务器上的所有数据库进行管理,下面将对此进行详细介绍。

作为数据库管理者或开发者等经常会检查整个数据库或用户表。

如:检查整个数据库的容量,看指定数据库所有用户表的容量,所有表的记录数等等,我们一般处理这样的问题都是通过游标来达到要求。

如果我们用sp_MSforeachtable就可以非常方便的达到相同的目的,

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

 

EXEC sp_MSforeachtable "EXECUTE sp_spaceused '?'"

 

二.各参数说明:

  

  @command1 nvarchar(2000),          --第一条运行的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数据库里执行下面的语句可以看到两个proc详细的代码

 

use master
exec sp_helptext sp_MSforeachtable
exec sp_helptext sp_Msforeachdb

 

 

三、使用举例:

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

  exec sp_MSforeachtable @command1="sp_spaceused '?'"
 
  --获得每个表的记录数和容量:
  EXEC sp_MSforeachtable @command1="print '?'",
                         @command2="sp_spaceused '?'",
                         @command3= "SELECT count(*FROM ? "
 
  --获得所有的数据库的存储空间:
  EXEC sp_MSforeachdb @command1="print '?'",
                      @command2="sp_spaceused "
 
  --检查所有的数据库
  EXEC sp_MSforeachdb @command1="print '?'",
                      @command2="DBCC CHECKDB (?) "
 
  --更新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_MSforeachtable @command1='Delete from ?'
  sp_MSforeachtable @command1 = "TRUNCATE TABLE ?"
 
--查询数据库所有表的记录总数
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,可以这么写

 

@whereand=' AND o.name in (''Table1'',''Table2'',.......)' 

 

又如:

我想更新Table1/Table2/Table3中NOTE列为NULL的值

 

 sp_MSforeachtable @command1='Update ? Set NOTE='''' Where NOTE is NULL'
                  ,@whereand=' AND o.name in (''Table1'',''Table2'',''Table3'')'

 

5. "?"特别说明:

"?"在存储过程的特殊用法,造就了这两个功能强大的存储过程.

  "?"的作用,相当于DOS命令中和我们在WINDOWS下搜索文件时的通配符的作用。

6.小结

 有上面的分析,我们可以建立自己的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(int0x0002)))
 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

我们来测试一下:

 

 --获得所有的存储过程的脚本:
EXEc sp_MSforeachObject @command1="sp_helptext '?' ",@objectType=4
 
--获得所有的视图的脚本:
EXEc sp_MSforeachObject @command1="sp_helptext '?' ",@objectType=2
 
--比如在开发过程中,没一个用户都是自己的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

 

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the problem that the object named already exists in the sqlserver database How to solve the problem that the object named already exists in the sqlserver database Apr 05, 2024 pm 09:42 PM

For objects with the same name that already exist in the SQL Server database, the following steps need to be taken: Confirm the object type (table, view, stored procedure). IF NOT EXISTS can be used to skip creation if the object is empty. If the object has data, use a different name or modify the structure. Use DROP to delete existing objects (use caution, backup recommended). Check for schema changes to make sure there are no references to deleted or renamed objects.

How to import mdf file into sqlserver How to import mdf file into sqlserver Apr 08, 2024 am 11:41 AM

The import steps are as follows: Copy the MDF file to SQL Server's data directory (usually C:\Program Files\Microsoft SQL Server\MSSQL\DATA). In SQL Server Management Studio (SSMS), open the database and select Attach. Click the Add button and select the MDF file. Confirm the database name and click the OK button.

What to do if the sqlserver service cannot be started What to do if the sqlserver service cannot be started Apr 05, 2024 pm 10:00 PM

When the SQL Server service fails to start, here are some steps to resolve: Check the error log to determine the root cause. Make sure the service account has permission to start the service. Check whether dependency services are running. Disable antivirus software. Repair SQL Server installation. If the repair does not work, reinstall SQL Server.

How to check sqlserver port number How to check sqlserver port number Apr 05, 2024 pm 09:57 PM

To view the SQL Server port number: Open SSMS and connect to the server. Find the server name in Object Explorer, right-click it and select Properties. In the Connection tab, view the TCP Port field.

How to recover accidentally deleted database in sqlserver How to recover accidentally deleted database in sqlserver Apr 05, 2024 pm 10:39 PM

If you accidentally delete a SQL Server database, you can take the following steps to recover: stop database activity; back up log files; check database logs; recovery options: restore from backup; restore from transaction log; use DBCC CHECKDB; use third-party tools. Please back up your database regularly and enable transaction logging to prevent data loss.

Where is the sqlserver database? Where is the sqlserver database? Apr 05, 2024 pm 08:21 PM

SQL Server database files are usually stored in the following default location: Windows: C:\Program Files\Microsoft SQL Server\MSSQL\DATALinux: /var/opt/mssql/data The database file location can be customized by modifying the database file path setting.

How to recommend friends to me on Taobao How to recommend friends to me on Taobao Feb 29, 2024 pm 07:07 PM

In the process of using Taobao, we will often be recommended by some friends we may know. Here is an introduction to how to turn off this function. Friends who are interested should take a look. After opening the "Taobao" APP on your mobile phone, click "My Taobao" in the lower right corner of the page to enter the personal center page, and then click the "Settings" function in the upper right corner to enter the settings page. 2. After coming to the settings page, find "Privacy" and click on this item to enter. 3. There is a "Recommend friends to me" on the privacy page. When it shows that the current status is "on", click on it to close it. 4. Finally, in the pop-up window, there will be a switch button behind "Recommend friends to me". Click on it to set the button to gray.

How to delete sqlserver if the installation fails? How to delete sqlserver if the installation fails? Apr 05, 2024 pm 11:27 PM

If the SQL Server installation fails, you can clean it up by following these steps: Uninstall SQL Server Delete registry keys Delete files and folders Restart the computer

See all articles