Home > Articles > Data > SQL Server

This chapter is from the book

2.7 SYSTEM STORED PROCEDURES AND DBCC

System stored procedures and extended procedures are built-in commands that perform a variety of tasks to do database administration and to provide information.

2.7.1 System Stored Procedures

There are hundreds of system stored procedures and extended procedures. Some individual stored procedures will be described as needed throughout the book. You may check the index to see if a given stored procedure is described in the book. A complete list of system stored procedures may be found in Appendix A. Metadata stored procedures are discussed on p. 376. Additional details may be found by looking each up by name in Books Online.

In general, system stored procedure names start with sp_ and return results within SQL Server. Extended stored procedure names start with xp_ and require doing work outside of SQL Server such as making calls to the operating system or an external process.

Some useful system stored procedures and extended procedures are summarized in Table 2-71.

Table 2-71. System Stored Procedures

sp_configure [settingname [, settingvalue]]

No arguments—lists all current server settings in five columns name minimum maximum config_value run_value where config_value is value configured but may not yet be effective until server restarts or "reconfigure" command is executed.

1 argument—shows its value; 2 arguments—sets its value

See page 177 for discussion and examples.

sp_dboption

Included for backward compatibility. Use ALTER DATABASE.

sp_help [objname]

No arguments—lists all objects in the current database.

1 argument—reports information about the database object in the current database.

sp_helpdb dbname

Reports information about a specified database or all databases.

sp_helpindex tablename

Reports indexes on the table or view.

sp_helptext objname

Prints the code text of a rule, a default or an unencrypted stored procedure, user-defined function, trigger or view.

sp_lock [spid]

Reports locks held by all processes or by spid (page 140).

sp_who

Reports all current users and processes connected to SQL Server.

xp_cmdshell

Executes a given command string as an operating system command shell and returns any output as rows of text.

xp_grantlogin

Grants a Microsoft Windows NT group or user access to Microsoft SQL Server.

xp_revokelogin

Revokes access from a Microsoft Windows NT group or user to Microsoft SQL Server.

Stored procedures are executed using the following syntax.

Syntax

[EXEC[UTE]]   sp_stored_procedure_name
   

EXEC or EXECUTE keyword is optional if this is the first statement in a batch.

2.7.1.1 The sp_ Procedures

The stored procedures provided by SQL server that begin with sp_ are predefined to provide administrative functions for managing SQL Server and displaying information about databases and users. Examples include the following: sp_helpdb, sp_help, sp_configure. See a complete list in Appendix A.

Example: Use sp_helpdb to display size and file information about pubs database.

SQL

EXEC  sp_helpdb  pubs
                  
 

Result

name       db_size       owner         dbid         created                             ...
-------    ----------    --------      ------       ----------                          ...
pubs       2.00 MB       sa            5            Aug 6 2000                          ...
name       fileid        filename                                                       ...
-------    ------        -----------                                                    ...
pubs       1             C:\Program Files\Microsoft SQL Server\MSSQL\data\pubs.mdf      ...
pubs_log   2             C:\Program Files\Microsoft SQL Server\MSSQL\data\pubs_log.ldf  ...

2.7.1.2 The xp_ Procedures—Provided

The procedures that begin with xp_, called extended stored procedures, allow creation of external routines in a programming language such as C. They are used to do work outside of SQL Server, such as accessing the registry, etc. A competent user may create his or her own extended stored procedures with sp_addextendedproc. Some examples include the following: xp_cmdshell, xp_grantlogin, xp_revokelogin. For more details, see Books Online Index: xp_.

Example: Use xp_cmdshell to show contents of C:\directory on server machine.

SQL

EXEC master..xp_cmdshell   'dir/w  C:\'
                  
 

Result

output
----------------------------------------------------------------------
Volume in drive C is AMY_C
Volume Serial Number is 2CA0-6A55
Directory of C:\
boot.ini   [Documents and Settings]   [HySnap]   [Inetpub]   [WINNT]
File(s)        189 bytes
4 Dir(s)   9,494,585,344 bytes free

Example: Display the names of database objects in the pubs database.

SQL

USE pubs
                  go
                  
                  EXEC sp_help      -- List all database objects in
                     graphics/ccc.gif pubs database
                  

Result

Name                                    Owner                  Object_type
------------------------------          ------------           ---------------
titlevie                                dbo                    view
authors                                 dbo                    user table
discounts                               dbo                    user table
employee                                dbo                    user table
...
titleauthor                             dbo                    user table
titles                                  dbo                    user table
syscolumns                              dbo                    system table
syscomments                             dbo                    system table
...
PK__jobs__117F9D94                      dbo                    primary key cns
PK_emp_id                               dbo                    primary key cns
UPK_storeid                             dbo                    primary key cns
UPKCL_auidind                           dbo                    primary key cns
...
FK__discounts__stor___0F975522          dbo                    foreign key cns
...
DF__authors__phone__78B3EFCA            dbo                    default (maybe cns)
...
CK__authors__au_id__77BFCB91            dbo                    check cns
...
User_type     Storage_type    Length     Prec   Scale      Nullable  Default_name Collation
------------  --------------- ---------  -----  ----       -----     -------      -------------------------------------
empid         char            9          9      NULL       no        none         SQL_Latin1_General_CP1_CI_AS
id            varchar         11         11     NULL       no        none         SQL_Latin1_General_CP1_CI_AS
tid           varchar         6          6      NULL       no        none         SQL_Latin1_General_CP1_CI_AS

