Home > Articles > Data > SQL Server

  • Print
  • + Share This
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.

  • + Share This
  • 🔖 Save To Your Account