Example: Display the metadata for the authors table of the pubs database including column names.

SQL

EXEC sp_help   authors      -- Show structure and
                  properties of "authors" table in pubs database
                  

Result

Name              Owner        Type            Created_datetime
------------      -------      ----------      -----------------------
authors           dbo          user table      2000-08-06 01:33:52.123

Column_name    Type         Computed          Length       Prec      Scale      Nullable
------------   -------      -------------     ---------    ------    -------    -----------
au_id         id            no                11                                no
au_lname      varchar       no                40                                no
au_fname      varchar       no                20                                no
...

2.7.2 DBCC

The initials DBCC stand for Database Console Command (a k a Database Consistency Checker before SQL Server 2K). DBCC statements check the physical and logical consistency of a database. Many DBCC statements can fix detected problems.

The four categories of DBCC statements and descriptions are shown in Tables 2-72 through 2-75 below. See Books Online for details.

2.7.2.1 DBCC Maintenance Statements

The commands listed in Table 2-72 will help you perform maintenance tasks on a database, index or filegroup.

Table 2-72. DBCC Maintenance Statements

DBCC DBREINDEX

Rebuilds one or more indexes for a table in the specified database.

DBCC DBREPAIR

Drops a damaged database.

NOTE: DBCC DBREPAIR is included in Microsoft SQL Server 2000 for backward compatibility only and may not appear in future versions. DROP DATABASE is recommended to drop damaged databases.

DBCC INDEXDEFRAG

Defragments indexes of the specified table or view.

DBCC SHRINKDATABASE

Shrinks the size of the data files in the specified database.

DBCC SHRINKFILE

Shrinks the size of the specified data file or log file for the related database.

DBCC UPDATEUSAGE

Reports and corrects inaccuracies in the sysindexes table. This may result in incorrect space usage reports by sp_spaceused.

2.7.2.2 DBCC Miscellaneous Statements

The commands in Table 2-73 will help you do miscellaneous tasks such as enabling row-level locking or removing a DLL from memory.

Table 2-73. DBCC Miscellaneous Statements

DBCC dllname (FREE)

Unloads the specified extended stored procedure dynamic-link library (DLL) from memory.

DBCC HELP

Returns syntax information for the specified DBCC statement.

DBCC PINTABLE

Marks a table to be pinned, which means Microsoft SQL Server does not flush the pages for the table from memory.

DBCC ROWLOCK

Does not affect the locking behavior of SQL Server 2K.

It is included for backward compatibility for SS 6.5 scripts and may not appear in future versions.

DBCC TRACEOFF

Disables the specified trace flag(s).

DBCC TRACEON

Turns on (enables) the specified trace flag.

DBCC UNPINTABLE

Marks a table as unpinned. After a table is marked as unpinned, the table pages in the buffer cache can be flushed.

2.7.2.3 DBCC Status Statements

The commands listed in Table 2-74 allow you to perform status checks.

Table 2-74. DBCC Status Statements

DBCC INPUTBUFFER

Displays the last statement sent from a client to Microsoft SQL Server.

DBCC OPENTRAN

Displays information about the oldest active transaction and the oldest distributed and nondistributed replicated transactions, if any, within the specified database. Results are displayed only if there is an active transaction or if the database contains replication information. An informational message is displayed if there are no active transactions.

DBCC OUTPUTBUFFER

Returns the current output buffer in hexadecimal and ASCII format for the specified system process ID (SPID).

DBCC PROCCACHE

Displays information in a table format about the procedure cache.

DBCC SHOWCONTIG

Displays fragmentation information for the data and indexes of the specified table.

DBCC SHOW_STATISTICS

Displays the current distribution statistics for the specified target on the specified table.

DBCC SQLPERF

Provides statistics about the use of transaction-log space in all databases.

DBCC TRACESTATUS

Displays the status of trace flags.

DBCC USEROPTIONS

Returns the SET options active (set) for the current connection.

2.7.2.4 DBCC Validation Statements

The commands shown in Table 2-75 allow you to perform validation operations on a database, table, index, catalog, filegroup, system tables or allocation of database pages.

Table 2-75. DBCC Validation Statements

DBCC CHECKALLOC

Checks consistency of disk space allocation structures of specified database.

DBCC CHECKCATALOG

Checks for consistency in and between system tables in specified database.

DBCC CHECKCONSTRAINTS

Checks integrity of a specified constraint or all constraints on the specified table.

DBCC CHECKDB

Checks the allocation and structural integrity of all the objects in the specified database.

DBCC CHECKFILEGROUP

Checks the allocation and structural integrity of all tables in the current database in the specified filegroup.

DBCC CHECKIDENT

Checks the current identity value for the specified table and, if needed, corrects the identity value.

DBCC CHECKTABLE

Checks the integrity of the data, index, text, ntext and image pages for the specified table or indexed view.

DBCC NEWALLOC

DBCC NEWALLOC is identical to DBCC CHECKALLOC which is recommended.

DBCC NEWALLOC is included in SS 2000 for backward compatibility and may not appear in future versions.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020