 About the Northwind sample Microsoft Access project and Microsoft SQL Server database

About the Northwind sample Microsoft Access project and Microsoft SQL Server database

This topic provides reference information about:

Using the Northwind Traders sample Microsoft Access project

Creating the Northwind Traders Microsoft SQL Server database

Using the Northwind Traders sample Microsoft Access project

Microsoft Access provides a sample Microsoft Access project (NorthwindCS.adp) that is located in the \Program Files\Microsoft Office\Office\Samples folder called Northwind Traders. You can use this sample project while you're learning Microsoft Access. The project contains many of the same sample forms and reports found in the Northwind sample Microsoft Access database (Northwind.mdb).

By viewing the tables, queries, forms, reports, data access pages, macros, and modules included in the Northwind Access project, you can develop ideas for your own application. You can also use the Northwind data to experiment with Access before you enter your own data. For example, you might want to practice designing queries by using the Orders table because it contains enough records to produce meaningful results.

The Northwind Access project includes a Help file (click Show Me on the menu bar) that documents its main features.

Return to top

Creating the Northwind Traders Microsoft SQL Server database

Access can automatically create for you the NorthwindSQL Server database the first time you open the Northwind Access project. The Startup form first asks you to log on to SQL Server, looks for Microsoft Data Engine (MSDE) running on your computer and if it finds it, asks if you want to create the NorthwindCS SQL Server database so that you can connect to it. If the Startup form doesn't find MSDE running on your computer, it prompts you to enter a server name, user name, and password so you can connect to an SQL Server database on the network. In either case if you say yes, the Northwind sample Access project runs the SQL installation script (NorthwindCS.SQL), also located in the \Program Files\Microsoft Office\Office\Samples folder. This SQL script is a sequence of SQL statements that creates the SQL Server database data structure, properties, views, and database diagrams, and loads the sample data. Once the script has finished running, the Northwind sample Access project connects to the newly-created SQL server database.

Return to top


 About using Microsoft SQL Server database utilities from Microsoft Access

About using Microsoft SQL Server database utilities from Microsoft Access

From a Microsoft Access project, you can perform the most common administrative tasks on a Microsoft SQL Server database, such as backing up or securing a database, by using several database utility commands that are a subset of SQL Enterprise Manager, the SQL Server database administrator component. These commands are visible when you install Microsoft Office 2000, but you cannot use these commands unless you have also installed Microsoft Data Engine (MSDE) or Microsoft SQL 7.0 on your computer.

You can do the following:

Administrative task | Command
Backup your SQL Server database | Backup (Tools menu, Database Utilities)
Restore your SQL Server database from a previous backup | Restore (Tools menu, Database Utilities)
Delete an SQL Server database | Drop SQL Database (Tools menu, Database Utilities)
Secure your SQL Server database | Database Security (Tools menu, Security)
Manage your SQL Server database replica Learn about SQL Server replication. | Synchronize Now (Tools menu, Replication) Create Publication (Tools menu, Replication) Pull Subscription (Tools menu, Replication) Push Subscription (Tools menu, Replication) Subscription Properties (Tools menu, Replication) Publisher Properties (Tools menu, Replication) Resolve Conflicts (Tools menu, Replication)

For more information on how to perform these administrative tasks, see the SQL Server Enterprise Manager Help (entmgr.chm) and Replication Wizard Help (replwiz.chm) located in the \Windows\Help folder. You can also get Replication Wizard help by pressing Help in the Wizard dialog boxes.

Note The Compact and Repair Database command (Tools menu, Database Utilities) compacts and repairs an Access project, and is not part of SQL Server Enterprise Manager, which has its own compact and repair function.


Create an Access project

What do you want to do?

Create a Microsoft Access project that is connected to an existing Microsoft SQL Server database

Create an Access project that is not connected to a Microsoft SQL Server database

Create a SQL Server database and connect an Access project to it

Connect an existing Microsoft Access project to an existing Microsoft SQL Server database

Not sure which choice you want?


 Open an Access project

Open an Access project

  1. On the File menu, click Open [image] .

  2. Click a shortcut on the Places Bar, or, in the Look In box, click the drive or folder that contains the Microsoft Access project that you want.

  3. In the folder list, double-click folders until you open the folder that contains the Access project.

    If you can’t find the Access project that you want to open, click Tools, and then click Find [image] . In the Find dialog box, enter additional search criteria. For Help on an option, click the question mark [image], and then click the option. Learn more about searching for files.

  4. Click the Access project that you want to open, and then do one of the following:
    • To open the Access project, click Open.

    • To open the Access project for read-only access, click the Open arrow, and then click Open Read-Only.

    You can open an Access project only in exclusive mode. If you attempt to open an Access project while another user has it open, Access prompts you to open a read-only copy of the file.

    For Help on an option in the dialog box, click the question mark [image], and then click the item.

Notes

  • To view in the Open dialog box a list of shortcuts to Access projects that you have opened previously, click History [image] on the Places Bar. You can also click the file name at the bottom of the File menu. If the list of recently used files isn’t displayed, click Options on the Tools menu, click the General tab, and then select the Recently used file list check box.

  • Microsoft Access can automatically create a shortcut in the Favorites folder and use that shortcut to open the Access database or Access project directly the next time. You can also create a shortcut manually.

  • When you open an Access project in read-only mode, you can still add or modify data, and create or modify tables, views, database diagrams, or stored procedures, because the data and these objects reside in the Microsoft SQL Server database. However, you can’t create or modify forms, reports, macros, or modules, because these objects reside in the Access project.


 Connect an Access project to a Microsoft SQL Server database

Connect an Access project to a Microsoft SQL Server database

You can connect a Microsoft Access project to a Microsoft SQL Server 6.5, Microsoft SQL Server 7.0, or Microsoft Data Engine (MSDE) database. If the Access project is already connected to a Microsoft SQL Server database, you can change that connection.

  1. Open the Access project that you want to connect to a Microsoft SQL Server database.

  2. On the File menu, click Connection.

  3. On the Connection tab in the Data Link Properties dialog box, enter a server name and the information necessary to log on to the server, and then select the database on the server. For additional information, click Help in the Data Link Properties dialog box.

Note If you are using MSDE on a personal computer, the default server name is the name of your computer, and the default logon ID is sa. Learn more about using MSDE.


 Control the number of records retrieved in a form or datasheet in a Microsoft Access project

Control the number of records retrieved in a form or datasheet in a Microsoft Access project

To improve performance, you can set the maximum number of records downloaded from an SQL Server database when working with data in a form or datasheet in a Microsoft Access project.

  1. Click maximum record limit [image] to the right of the navigation buttons.

  2. Adjust the slider to reset the limit. You can type in a specific value in the text box.

    Note Dragging the slider all the way to the right sets the limit to "No Limit." Be cautious doing this — it could decrease the performance of your Access project — , especially if the recordset of the form or datasheet is large.

    Tip If you set the maximum record limit to a high value, and the download operation takes a long time, you can cancel the operation by clicking Cancel Query [image] or pressing CTRL+BREAK.

Notes

  • If you are using a form, Microsoft Access saves the setting with the form if you adjust the setting. The default maximum record limit is 10,000 for all new forms and datasheets, but you can change the default limit. On the Tools menu, click Options, click the Advanced Tab, and change the default number in the Default max records text box. Entering a value of 0 means that there is no limit. You can also set the default value for an individual form by using the MaxRecords property.

  • Microsoft Access displays the maximum record limit button by default, but you can hide this button by setting the MaxRecButton property of a form or datasheet to False.

  • Access loads records from the Microsoft SQL Server database asynchronously, which means you can interact with Access before all the records are retrieved. Access displays the number of records it is loading from the SQL Server database next to the maximum record limit button.


Ways to get assistance while you work

This topic provides reference information about:

Asking for Help from the Office Assistant

Getting Help from the Help menu

Getting Help from the Office Update Web site

Finding out what's new in Access 2000

More information

Asking for Help from the Office Assistant

When you have a question about a Microsoft Office program, you can ask the Office Assistant. For example, to get Help about how to format a chart, type How do I format a chart? in the Assistant.

If the correct topic doesn't appear in the Assistant balloon, click None of the above, look for more help on the Web at the bottom of the list of topics. You will get suggestions on how to phrase a question to the Office Assistant or how to narrow your search by using keywords. If you still can't find the information you want, you can send feedback to improve future versions of Help and be automatically connected to the Microsoft Office Update Web site to search for help there.

The Assistant automatically provides Help topics and tips on tasks you perform as you work — before you even ask a question. For example, when you design a report, the Assistant automatically displays topics for helping you create and design a report.

The Assistant also displays tips on how to use the features in the Office programs more effectively. Click the light bulb [image] next to the Assistant to see a tip.

You can also select a different Assistant and set it to operate so that it matches your personality and the way you work. For example, if you prefer using the keyboard to using the mouse, you can have the Assistant display tips on shortcut keys. Because the Assistant is shared by all Office programs, any options you change will apply to the Assistant in your other Office programs as well.

Return to top

Getting Help from the Help menu

Just click Microsoft Access Help on the Help menu. If the Assistant is turned on, it appears. If the Assistant is turned off, the Help window appears. To type a question in the Help window, click the Answer Wizard tab. To scroll through a table of contents for Help, click the Contents tab. When you want to search for specific words or phrases, click the Index tab.

To see a ScreenTip for a menu command, toolbar button, or screen region, click What's This? on the Help menu and then click the item you want information about.

To see a ScreenTip for a dialog box option, click the question mark button [image] in the dialog box, and then click the option. (If you don't see the question mark button, select the option and then press SHIFT+F1.)

To see the name of a toolbar button, rest the pointer over the button until the name appears.

Return to top

Getting Help from the Office Update Web site

You can connect to the Microsoft Office Update Web site and other Microsoft Web sites directly from any Office program by using the Office on the Web command on the Help menu. For example, you can access technical resources and download free product enhancements — all without leaving the Office program you're working in.

Return to top

Finding out what's new in Access 2000

Discover the new features in Access 2000 that make the product easier to use, along with tips on how you can apply them in your work.

Return to top

More information

Connect to Microsoft technical resources

Display tips and messages through the Office Assistant

Get Help without the Office Assistant

Return to top


 Glossary

Glossary

A | Return to top
absolute positioning access key action action argument action list action row Active Server Pages (ASP) file ActiveX component ActiveX control ActiveX Data Objects (ADO) add-in ADO (ActiveX Data Objects) aggregate function aggregate query alias American National Standards Institute (ANSI) character set | American Standard Code for Information Interchange (ASCII) ANSI (American National Standards Institute) character set API (Windows application programming interface) application background Application Note argument array ASCII (American Standard Code for Information Interchange) ASP files asynchronous autoformat automatic link Automation Automation object
B | Return to top
back end BCP (Bulk Copy Program) binary data type bit data type bit mask bitmap BLOB (Binary Large Object) body Bookmark bound column bound control | bound HTML control bound hyperlink control bound object frame bound picture break mode breakpoint browser Build button builder built-in toolbar
C | Return to top
calculated control calculated field Call Stack (View menu) call tree candidate key caption section cascading event case-sensitive channel number char data type chart check box check constraint class class module class name class name (OLE) Clear All Breakpoints (Debug menu) client client/server code page code stub Code window collection column combo box | command bar command button command line comparison operator compile time component/ActiveX component compound control conditional compiler constant conditional expression conditional formatting conflict connection string constant constraint Continue (Run menu) continuous form control control containing a hyperlink Control menu criteria current record cursor data type custom dialog box custom properties dialog box custom toolbar
D | Return to top
data access page data access page Design view data access page properties Data Access Page window data definition data item data source control data type database database diagram database objects Database window data-definition query datasheet Datasheet view datetime data type DBCS (Double-Byte Character Set) DDE (dynamic data exchange) DDE channel debugging decimal data type Declarations section default | default control style default property default value Definition (View menu) delete query delimited text file Design Master Design view destination detail section (forms) detail section (reports) DHTML (Dynamic HTML) direct synchronization disabled control DLL (dynamic-link library) docked document properties domain domain aggregate function Double data type drop-down list box dynamic data exchange (DDE) Dynamic HTML (DHTML) dynamic-link library (DLL)
E | Return to top
echo embed (insert) Empty End (Run menu) equijoin escape character event event procedure | event property exclusive expand control expand indicator export expression external database external table
F | Return to top
field field list field selector File Transfer Protocol (FTP) Fill fill factor filter Filter By Form Filter By Selection Filter Excluding Selection Filter For Input fixed positioning fixed-width text file float data type floating focus font | foreign key form form Design view form footer form header form module form properties form selector Form view Form window format Formatting toolbar Formatting toolbar (Page) FTP (File Transfer Protocol) full outer join Function procedure
G | Return to top
GIF (Graphics Interchange Format) global default global menu bar global replica global shortcut menu Graphics Interchange Format (GIF) grid (Datasheet view) grid (Design view) | Grid button group filter control group footer group header group level grouped controls grouped data access page Groups bar
H | Return to top
handle history list hotspot image control HTML (Hypertext Markup Language) HTTP (Hypertext Transfer Protocol) HTX files hub | hyperlink hyperlink address hyperlink base hyperlink field Hypertext Markup Language (HTML) Hypertext Transfer Protocol (HTTP)
I | Return to top
IDC files identifier (expressions) identifier (Visual Basic) image control image data type IME (Input Method Editor) Immediate window import import/export specification Indent (Edit menu) index indirect synchronization inline positioning inner join | in-place activation Input Method Editor (IME) input source Insert query Insert Values query instance int data type Integer data type Internet Internet synchronization intranet intrinsic constant item
J-K | Return to top
Jet and Replication Objects (JRO) join join condition join operator Joint Photographic Experts Group (JPEG) Journal (Outlook Bar) | JPEG (Joint Photographic Experts Group) JRO (Jet and Replication Objects) junction table key keyboard handler keyword
L | Return to top
label language folder Layout Preview left outer join library database Line/Border Width button link (OLE/DDE) linking table list box | list index literal local object local replica locale Locals window locked Long data type
M | Return to top
macro macro group Macro window main form make-table query manual link many-to-many relationship marquee maximum record limit menu menu bar menu bar macro metafile method Microsoft Access database Microsoft Access data file Microsoft Access object Microsoft Access project | Microsoft Data Engine (MSDE) Microsoft Download Service Microsoft Knowledge Base Microsoft Network Microsoft Office Web Components Microsoft Script Editor Microsoft Software Library Microsoft Visual Basic Microsoft Visual Basic Scripting Edition (VBScript) modal module module level module-level variable money data type Move mode MSDE (Microsoft Data Engine) multiuser (shared) database My Computer
N | Return to top
navigation buttons Navigation mode nchar data type New Object button ntext data type | Null null field numeric data type numeric expression nvarchar(n) data type
O | Return to top
object Object Browser Object data type object library Object list object-naming rules Objects bar ODBC (Open Database Connectivity) ODBC Connection String Builder ODBC data source ODBC database ODBCDirect Office Links button OLE OLE container | OLE DB OLE DB Provider OLE object OLE server OLE/DDE link one-to-many relationship one-to-one relationship Open Database Connectivity (ODBC) operator option button option group Outdent (Edit menu) outer join Outlook Bar
P-Q | Return to top
page (HTML) page footer (forms) page footer (reports) page header (forms) page header (reports) Page view parameter partial replica PivotTable list pixel plus pointer point pop-up form preview primary key primary table | Print Preview private procedure procedure Procedure (Insert menu) procedure level procedure-level variable project property property pages property sheet public variable publication publish query question-mark pointer Quick Watch (Debug menu)
R | Return to top
real data type record record navigation control record navigation section record navigation toolbar record number box record selector record source recordset referenced database referencing database referential integrity reflexive relationship refresh relationship relative link relative positioning repaint replica replica set | replication report report Design view report footer report header report module report selector report snapshot Report window Reset (Run menu) result set right outer join row row selector rule ruler run time run-time error
S | Return to top
schema scrolling text control search condition search page section section selector select query selected control selection rectangle self-join separator server Server Filter By Form server-generated HTML shared database shortcut key shortcut menu Single data type single stepping sizing handle smalldatetime data type smallint data type smallmoney data type Snap To Grid snapshot Snapshot Viewer Snapshot Viewer control sort order Sorting And Grouping box (data access pages) Sorting And Grouping box (reports) Special Effect button spreadsheet SQL (Structured Query Language) | SQL database SQL string/statement standard module start page statement status bar Step Into (Debug menu) Step Out (Debug menu) Step Over (Debug menu) stored procedure string string comparison String data type string delimiter string expression Structured Query Language (SQL) Sub procedure subdatasheet subform subform/subreport control submenu subquery subreport subscribe subscription subset surrogate key synchronization syntax error sysname data type system object
T | Return to top
tab control tab order table table Design view text box text data type text query (Microsoft Knowledge Base) theme timestamp data type tinyint data type title bar Toggle Breakpoint (Debug menu) | toggle button toolbar toolbox ToolTips topic topology transaction transaction log trigger twip type library
U-V | Return to top
unbound control unbound form or report unbound object frame UNC (Universal Naming Convention) unenforced relationship Unicode Uniform Resource Locator (URL) union query uniqueidentifier data type unique constraint Universal Naming Convention (UNC) update update query updateable snapshot URL (Uniform Resource Locator) user-defined collection | user-defined data type user-defined function user-defined object validation value varbinary data type varchar (n) data type variable Variant VBScript (Visual Basic Scripting Edition) verb view (object) View button visibility Visual Basic Editor
W-Z | Return to top
watch expression Watch pane Watch window Web Page Preview What's This button What's This tip WHERE clause | wildcard character Windows application programming interface (API) wizard World Wide Web zero-length string Zoom box
 | Return to top


 Ways to filter records in a form, report, or datasheet

Ways to filter records in a form, report, or datasheet

The type of filter that you create depends on whether you want to filter records at the server before they are retrieved from the database, or locally after they are retrieved. It also depends on the type of object for which you're creating the filter.

This topic provides reference information about:

Ways to filter records before they are retrieved from the database

Ways to filter records after they are retrieved from the database

Ways to filter records before they are retrieved from the database

For forms and reports, there are a number of ways that you can filter records at the server before they are retrieved from the database. By filtering records at the server, you can improve the form or report's performance. Besides basing the form or report on a query that includes criteria (search conditions) to limit the records, you can:

Define a specific filter in the ServerFilter property of the form or report. When you or others open the form or report, it contains only the records that meet the criteria that you specified in the ServerFilter property. You can't change the filter unless you change the property or use the filtering techniques described below to limit the records once they are local.

Prompt for a different filter each time you open a form in Form view or Datasheet view. You do this by setting the form's ServerFilterByForm property to Yes. Then, when you switch to Form view or Datasheet view, Microsoft Access displays the Server Filter By Form window, which is a copy of the form (or datasheet) that you are filtering, but without records. In the form, you can specify different criteria by choosing your search values from drop-down lists in each field. When you apply the filter, Microsoft Access sets the ServerFilter property to the filter you defined in the Server Filter By Form window.

Note You can't use Server Filter By Form with a form bound to a stored procedure. Consider using parameters in the stored procedure, and then setting the form's InputParameters property to bind the parameters to the form.

Return to top

Ways to filter records after they are retrieved from the database

For forms and datasheets, you can filter records after they've already been retrieved. This is true even for forms that were initially filtered at the server. Once the records are displayed, you can use these local filtering techniques to limit the records:

Filter By Form displays a copy of the form (or datasheet) that you are filtering, but without records. You can specify different criteria each time you use the form or datasheet by choosing your search values from drop-down lists in each field or by specifying an expression. There's no need to scroll through all the records in a datasheet or form, and you can specify multiple criteria at once.

Filter By Selection finds records with a field containing all or part of a value you selected in that same field on a form, subform, or datasheet. If you want to further limit the records, you can continue selecting other values or partial values. Each time you apply the filter, it uses the previous values that you selected and any subsequent values to determine the filtered set of records.

Filter For Input displays an area on the shortcut menu where you can type the exact value that you're searching for in the current field or the expression whose result you want to use as your criteria.

Return to Create a filter for a table, query, form, or report.

Return to top


Create a filter for a table, query, form, or report

With a filter, you can limit the records to a specific subset that you want to view or work with. You can filter records at the server before they are retrieved from the database, or on your local machine after they are retrieved.

What do you want to do?

Limit records before they are retrieved from the database

Enable Server Filter By Form to prompt for filter criteria each time you view a form

Create a filter in the Server Filter By Form window in a form

Create a specific filter that's automatically applied when a form or report is opened

Limit records after they are retrieved from the database

Create a filter in Datasheet view or Form view using Filter By Selection

Create a filter in Datasheet view or Form view using Filter By Form

Create a filter in Datasheet view or Form view using Filter For Input

Not sure which choice you want?


 Apply a filter in a table, query, or form

Apply a filter in a table, query, or form

Do one of the following:

To apply a filter in Form view, datasheet view, or the Filter By Form window

  • Click Apply Filter [image] on the toolbar.

To apply a filter from the Server Filter By Form window

  • Click Apply Server Filter [image] .

Notes

  • Microsoft Access can apply a filter automatically when you open a form if you set the form's OnOpen property to a macro that uses the ApplyFilter action or to an event procedure that uses the ApplyFilter method of the DoCmd object, or by setting the form's ServerFilter property without enabling Server Filter By Form.

  • If you create a local filter in a form or subform that already contained a filter from a previous working session, the new filter replaces the previous one.


 Remove a filter from a table, query, or form

Remove a filter from a table, query, or form

The following procedures do not apply to a filter that was created in the Server Filter By Form window. You can only delete a filter created using Server Filter By Form, you can't temporarily remove it and reapply the same one later on.

  • To remove a filter and show the records that were displayed previously in the table, query, or form, click Remove Filter [image] on the toolbar in Datasheet view or Form view.

  • To remove a filter in a multiuser (shared) database and see which records have been added, deleted, or changed since you opened the table, query, or form, click Remove Filter/Sort on the Records menu in Datasheet view or Form view.

Notes

  • Removing a filter doesn't delete it. You can reapply the filter by clicking Apply Filter [image] on the toolbar.

  • If you prefer, you can use the ShowAllRecords action in a macro or Visual Basic for Applications code to remove the filter.


 Reapply a filter to retrieve the most current set of records

Reapply a filter to retrieve the most current set of records

If you're working in a multiuser (shared) database, you may want to reapply the filter occasionally to see which records have been added, deleted, or changed since you opened the form or datasheet and applied the filter.

To reapply a filter that you created using Filter By Selection, Filter By Form, or Filter For Input

  • With the filtered records displayed in a datasheet, form, or subform, click Apply Filter/Sort on the Records menu.

To reapply a filter that you created using Server Filter By Form

  • Click Server Filter By Form [image] on the toolbar to redisplay the window, and then click Apply Server Filter [image] on the toolbar.


 Delete a filter in the Server Filter By Form window and display all records

Delete a filter in the Server Filter By Form window and display all records

  1. In the Server Filter By Form window, click Clear Grid [image] on the toolbar

  2. Click Apply Server Filter [image] on the toolbar.

    If you don't want to filter records at the server, you can disable the Server Filter By Form window.


 Enable or disable filtering records in a form

Enable or disable filtering records in a form

  • Display the property sheet for the form, then set the AllowFilters property to Yes to enable filtering or to No to disable filtering capabilities in Form view and in form Datasheet view.

Note When you set the AllowFilters property to No, you disable Filter By Selection, Filter By Form, Server Filter By Form, and Filter For Input.


 Enable or disable using Server Filter By Form to limit records before they are retrieved for a form

Enable or disable using Server Filter By Form to limit records before they are retrieved for a form

You can't use Server Filter By Form with a form bound to a stored procedure.

  1. Open a form in Design view.

  2. Display the property sheet for the form.

  3. Do one of the following:
    • To enable Server Filter By Form, set the ServerFilterByForm property and AllowFilters property to Yes.

    • To disable Server Filter By Form, set the ServerFilterByForm property to No.
  4. Switch to Form view or the form's datasheet view to test using Server Filter By Form.

Note When you enable Server Filter By Form, Microsoft Access disables Filter By Form.


Troubleshoot filters in tables, queries, and forms

What do you need help with?

Why are some of the fields in the Filter By Form or Server Filter By Form window unavailable?

Why do the lists in the Filter By Form or Server Filter By Form window take so long to display?

I don't have lists of values to pick from on one or more of the fields in the Filter By Form or Server Filter By Form window. Why not?

The lists in the Filter By Form window or Server Filter By Form window include some but not all the values from the fields

The local filter didn't return all the records that meet the criteria I specified


 Ordering Query Results

Ordering Query Results

Though you can't specify a sort order in the Query Designer for a view, you can for an SQL statement stored in the RecordSource property of a form or report. You can also specify a sort order in a stored procedure using an ORDER BY clause in a SELECT statement. You can order your query by the contents of a data column or by an expression. The Query Designer allows you to specify the sort types ascending and descending.

You can also order the query results by more than one column or expression and specify the sort order for each. For example, if you are querying an employee table, you can order the results by department (sort order = 1) and within each department by last name (sort order = 2).

Note You cannot sort by the contents of a Text or Image column.

To order query results

  1. If you have not already, add the columns or expressions that you want to sort by to the Grid pane.

    If you don’t want the columns or expressions to be part of the query results, remove them as output columns.

  2. In the Grid pane, locate the row containing the first data column or expression to sort by, and then in the Sort Type grid column, choose Ascending or Descending.

  3. If you are sorting by multiple columns or expressions, specify the sort order in the Sort Order column of the grid.


 Ways to sort records in a table, query, form, or report

Ways to sort records in a table, query, form, or report

Whether you can sort records at the server before records are retrieved or locally on your computer after records are retrieved depends on the object you're working with. The results of sorting at the server versus sorting locally can vary. This is because the local sort order is determined by the Regional settings in Control Panel, whereas the server sort order is determined by the settings specified when SQL Server was installed.

This topic provides reference information about:

Sorting records before they are retrieved from the database

Sorting records after they are retrieved from the database

Sorting records before they are retrieved from the database

You can sort records at the server by using a stored procedure, or a SQL statement in the RecordSource property of a form or report. You sort the records by including an ORDER BY clause in the query's SELECT statement. When you specify a sort order this way, you can perform complex sorts, which means you can sort records in ascending order by some fields and in descending order by others. Each time you view the results of a stored procedure or SQL statement, the sort order is automatically applied. To sort data when the record source is a view or table, you must use the local sorting technique described next.

Return to top

Sorting records after they are retrieved from the database

You can sort records locally in Form view of a form, or in Datasheet view of a table, query, or form. You do this by using the Sort buttons on the toolbar or by setting the OrderBy property in Design view. For reports, you can sort groups of records using the Sorting and Grouping box, or you can sort on all records by setting the report's OrderBy property in Design view.

When you use the Sort buttons, you can perform simple sorts, which means you can sort all records in ascending or descending order (not both). When you set the OrderBy property directly, you can sort records in ascending order by some fields and in descending order by others. Microsoft Access saves the local sort order that you specify in a form or report, and applies it automatically when you open the object. The local sort order for a table or query is not saved; however, if you create a form or report from the sorted table or query while it's open, the new form or report will inherit the sort order.

Return to top

Return to Sort records in a table, query, form, or report


Sort records in a table, query, form, or report

You can sort records at the server before they are retrieved from the database or on your local computer after they are retrieved. The way you sort records depends on the object you're working with.

What do you want to do?

Sort records before they are retrieved from the database

Sort records in a stored procedure, or in a SQL statement in the RecordSource property of a form or report

Sort records after they are retrieved from the database

Sort records in Datasheet view or Form view

Not sure which choice you want?


 Remove a local sort order from a table, query, or form

Remove a local sort order from a table, query, or form

  • In Datasheet view or Form view, click Remove Filter/Sort on the Records menu.


 Database Diagram Designer

Database Diagram Designer

The Database Diagram Designer is a visual tool allowing you to create, edit, or delete tables, columns, indexes, defaults, constraints, and relationships for databases while you’re directly connected to the database in which those database objects are stored.

You interact with the server database using database diagrams. Database diagrams graphically represent the tables in your database. These tables display the columns they contain, the relationships between the tables, and indexes and constraints attached to your tables. When you establish a connection to a database, you can use database diagrams to:

  • View the tables in your database and their relationships.

  • Perform complex operations to alter the physical structure of your database.

    Note You can also create or modify a single table in table Design view; however, Microsoft Access Help focuses on designing or modifying tables from a database diagram.

You can make changes freely in the database diagram without affecting the underlying database. When you modify a database object through a database diagram, the modifications you make are not saved in the database until you save the database diagram. Thus, you can experiment with "what if" scenarios on a database’s design without permanently affecting its existing design or data.

You control the timing, type, and extent of the changes to your database by choosing how changes to the database diagram affect the server database.

Creating and Managing Database Diagrams

You can use database diagrams to:

  • Manipulate database objects without having to write SQL code.

  • Visualize the structure of your database tables and their relationships.

  • Provide different visualizations of complex databases.

  • Experiment with database changes without modifying the underlying database.

  • Create new tables, indexes, relationships, and other constraints.

  • Alter the structure of your database.

For example, you can create a database diagram for your company’s payroll department that shows only tables that hold employee benefits information. Or you can create a diagram for your development team that shows only those tables that are used in a specific application module.

You can change the size, shape, and position of objects in your diagram without affecting their definitions in the database. When you save your database diagram, the layout of your diagram is preserved as well as any changes you made to the object definitions in your diagram.

The Database Diagram Designer does not require additional security features set up separately from the security features in your database. Database diagrams are saved in the dtproperties or MicrosoftDTProperties table of your database.

For information about | See
Creating, saving, formatting database diagrams | Working in Database Diagrams
Working with multiple users and reconciling changes with a modified database | Working in a Multi-User Environment
Creating, editing, deleting database objects in a database diagram | Working with Database Objects

Creating and Modifying Database Objects

Tables are the basic building blocks of database diagrams. Every diagram is made up of one or more tables and the various objects related to those tables.

Each table has a set of columns that contain information about the type of data that you will store in the table. You must define at least one column in order to save a table in the database. Each column must have a column name, an assigned data type, and an assigned length. These and other properties can be defined in your database diagram. You modify tables and their columns directly in a database diagram.

A table can also have a set of constraints and indexes. Because constraints and indexes are defined for a specific table, they are treated as properties of that table in a database diagram. You use the property pages to create, modify, or delete these database objects for a table.

You can use the Database Diagram Designer to create and modify database objects, including:

  • Tables

  • Columns

  • Table Relationships

  • Indexes

  • Constraints

For more information about creating and modifying database objects, see Working with Database Objects.


 Working in Database Diagrams

Working in Database Diagrams

You can perform two types of operations in database diagrams:

  • Operations that modify the structure of your database.

  • Operations that modify the graphical layout of the tables and relationships in your diagram without affecting the definition of those objects in your database.

When you save a database diagram, your changes to the definitions of your database objects, as well as your changes to the graphical layout of your diagram, are saved in the dtproperties or MicrosoftDTProperties table of your database.

Modifying the Structure of Your Database Using Database Diagrams

You can create database diagrams of varying complexity, from diagrams that contain just one table to diagrams that contain hundreds of tables. When you first create a diagram, you are presented with a blank diagram surface to which you can add tables.

To | See
Create a new database diagram for your project | Creating a Database Diagram
Add tables to the database diagram, edit column properties, create relationships between tables, create indexes, and create constraints | Working with Database Objects
Update the database using database diagrams | Controlling Database Changes

You interact with database diagrams by using commands available in menus and on the Database Diagram Designer toolbar:

Working with a Single Table in the Database

When you want to work with only one table, you can either create a database diagram for that table or you can create the table in table Design view. When you create, open or design a table in table Design view, you can only work with that table. Design view is like Column Properties view for a table in a database diagram.

In this single-table mode, you can define the properties of a new table, adding columns and column properties. When you save the new table, it is added to your database and to the list of tables in the Database window. You can then easily add this table to existing or new database diagrams.

Laying Out Tables Graphically Using Database Diagrams

You can perform a variety of diagramming operations in a database diagram without affecting the object definitions in your database. You can customize the appearance of your diagram to meet your development needs in the following ways:

To | See
Arrange tables automatically | Arranging Tables Automatically
Use the keyboard or mouse to move around in a diagram | Navigating a Database Diagram
Change the size and shape of tables | Changing a Table View and Adjusting the Table Size
Remove tables from the diagram without deleting them from the database | Removing a Table from a Database Diagram
Change the magnification of a diagram, zoom to fit selected items in a diagram | Zooming a Database Diagram
Print and preview your database diagram | Printing and Previewing Database Diagrams
Open the Properties pages to edit properties for the objects in your diagram | Setting Properties in a Database Diagram
Divide and merge diagrams to make managing parts of the database easier | Subdividing a Database Diagram and Merging Subdiagrams into a Master Diagram
Select and move tables and relationship lines in a diagram | Selecting Multiple Objects in a Database Diagram

These operations affect the appearance of your diagram, but they do not affect the structure of your database.


 Database Diagram Window

Database Diagram Window

The Database Diagram window presents a graphic display of the tables and relationships in your database.

Note To create or modify a single table outside of a database diagram, you can use table Design view.

Database diagram with tables and relationship lines

In the Database Diagram window, you can:

  • Add tables to the database diagram by dragging them from the Show Table list.

  • Remove tables from the diagram or delete them from the database.

  • Save selected tables, or the entire database diagram.

  • Create, edit, or delete relationships between tables.

    Dragging a column from one table to another to create the relationship line

  • Create, edit, or delete tables and table column definitions.

  • Open the property pages to edit objects shown in the diagram, or to create, edit, or delete database objects such as indexes and constraints that are not graphically represented in the diagram:

    Property Pages for a table

  • Lay out the objects shown in the diagram by changing the table view. Five pre-defined table views are available as shown below. For more information, see Changing a Table View.

    Five views of tables in a database diagram

  • Change the arrangement of the objects in the database diagram by automatically arranging the tables, expanding and collapsing the tables by changing the column view, and by rearranging relationship lines. For more information, see Formatting a Database Diagram.

When you save a database diagram, the database is updated to match your diagram. The diagram is available from the Database window. To see it, click Diagrams [image] under Objects in the Database window, click the diagram name, and then click the Design button on the Database window toolbar. The diagram is also saved in the dtproperties or MicrosoftDTProperties table of your database.

If you close a diagram without saving it, the underlying database remains unchanged.

For more information about database diagrams, see Working in Database Diagrams.


 Working with Database Diagram Objects

Working with Database Diagram Objects

You can easily manage your database graphically through database diagrams. You can use database diagrams to create, edit, manage, or delete database objects (tables, table columns, table relationships, and constraints) while you’re directly connected to the database in which those objects are stored. In the diagram, you can easily see the relationship between the objects in your database. You can also define and edit the properties of the database objects all from within your database diagram.

The tables represented in your diagrams are merely references to tables that reside in the database. An individual database table can exist in more than one database diagram. Thus, a table that appears in many database diagrams actually exists in only one place, the server database itself.

A database diagram

When you modify a table in a database diagram, your modifications are immediately applied to that table in every other diagram that it appears in. Similarly, when you remove a table from a database diagram, it is also removed from the other diagrams that it appears in. Therefore, if you delete a table in a multi-user environment, the table will be removed from the database diagrams of all other users.

When you save a database diagram, all changes you made to the tables in your diagram and their related objects are saved in the server database.

In most databases, if you perform any of the following actions on a database table, the table will be automatically recreated in your database when you save the table or the database diagram. The table must be recreated in the database in order for your database to accept your changes.

  • Change the properties of an existing column.

  • Append a column that doesn’t allow nulls to the end of an existing table.

  • Add a column in the body of an existing table.

  • Reorder existing columns.

  • Delete an existing column.

When you save a table on which you’ve performed any of these actions, any triggers, bound defaults, and rules associated with each table are also saved.

For information about | See
Creating tables, changing the table view, adjusting table size, duplicating tables, adding columns to tables | Tables
Inserting, moving, deleting columns in database tables and setting properties for those columns | Columns in a Database Table
Defining relationships and enforcing referential integrity between tables | Table Relationships
Creating indexes to make accessing the information in your tables easier | Indexes
Working with constraints to limit the values that can be entered in tables | Constraints


 Database Diagram Designer Considerations for SQL Server Databases

Database Diagram Designer Considerations for SQL Server Databases

If you are creating database diagrams using Microsoft® SQL Server™, you can take advantage of features specific to that server. The following guidelines outline differences you will notice in the Database Diagram Designer when you work with SQL Server, and provide information about SQL Server-specific features that you can use.

Below you will find information about:

  • SQL Server Version

  • Case Sensitivity

  • Full-Text Indexes

  • Changing Column Properties

  • Enforced and Unenforced Table Relationships

SQL Server Version

The Database Diagram Designer is designed to support Microsoft SQL Server versions 6.5 and 7.0.

Case Sensitivity

Column and table names in a SQL Server database can be stored in uppercase letters, lowercase letters, or a combination of both. For example, a column name can appear as "LASTNAME," "LastName," or "lastname."

Depending on how SQL Server was installed, databases can be case-sensitive or case-insensitive. If a database is case-sensitive, you must enter owner, table, and column names using the correct combination of uppercase and lowercase characters. If the case of the name you provide does not match exactly, SQL Server returns an error reporting an "invalid object name."

The objects in the Database window will not reflect the case sensitivity of your server. However, when entering column names in a database diagram, you must be careful to match names to the way they will be interpreted by the server.

Note The server's case sensitivity settings do not affect the names of objects stored in the Microsoft Access project (forms, reports, macros, and modules), or data access pages. If any of these objects reference table or column names from the SQL Server database, case sensitivity is ignored. Therefore, if your database is case-sensitive and you have objects with the same name but different case (Authors vs. AUTHORS, for example), you may get unexpected results because the Microsoft Access project won't distinguish between the two. In addition, any local sorting performed on data won't be case-sensitive.

If the server was installed with a case-insensitive option, you can enter database object names (owner, table, and column names) using any combination of uppercase and lowercase characters.

Tip To determine the case sensitivity of a server, execute the stored procedure sp_server_info, and then examine the contents of row 18. If the server has been installed with the case-insensitive setting, the option for sort_order will be set to nocase.

Full-Text Indexes

Through Index Server 2.0 shipped with SQL Server 7.0, you can implement full-text indexing. However, the Database Diagram Designer provides limited support for tables that contain full-text indexes. For example, when you add a table to a diagram or design a table that contains a full-text index, you will not be able to save changes that you make to that table. You can modify the table if you remove the index from the table before you attempt to use it in in the Database Diagram Designer.

For more information on full-text indexing, refer to the SQL Server 7.0 documentation.

Changing Column Properties

For information on the procedure you use to set column properties, see Setting Column Properties.

The following items contain information specific to Microsoft SQL Server databases.

  • Default Values for Data Types

  • Changing the Data Type Assigned to a Column

  • Changing the Column Length

  • Changing the Column Precision

  • Changing the Column Scale

  • Changing the Null Option Assigned to a Column

  • Assigning a Default Value to a Column

  • Redefining a Global Default

  • Changing a Column’s Identity Properties

Note In Microsoft SQL Server version 7.0, you have the ability to add computed columns in your tables. The Database Diagram Designer and table Design view do not support this feature. If you modify a table that has computed columns, these columns may be converted to actual columns. For more information, see "Using Computed and Calculated Columns" in your SQL Server documentation.

Default Values for Data Types

The following default values are automatically added for the new column:

Data Type | Description | Default value
Column Name | The name of a column in a table. Column names must conform to your database rules for identifiers and must be unique in the table. | Blank
Datatype | The data type of the column. System- or user-defined data types are acceptable. | Character (char)
Length | The maximum number of digits (for numeric data types) or characters allowed for values in the column. | 10
Precision | The maximum total number of decimal digits that can be stored, both to the left and to the right of the decimal point. | 0
Scale | The maximum number of decimal digits that can be stored to the right of the decimal point. This value must be less than or equal to the precision. | 0
Allow Nulls | Whether or not the column can accept null values. | Yes (checked)
Default Value | The value that will be inserted into the column if the user does not make an entry. Default values are ignored for columns with a timestamp data type. If you do not define a default value and a column allows nulls, NULL will be inserted. | Blank
Identity | Whether or not the column will generate incremental values for new rows based on the Identity Seed and Identity Increment settings. | No (not checked)
Identity Seed | The value assigned to the first row in the table. If left blank, this setting default is 1. | Blank
Identity Increment | The value which is added to the Identity Seed and assigned to the second row in the table. Each subsequent row is increased by this value. If left blank, this setting default is 1. | Blank

Changing the Data Type Assigned to a Column

A column's data type determines what kind of data can be stored in the column. A list of system-defined data types appears in the Datatype property column in Column Properties view.

You can choose the appropriate data type for the information you want to store in the column. If user-defined data types exist for your database, they appear at the end of the Datatype list. The system-defined data type that corresponds to the user-defined data type appears in parentheses at the end of the user-defined data type name. For example: "id (varchar)."

Special considerations for assigning a user-defined data type to a column

  • Selecting a data type automatically sets the length, precision, and scale for the column based on the data type’s definition. You cannot change these settings for user-defined data types.

  • You can change the Allow Nulls setting only if the user-defined data type allows null values.

  • When you select a user-defined data type, the Default Value setting is blank, even if a bound default is defined for the data type. You can check whether a bound default exists by saving the table and reloading it into memory. When you reopen the table, the bound default will appear in the Default Value cell. If you try to set a default value for a column that already has a bound default, an error message will prompt you to remove your entry.

For information about creating user-defined data types in Microsoft SQL Server, see "Creating User-Defined Datatypes" in SQL Server Books Online or Database Developer’s Companion.

Note Changing the data type recreates the table in the database when you save the table or diagram. For more information about automatically recreating tables, see Working with Database Objects.

Caution If this column is related to columns in other tables, then the data type of the related columns must also be changed to preserve referential integrity. When you save the table or diagram, the Datatype Change Required dialog box enables you to automatically change the data type of the related columns.

For information on Microsoft SQL Server data types, see the Transact-SQL Reference in Microsoft Access Help, SQL Server Books Online or Database Developer’s Companion.

Microsoft SQL Server 7.0 Data Types

Version 7.0 of SQL Server includes the following data type enhancements:

  • char, varchar, binary, varbinary

    Expanded maximum length of character and binary data to 8,000 bytes.

  • nchar, nvarchar, ntext

    New Unicode data types.

    Maximum length of (nchar, nvarchar) character data to 4,000 characters.

  • uniqueidentifier

    New data type for storing globally unique identifier (GUID).

For more information, see "New Data Types" in your SQL Server documentation.

Changing the Column Length

When you select a data type, the column length is automatically defined. You can reset the length property for a column with a data type of binary, char, varbinary, or varchar if you want to increase or decrease the length of acceptable values in that column. For columns with other data types, the length is derived from the data type.

Note Changing the column length recreates the table in the database when you save the table or diagram. For more information about automatically recreating tables, see Working with Database Objects.

Default Column Lengths for Microsoft SQL Server Data Types

Data type | Default length | Range of allowable length values
binary | 10 | 1 - 255
bit | 1 |
char | 10 | 1 - 255
datetime | 8 |
decimal | 9 |
float | 8 |
image | 16 |
int | 4 |
money | 8 |
numeric | 9 |
real | 4 |
smalldatetime | 4 |
smallint | 2 |
smallmoney | 4 |
sysname | 30 | 1 - 255
text | 16 |
timestamp | 8 |
tinyint | 1 |
varbinary | 50 | 1 - 255
varchar | 50 | 1 - 255

Changing the Column Precision

For most data types, the column precision is automatically defined. You can change the column precision for the decimal and numeric data types if you want to redefine the maximum number of digits these columns use. The precision of a numeric column refers to the maximum number of digits used by the selected data type. The precision of a non-numeric column generally refers to either the maximum length or the defined length of the column.

The Database Diagram Designer prevents you from changing the precision of a column that does not have one of these assigned data types.

Note Changing the column precision recreates the table in the database when you save the table or diagram. For more information about automatically recreating tables, see Working with Database Objects.

Changing the Column Scale

When you select a data type, the column scale by default is set to 0. The scale of a numeric column refers to the maximum number of digits to the right of the decimal point. For columns with approximate floating point numbers, the scale is undefined because the number of digits to the right of the decimal point is not fixed.

You can change the scale for a numeric or decimal column if you want to redefine the number of digits that can appear to the right of the decimal point.

Note Changing the column scale recreates the table in the database when you save the table or diagram. For more information about automatically recreating tables, see Working with Database Objects.

Changing the Null Option Assigned to a Column

For each column in your table, you can specify whether to allow null values or disallow null values. A null value, or NULL, is not the same as zero (0) or blank; NULL means that no entry has been made. Its presence usually implies that the value is either unknown or undefined. For example, a null value in the price column of the titles table of the pubs sample database does not mean that the book has no price; it means that the price is unknown or has not been set.

If null values are not allowed, the user entering data in the table must enter a value in the column or the table row cannot be accepted in the database.

Note You cannot change this property on a primary key column. If Allow Nulls is not checked, but null values are stored in that column, Microsoft® SQL Server™ will generate an error message when you try to save the table. Also, Identity columns can't have null values.

Changing the null option on a new, non-key column recreates the table in the database when you save the table or diagram. For more information about automatically recreating tables, see Working with Database Objects.

Assigning a Default Value to a Column

For each column in your table, you can specify a default value that will be entered in the column if the user leaves it blank. If you do not assign a default value and the user leaves the column blank, then:

  • If you set the option to allow null values, NULL will be inserted into the column.

  • If you did not set the option to allow null values, the column will remain blank.

For details on setting the Allow Nulls option, see Changing the Null Option Assigned to a Column.

For text strings, enclose the value in single quotation marks ('); do not use double quotation marks (") because they are reserved for quoted identifiers. For example, type: 98036 or 'Paris, France'.

If your entry in the Default Value column replaces a bound default (which is shown without parentheses), the default will be unbound and the new value will replace it.

Redefining a Global Default

A global default is one that is defined for a specific database and is shared by columns of different tables. For example, suppose several of your tables have a quantity column. You can define a global default in your database that inserts a value of 1 in the quantity column whenever the user leaves that column blank in any table.

If a global default is bound to a column, you can specify a different default value for that column in a specific table. In such a case, the existing global default is unbound from the column before the new default value is bound to the column.

To redefine a global default

  1. In your database diagram, assign a new default value to the column you want to change.

    For details about assigning default values, see Assigning a Default Value to a Column.

  2. A message prompts you to permanently unbind the existing default in order for the new default to be applied. Choose OK.

Changing a Column’s Identity Properties

You can change the identity properties of a column if you want to redefine the sequential numbers that are automatically generated and stored in that column when new rows are added to the table. You can set the identity properties on only one column per table.

Columns that have the Identity property contain system-generated sequential values that uniquely identify each row within a table (for example, employee identification numbers). When inserting values into a table with an identity column, Microsoft SQL Server automatically generates the next identifier based on the last used identity value (the Identity Seed property) and the increment value (the Identity Increment property) specified during the creation of the column.

The Identity property can be set only for a column with a data type of decimal, int, numeric, smallint, or tinyint; it must not allow null values; and it must not be bound by a default constraint.

To change a column’s identity properties

  1. In your database diagram, select the table in which you want to change the identity properties of a column.

  2. If you're not already in Column Properties view, right-click the table and choose Column Properties from the shortcut menu.

  3. If the Allow Nulls property is set, clear the check box.

  4. Check the box inside the Identity cell for the column whose values you want to automatically increment.

    Note Only one column per table can be defined as an identity column.

  5. Type a value in the Identity Seed cell. This value will be assigned to the first row in the table. If you leave this cell blank, the value 1 will be assigned by default.

  6. Type a value in the Identity Increment cell. This value is the increment that will be added to the Identity Seed for each subsequent row. If you leave this cell blank, the value 1 will be assigned by default.

For example, suppose you want to automatically generate a 5-digit Order ID for each row added to the orders table, beginning with 1000 and incremented by a value of 10. To do this, you would check the Identity property box, type an Identity Seed of 1000, and type an Identity Increment of 10.

If you change any of the identity properties for a table, the existing identity values will be preserved. Your new settings apply only to new rows that are added to the table.

Note If an identity column exists for a table with frequent deletions, gaps can occur between identity values. If you want to avoid such gaps, do not use the Identity property.

Enforced and Unenforced Table Relationships

In SQL Server, the following options are available when enforcing referential integrity:

For details about this option | See
Check existing data on creation | Checking Existing Data When Creating a Relationship
Enable relationship for INSERT and UPDATE statements | Disabling a Foreign Key Constraint with INSERT and UPDATE Statements
Enable relationship for replication | Disabling a Foreign Key Constraint for Replication


 Creating a Database Diagram

Creating a Database Diagram

You can use a database diagram to create, edit, or delete database tables. You can also use a database diagram to see how your tables relate to each other. When you create a new database diagram, you are presented with a blank diagram surface to work on.

To create a database diagram

  1. Make sure you’re connected to the database whose tables you want to edit.

  2. In the Database window, click Database Diagrams [image] under Objects, and choose the New button on the Database window toolbar.

  3. A blank database diagram appears. On the View menu, choose Show Table.

  4. Add tables to the diagram by dragging a table or one of its columns from the Tables folder in the Show Table list into the diagram. When you release the mouse button, the table appears on your diagram and valid relationship lines to other tables in the diagram are automatically drawn.

    -or-

    Create a new table in the diagram by right-clicking anywhere inside the diagram and then choosing New Table from the shortcut menu.

    For more information see Adding Tables to a Database Diagram.

  5. Arrange the objects in your diagram. For more information, see Formatting a Database Diagram.

If you want to move objects to different parts of your diagram — for example, to align the tables or reduce the number of overlapping relationship lines — first select the objects, and then drag the selection to its new location.

  • To select a table, click its title bar.

  • To select a set of tables, hold down the CTRL key as you click inside the title bar of each table in the set.

  • To select a set of tables grouped together, position the pointer near one of the tables and then drag a rectangle around all the tables in the set.

If you select multiple tables, the relationship lines that connect them are automatically included in the selection.

If you select a relationship line, you can slide a line segment to a location that is parallel to its original position. If the relationship line has more than one segment, you can drag a corner diagonally to change both its vertical and horizontal position.

For an overview of the elements that you can edit in a table, see Working with Database Objects.


Saving a Database Diagram

Save your database diagram to update the database with the changes you made to the diagram layout and the object definitions in the diagram.

To save a database diagram

  1. Click the Save button [image] on the toolbar.

  2. For a new database that hasn't been previously saved, the Save As dialog box appears. In the Save As dialog box, type a name for your diagram and choose OK.

  3. If you have made changes to tables in your diagram, the Save dialog box appears and displays a list of tables that will be saved in the database when you save your diagram. Choose Yes to update the database to match your diagram.

Database diagrams are saved in the dtproperties or MicrosoftDTProperties table of your database.


Navigating a Database Diagram

You can move around in a database diagram by using the keyboard or the mouse.

To use the mouse, click to select an object. To use the keyboard, refer to the following table for keyboard navigation methods.

To | Press
Move from a table cell to the table’s title bar | ESC
Move from a table’s title bar to the last cell you edited | ENTER
Move from table title bar to table title bar, or from cell to cell inside a table | TAB
Expand a list inside a table | ALT + DOWN ARROW
Scroll through the items in a drop-down list from top to bottom | DOWN ARROW
Move to the previous item in a list | UP ARROW
Select an item in a list and move to the next cell | ENTER
Change the setting in a check box | SPACEBAR
Go to the first cell in the row, or to the beginning of the current cell | HOME
Go to the last cell in the row, or to the end of the current cell | END
Scroll to the next "page" inside a table, or to the next "page" of the diagram | PAGE DOWN
Scroll to the previous "page" inside a table, or to the previous "page" of the diagram | PAGE UP


 Selecting Multiple Objects in a Database Diagram

Selecting Multiple Objects in a Database Diagram

You can perform actions on a group of objects by selecting multiple objects in a database diagram. You can select multiple objects that are adjacent to each other or that are spatially separated from each other by other objects.

To select all objects in the diagram

  • Right-click the diagram and choose Select All from the shortcut menu.

To select a group of adjacent tables

  • Hold down the SHIFT key while you click each table that you want to add to your selection.

    –or–

  • Point to the diagram background and drag a rectangle around the tables you want to select. Each table does not have to be fully contained in the rectangle to be selected.

To select a group of spatially separated tables

  • Hold down the CTRL key while you click each table that you want to add to your selection. If you click the title bar of an already selected table, that table is removed from the selection.

To select a group of adjacent columns

  • Hold down the SHIFT key while you click the row selector Row selector of the first and last columns that you want to select. This method selects every column from the column that displays the selected row indicator Selected row selector to the last row selector you clicked.

To select a group of spatially separated columns

  • Hold down the CTRL key while you click the row selector Row selector of each column that you want to add to your selection. If you click the row selector of an already selected column Selected row selector, that column is removed from the selection.

To select a relationship line

  • Click the relationship line.

    You can select only one relationship line at a time. For example, you can select a relationship line when you want to change its properties. When you select a group of tables, the relationship lines between the tables are automatically included in the selection.


 Setting Properties in a Database Diagram

Setting Properties in a Database Diagram

Set column properties in the database diagram to redefine a column name, data type, and so on. Use the Properties Pages dialog box to set properties of tables, relationships, indexes, and constraints.

To edit column properties

  1. In your database diagram, select the table whose columns you want to edit.

  2. Right-click the table and select [image] Column Properties.

  3. Click inside the cell you want to change and then edit the property. The new setting takes effect when you exit that cell.

For more information, see Column Properties.

To set properties of other database objects

  1. In your database diagram, select the table or relationship line whose properties you want to edit. To edit an index or constraint, select the table that it’s attached to.

  2. Right-click the object and select Properties from the shortcut menu.

  3. Select the tab that shows the properties for the object you want to edit.
    • Choose the Tables tab to rename the table or edit check constraints.

    • Choose the Relationships tab to rename the relationship or change the columns that participate in the selected relationship.

    • Choose the Indexes/Keys tab to rename an index, create or edit an index or constraint, or set a fill factor.
  4. Type or select a new setting. The setting takes effect when you exit the field.

Property settings are saved in the database when you save the diagram or selected tables. If you close a database diagram to discard unsaved changes when other database diagrams are still open, the modified database objects will remain in memory until you close all open diagrams. For example, suppose you change the properties of the authors table and close the table without saving it. If you then add the authors table to another open diagram, it will appear in the new diagram in its modified state. To discard all unsaved changes, you must close all open database diagrams without saving them.


Canceling an Action in a Database Diagram

In a database diagram, you cannot undo actions once they have been completed. However, you can cancel an action before it is completed.

The following table lists actions and how you can cancel them before they are completed.

Type of action | To cancel the action
Dragging a table into a database diagram | Before you release the mouse button, drag-and-drop the objects outside the diagram or press the ESC key.
Typing in a table cell | Press the ESC key before exiting the cell.
Editing a property inside the properties pages dialog box | Press the ESC key before exiting the field.
Creating a relationship line | Before you release the mouse button, drag the line to the diagram background. –or– Choose Cancel in the Create Relationship Dialog Box.

Even though you cannot undo a deletion, you can make sure that the deletion does not take effect in your database by closing the affected diagrams without saving them first.


Formatting a Database Diagram

You can format your database diagram in a number of convenient ways. You can choose to have the diagram's layout automatically changed to best show the tables you're currently working on, or automatically display labels for relationship lines. The database diagram can display annotations you create for the diagram and its objects. You can also change the zoom setting of the diagram to display just the amount of the diagram you'd like to see.

To | See
Lay out the tables in the diagram automatically | Arranging Tables Automatically
Add notes to a database diagram | Annotating Diagrams
Show a label identifying relationship lines between tables | Adding Labels to Relationship Lines
Change the zoom setting to view different amounts of the diagram | Zooming a Database Diagram


Arranging Tables Automatically

You can automatically rearrange your database diagram to display the table or tables you want to work on, or you can rearrange the entire diagram in a way that best displays all the tables and their relationships.

To arrange all tables in a diagram automatically

  1. Right-click the database diagram.

  2. From the shortcut menu, select Layout Diagram.

    The diagram is rearranged to best display all the tables and their relationships. This is especially useful if you've moved the tables in the diagram, or added new tables, and want to clean up the layout of the diagram.

To arrange selected tables in a diagram automatically

  1. Select the tables you want to arrange.

  2. Right-click a table and choose Layout Selection from the shortcut menu.

    The diagram is rearranged to best display the currently selected table or tables and their relationships.


Annotating Diagrams

You can put notes into your diagram, to describe the diagram and its objects. These can include headings, descriptions of the tables and their contents, and any other information you want to place in the diagram.

To add annotations to a diagram

  1. Right-click the database diagram.

  2. From the shortcut menu, choose New Label. A blank text box appears in the diagram at the location where you right-clicked.

  3. Type the annotation in the text box.

To change the font of the annotation

  1. Select the text annotation box whose font you want to change.

  2. Right-click inside the text annotation box and choose Font from the shortcut menu.

Note All text in the text annotation box will be changed to the new font.

To arrange the text annotation in a diagram

  1. Select the text annotation box.

  2. Drag the box into position in the diagram.

Tip You can use annotations to describe the relationships between tables in your diagram. However, you can also generate relationship labels automatically. For more information, see Adding Labels to Relationship Lines.


Adding Labels to Relationship Lines in a Database Diagram

You can choose to have all relationship lines in a database diagram display a label automatically.

To add labels to relationship lines in a diagram

  1. Right-click the database diagram.

  2. From the shortcut menu, choose Show Relationship Labels.

To rename relationship labels

  1. Select the relationship line you want to rename.

  2. Right-click the relationship line and select Properties from the shortcut menu.

  3. Select the Relationships tab.

  4. In the Relationship name box, type a new name for the relationship label.

Note You cannot change the font for relationship labels.

If relationship line labels are not displayed, you can still see the relationship line label for a given relationship.

To view a label for a specific relationship line

  1. In the database diagram, move the mouse over the relationship line.

  2. The Tooltip will show the relationship label.


 Zooming a Database Diagram

Zooming a Database Diagram

Change the zoom level of your database diagram to control how much of the diagram you can see on your screen at once.

To zoom a database diagram

  • Select a setting from the Zoom list on the toolbar.

    Note To edit tables, you must set the zoom level to 50% or higher. To create relationships, you must set the zoom level to 25% or higher.

To zoom to a selected object

  • Select an object in the diagram and choose Selection from the Zoom list on the toolbar.

Tip To center the entire diagram in the window, use Select All to highlight all objects in the database diagram and then choose Selection from the Zoom list on the toolbar. This will zoom your diagram to fit in the current diagram window size.


 Subdividing a Database Diagram

Subdividing a Database Diagram

Database diagrams can range in complexity from just one table to hundreds of tables. When you’re working with a large number of tables, you can create a "master" diagram that contains all the tables you need, and then divide the master diagram into many smaller diagrams or "subdiagrams."

Subdivide your diagram when you want to isolate a group of the tables. For example, if you are designing an application with many modules, you can create one master diagram with all the tables that your application needs. You can then subdivide the master diagram so that each subdiagram contains only the tables pertaining to a specific module.

To subdivide a database diagram

  1. Open the master diagram.

  2. Create a new database diagram. For details, see Creating a Database Diagram.

  3. In the master diagram, select the group of tables you want to isolate in the subdiagram. For details, see Selecting Multiple Objects in a Database Diagram.

  4. Copy or drag the tables into the new database diagram. For details, see Copying a Table Across Database Diagrams.

Because each table that appears in a database diagram is merely a reference to a database table, you need to edit the table in only one diagram in order for your changes to be immediately reflected in each diagram in which the table appears.


Merging Subdiagrams into a Master Diagram

Merge a set of subdiagrams into a master diagram to consolidate multiple diagrams for a large group of tables that are logically related. For example, as you add new modules to an existing application, you can create one diagram for each new module. You can then merge all the diagrams into the master diagram.

To merge subdiagrams into a master diagram

  1. Open your master diagram or create a new diagram. For details, see Creating a Database Diagram.

  2. Open the subdiagram that you want to merge into the master diagram.

  3. Select Tile Horizontally or Tile Vertically from the Window menu so that both diagrams are visible.

  4. In the subdiagram, choose Select All from the Edit menu.

  5. Position the pointer on the title bar of one of the selected tables and drag the selection to the master diagram. If your selection contains a table that is already displayed on the master diagram, it will not be duplicated. A diagram cannot contain duplicate copies of a table.

  6. Repeat steps 2 through 5 for each subdiagram that you want to merge into the master diagram.

When you consolidate a group of tables into one diagram by merging subdiagrams into a master diagram, the layout of the individual subdiagrams is maintained within the master diagram.


Printing and Previewing Database Diagrams

Printing your database diagrams gives you a useful picture of your database structure to refer to or distribute. You can preview the page breaks in the database diagram. You can also further customize the way your printed database diagram will look by changing the layout of the database diagram, and by specifying the table views in the diagram.

To print a database diagram

  1. Display the diagram and make sure its layout is what you want to see on the printed page.

  2. From the File menu, choose Print.

  3. Depending on your printer setup, you may need to make or verify a selection in the Print dialog box and click OK.

The Database Diagram Designer displays a set of grid lines showing how the database diagram will be broken into pages when it prints. You can recalculate the grid lines after you've added or rearranged objects.

To preview page breaks

  • If grid lines aren't already displayed, choose View Page Breaks from the Diagram menu.

To recalculate page breaks

  • Right-click in the diagram, and choose Recalculate Page Breaks from the shortcut menu.

    Database diagram with page breaks

Changing the Layout

Before you print, arrange the objects in the database diagram so that it looks the way you want it. You can change the size, shape, and position of objects in your diagram without affecting their definitions in the database.

To change the layout of your diagram, use the features and commands of the Database Diagram Designer to move, size, and shape the objects. For example, you can use the mouse to move or size tables, or use the automatic layout command to automatically reposition the objects in relationship to the selected object or objects.

For more information, see Arranging Tables Automatically

Changing the Views

Each table in a database diagram appears in one of five views: Column Properties, Column Names, Key Columns, Table Names, or Custom. These views show different levels of detail about the table columns, column properties, and property settings. For more information, see Changing a Table View.

The Column Properties and Custom views are the most useful for printing, because they show the most information about the overall structure of the database. With the Custom view you can determine exactly what columns you want to see. You can also avoid displaying scroll bars on any of the tables.

The Column Properties view shows all column properties, even ones you don't normally need to see or set.

Note You can hide and show columns in Column Properties view (by setting the column width to zero), and these columns won't be printed. However, this applies only to one table, and can't be applied automatically to other tables. It does not change the default display for new tables added to the diagram. The Custom view gives you all these capabilities.


Working with Database Diagrams in a Multi-User Environment

You can work with database diagrams in a multi-user environment; that is, an environment in which more than one user may make changes to a database diagram and the database at a time. When you save a diagram, the Database Diagram Designer verifies that the database has not been modified since you last saved the diagram. If another user has made changes, you will be notified that the database has been modified. You may need to reconcile these changes, both in the database diagram and in the database itself.

To | See
Work with others on shared database diagrams | Multi-User Environments
Resolve changes made to a database diagram by multiple users | Reconciling a Database Diagram with a Modified Database


 Ownership of Database Objects

Ownership of Database Objects

Each database has a database owner. The database owner is the creator of the database and has system administrator privileges inside the database. It is the database owner who determines the access and capabilities provided to other users. Within a database diagram, the database owner is identified by his or her database user name.

In most databases, each database object (table, index, view, default, constraint, trigger, and stored procedure) also has a designated owner. The user who creates a database object is the database object owner and is automatically granted all permissions to it. The database object owner is not necessarily the database owner. Any user who has permission to create a database can be a database object owner. In many databases, it is possible to transfer ownership of database objects. See your database documentation for details.

Database diagrams enable you to work with a table that is owned by another user. For example, you can move a column from a table that you don’t own to a table that you just created. If you have sufficient permissions to modify the database with your changes, you can do so by saving your diagram.

For more information about database owners and database object owners, see the documentation for your database.


 Diagrams Affected by Another User's Changes

Diagrams Affected by Another User’s Changes

In a multi-user environment, your database diagram can be affected by changes other users have saved to:

  • Your diagram, which other users changed since you opened the diagram.

  • Database objects shared between diagrams.

  • The database.

For example, your diagram might contain a table that another user deleted or renamed. In such a case, your diagram will no longer reflect the current state of the database. When you attempt to save your database diagram, the Database Changes Detected dialog box notifies you that the database has been updated since you opened your diagram.

This dialog box also displays a list of database objects that will be affected as a result of saving your diagram or selection. At this point, you can take one of these actions:

  • Save your diagram or selection and update the database with all the changes in the list. This action will also affect other diagrams that share the same database objects.

    For example, suppose you edit the au_id column in the titleauthors table on your diagram and another user’s diagram contains the authors table which is related to the titleauthors table by the au_id column. Saving your diagram will affect the other user’s diagram. Similarly, suppose that another user defined a check constraint for the qty column in the sales table. If you delete the qty column and save the sales table, the other user’s check constraint will be affected.

  • Cancel the save action. You can then close the diagram without saving it. When you reopen or recreate the diagram, it will be in synch with the database.

  • Save a list of the changes. You can save the list of database changes shown in the Database Changes Detected dialog box to a text file in the project directory so that you can investigate the cause of other users’ changes.

    For example, if another user edited a table that you marked for deletion, you may want to research whether the table should be deleted before updating the database.


Database Diagram Objects Deleted by Another User

In a multi-user environment, deleting database objects from the database can affect other users. If another user deletes a database object that appears in your database diagram, the effect of the deletion on your diagram depends on where the object was deleted.

Where the object was deleted | How your database diagram is affected
In another copy of your database diagram | The deleted object is removed from your diagram.
In a different database diagram | The deleted object is removed from your diagram.
In the database | If your diagram has no unsaved changes to that object, the object will be removed from your diagram the next time you open it. If your diagram contains unsaved changes to that object, the object will remain in your diagram. You can recreate it in the database by saving your diagram.

Note Recreating a deleted object creates a new definition of that object in the database; it does not restore the data that was deleted when the object was deleted.

For example, if the titles table is deleted in the database and you have unsaved changes to the titles table in your database diagram, then saving your diagram will create a new titles table in the database. Any data that existed in the titles table before it was deleted is not restored.

For details about saving a diagram when the database has changed, see Reconciling a Database Diagram with a Modified Database.


Controlling Database Changes through Database Diagrams

The Database Diagram Designer provides tools to help you make changes to your database. You can control when and how changes to a database made in a database diagram are saved by noting which objects have been changed and which remain unchanged in the database diagram and by rolling back unwanted changes.

To | See
Use database diagrams to control changes to the database | Controlling Database Changes Through Database Diagrams
Return to a previous version of a database diagram without saving changes | Rolling Back Unsaved Database Changes
Ensure that database objects have a unique name | Uniquely Naming Database Objects


 About Controlling Database Changes Through Database Diagrams

About Controlling Database Changes Through Database Diagrams

Database diagrams enable you to modify your database objects without updating the database until you explicitly save the changes you’ve made. If you modify a table and remove it from a diagram without saving the diagram, the table continues to exist in memory in its modified state until you close the Database Diagram Designer.

During an editing session, you have the freedom to experiment with different object definitions to see how a proposed modification will affect the database. When you complete your modifications, you can either save your diagram and thereby update the database to match your diagram, or you can discard it and leave the underlying database unchanged.

Note Having any database diagram open while you have a table open in table Design view, regardless of whether the table exists on the diagram, can affect how table changes are saved. If you make changes to the table in Design view and then close the table without saving it, the changes are still in memory. Therefore, if you save the database diagram, the table changes are saved, too. To discard the changes, you need to close the database diagram without saving it.

Differentiating Saved from Unsaved Database Changes

When you edit a table in a database diagram, an asterisk (*) appears after the table name in the title bar to indicate that the table contains changes that you have not yet saved in the database.

Table with asterisk in title bar

This indicator appears as a result of a change you made to a database object, such as a column or index, in the table or your diagram. When you add a modified table to another open diagram, the table appears there with its unsaved changes and an asterisk in its title bar. When you save the diagram, the asterisk disappears.


Rolling Back Unsaved Database Changes in Diagrams

To roll back unsaved database changes

  1. Close your database diagram.

  2. A message prompts you to save your changes to the diagram. Choose No.

Caution Other open diagrams might be affected by your changes even though you closed the diagram without saving it. To be sure that your changes, which still exist in memory, do not affect open diagrams, close all diagrams in your editing session without saving them. If you want to update the database with changes to other diagrams only, save those diagrams before closing the one whose changes you want to discard.


Uniquely Naming Database Objects in Diagrams

When you name database objects in a database diagram, you will be alerted if the name you choose is already used by another object. An error will occur in the following situations when you attempt to give an object a name already defined in the database catalog:

Object you attempt to name | Object already named in the database catalog | Outcome
Table | Table | Error
 | Relationship | Error
 | Column | Accepted
 | Constraint | Accepted in the diagram, but causes an error when you attempt to save
 | Index | Accepted
Relationship | Table | Error
 | Relationship | Error
 | Column | Accepted
 | Constraint | Error
 | Index | Accepted
Column | Table | Accepted
 | Relationship | Error
 | Column | Error if within same table; accepted across tables
 | Constraint | Error
 | Index | Accepted
Constraint | Table | Error
 | Relationship | Error
 | Column | Accepted
 | Constraint | Error
 | Index | Error
Index | Table | Error
 | Relationship | Error
 | Column | Accepted in the diagram, but causes an error when you attempt to save
 | Constraint | Error
 | Index | Error


 Tables

Tables

A database consists of one or more tables. A table is a collection of data, arranged in rows and columns. For example, you might have a table for author information called authors. Each column would contain a certain type of information, such as the author’s last name. Each row would contain all the information about a specific author: first name, last name, address, and so on.

In a database, you might have a number of tables, each devoted to a specific topic. For example, the pubs database might contain tables for authors, titles, and so on. Using a separate table for each topic can eliminate duplicate data, make data storage more efficient, and reduce data-entry errors.

Tables are the basic building blocks of database diagrams. In a database diagram, each table is laid out in a matrix so that you can see all the properties defined for every column in your database table.

Tables in a Database Diagram

Each table in a database diagram has three distinct features: a title bar, a row selector, and a set of property columns.

  • Title Bar The title bar shows the name of the table. If another user owns the table, then that user’s name appears in parentheses at the end of the table name.

    Table's title bar displaying the owner's name in parentheses

    For information about table owners, see Working in a Multi-User Environment.

    If you have modified a table and have not yet saved it, an asterisk (*) appears at the end of the table name to indicate unsaved changes. For information about saving modified tables and diagrams, see Controlling Database Changes.

    Table's title bar displaying an asterisk
    or
             Table's title bar displaying the owner's name and an asterisk
  • Row Selector You can click the row selector Row selector to select a database column in the table. The row selector displays a key symbol Primary key symbol if the column is in the table’s primary key. For information about primary keys, see Defining a Primary Key.

  • Property Columns The set of property columns is visible in the Column Properties view or Customized view of your table. You can view a table in any of five different views to help you manage the size and layout of your diagram.

    Table in Column Properties view

    For more information about column properties, see Column Properties. For more information about table views, see Changing a Table View.

Before you begin defining the columns for a table, determine what type of data the table will hold and how that table relates to the other tables in your database.

Designing Tables

To determine the structure of a new table, you need to decide:

  • What type of data the table will contain.

  • What columns you need in the table and the data type (and length, if required) for each column.

  • Which columns should accept null values. For information about data types, allowing null values, and other column properties, see Columns.

  • Whether to use constraints and if so, where. For more information, see Constraints.

  • What types of indexes you need, where you need them, and which columns should be the primary key and foreign key. For more information, see Indexes.

After you decide on the structure of your table, you can create the table and define its columns in your database diagram. You can also alter the table’s appearance in your diagram so that the information you need is visible when you need it. When you save your table or the diagram, the table is created in your database.

Microsoft Access has two modes for working on tables. You can view tables directly in a database diagram by using Column Properties view or, from the Database window, you can open a single table in Design view by clicking Tables [image] under Objects, clicking the name of a table in the list, and then clicking the Design button on the Database window toolbar. This opens the table in a single window where you can define columns and properties for the table.

Note The procedures for defining columns and properties that are described in Microsoft Access Help assume you are working in a database diagram; however, you can use the information to work in table Design view as well.

If you know exactly what you want in a table, it is often most efficient to define everything you need at the beginning, including the table’s data restrictions and additional properties. However, in many cases, you’ll do best to first create a basic table and save it so it is created in your database. You can then add some test data to the table and experiment with the table in the database diagram to fine-tune its design.

The Database Diagram Designer enables you to try out different designs by working with tables in your diagram. Through experimentation, you can determine what types of data are frequently entered and queried and then redesign your table accordingly.

When you change a table’s design in a database diagram, any data that is stored in the table is preserved to the extent possible. When you’re satisfied with your basic design, you can add constraints, indexes, and any additional columns that you require. For more information, see Working in Database Diagrams.

To | See
Create a new table in your database diagram, add existing tables or related tables to your database diagram | Adding Tables to a Database Diagram
Create a new table or work with an existing table in table Design view instead of in your database diagram | Create a table in table Design view
Copy a table from one database diagram to another diagram | Copying a Table Across Database Diagrams
Create a new table that contains some of the same columns as an existing table in your diagram | Duplicating Tables
Deleting a table from a database diagram and the database | Removing a Table from a database Diagram Deleting a Table from a Database Diagram and the Database
Change the name of a table in a database diagram and in the database | Renaming a Table
Change the amount of information shown for the tables in the diagram | Changing a Table View
Change the size of the table window in the diagram | Adjusting the Table Size
Add or delete columns to a table, change column property settings | Columns


 Adding Tables to a Database Diagram

Adding Tables to a Database Diagram

You can add a table to your database diagram to edit its content or relate it to other tables in your diagram. You can either add existing database tables to a diagram or insert a new table that has not yet been defined in the database.

  • Inserting a New Table

  • Adding an Existing Table

  • Adding Related Tables

Inserting a New Table

Adding a new table to the database diagram means that you are defining a new table that doesn’t already exist in the database. To create a new table, you must define the individual columns that make up the table. The table is created in the database when you save the table or the diagram.

To insert a new table into a diagram

  1. Make sure you’re connected to the database in which you want to create the table.

    To create a table in your current diagram, on the Diagram menu, click New Table.

    –or–

    Right-click in the diagram, and select New Table.

  2. In the Choose Name dialog box, change the system-assigned name of the table if you want, and then choose OK.

    A new table appears in the diagram in Column Properties view.

  3. In the first cell of the new table, type a column name. Then press the TAB key to move to the next cell.

  4. Under Datatype, select a data type for the column. Each column must have a name and data type.

    You can set other properties for the column by typing or selecting values, or you can accept the default settings.

  5. Repeat steps 3 and 4 for each column you want to add to the table.

When you save your database diagram, the new table will be added to your database.

Note If you create a new table, then remove it from the diagram before saving it to the database, the table name remains in memory until you close the database diagram. Also, if you delete an existing table from the database, the table name remains in memory. To use the table name again, close and restart the Database Diagram Designer.

Adding an Existing Table

Adding an existing table means that the table you want to appear in your diagram already exists in your database. If you add a group of tables to a diagram, any relationships that exist between the tables are also added to the diagram.

To add an existing table to a diagram

  1. Make sure you’re connected to the database whose objects you want to edit.

  2. Right-click in the database diagram window, and then click Show Table.

  3. In the Show Table list, select a table in the Tables folder.

  4. Drag the table into your database diagram.

  5. Release the mouse button.

If relationships exist between the selected table and other tables in your diagram, relationship lines are automatically drawn.

When you add a table to a diagram, the definition of the table (not the data that is stored in the table) is loaded from your database into memory. At that point you can edit the table’s definition, for example by adding new columns or modifying the objects that are attached to it.

Adding Related Tables

For tables with existing foreign key constraints, you can easily add the related tables to the database diagram.

To add related tables to a diagram

  1. Select one or more tables with foreign key constraints in the database diagram.

  2. Right-click on any of the selected tables and choose Add Related Tables.

Both those tables referenced by a foreign key constraint from the selected table(s) and those referencing the selected table(s) with a foreign key constraint are added to the diagram.


 Changing a Table View in a Database Diagram

Changing a Table View in a Database Diagram

When you’re working with only a few tables in a database diagram, it’s usually helpful to view as much column information as possible. Such a view not only gives you more information, but it also enables you to edit the column definitions.

When you’re working with a large number of tables, however, it’s usually preferable to view only the column names, or only the table name, so that you can see more of the tables in your diagram at once.

In a database diagram, you can expand the tables you want to edit as needed and then collapse them again to save space on the diagram.

Each table in a database diagram can be displayed in one of five views.

Tables in each of the five views

  • Column Properties [image] Shows a grid of all the table columns, column properties, and property settings. You can edit the column properties directly by typing in a cell or using the Cut, Copy, and Paste commands. You can also move and delete entire column definitions. You can configure the grid to show a subset of all the available properties for the columns in a table.

    When you insert a new table into a diagram, it is shown in this view so that you can begin defining each column.

  • Column Names [image] Shows the names of all the columns in the table listed by name. You can rename the column names in this view. When you add an existing table to a diagram, it is shown in this view.

  • Keys [image] Shows the names of all the columns in the table that are primary keys or foreign keys or that have unique constraints. You can rename the columns in this view.

  • Name Only [image] Represents a table in its minimized state and shows only the table name.

  • Custom [image] Displays only the columns you choose. This gives you the flexibility to display only the information you want. This view is also useful for printing the database diagrams, because you can display more tables on one page, and won't normally see horizontal scroll bars on the tables. For more information, see Printing and Previewing Database Diagrams.

    The default set of columns for the Custom view includes Column Name, Condensed Datatype, and Nullable.

    Column | Setting
    Column Name | The name of the field in the table.
    Condensed Datatype | Information about the field's data type, in the same format as the SQL Create Table statement. For example, a field containing a variable-length string with a maximum length of 20 characters would be represented as varchar(20).
    Nullable | Null (the field can contain a Null value) or Not Null (the field must contain a non-null value).

To change a table view

  1. In your database diagram, select the tables you want to see in another view. To change the view of all the tables in your diagram, choose Select All from the Edit menu. (Make sure no tables are already selected when you choose the command.)

  2. Right-click the table and select the desired view from the shortcut menu.

    -or-

    Click the corresponding command on the Table Modes drop-down button on the toolbar to change the view of the selected tables:

    Click this button | Button name | To
    Column Properties Add, rename, or delete columns,
    create relationships to other tables,
    edit column properties
    Column Names Add, rename, or delete columns,
    create relationships to other tables
    Keys Add, rename, or delete key columns,
    create relationships to other tables
    Name Only | Minimize tables
    Custom Add, rename, or delete the property columns you've chosen to display in the property grid,
    create relationships to other tables,
    edit column properties for the columns you've chosen to display

When you finish editing a table, you can change it to a different view or resize it to create more space on the diagram.

To modify the Custom view

  1. In your database diagram, select the table you want to see in Custom view.

  2. From the Diagram menu, choose Modify Custom View. The Column Selection dialog box appears.

  3. Use the arrows to move the desired columns from the Available columns box to the Selected columns box.

    Note To add a column, highlight the column in the Available columns box and click the > button. The column will then be listed in the Selected columns box. To display all columns, click the >> button. To remove a column from the Selected columns box, highlight the column and click the < button.

  4. The columns will appear in the table in the order they are displayed in the Selected columns box. Use the Sort arrows to rearrange the columns in the Selected columns box to the desired order.

  5. To make this setting the default Custom view, select the Save as default box.

    Note If the Save as default box is not selected, the columns listed in the Selected columns box will be displayed for all the database tables displayed in Custom view on the current diagram. However, this setting will not be saved and is not applied to other diagrams when you choose the Custom view command.

  6. Click OK.

The selected table is redrawn to display the columns chosen in the dialog box.


 Adjusting the Table Size in a Database Diagram

Adjusting the Table Size in a Database Diagram

You can adjust the size of a table in the diagram in any of its five views. For example, you can enlarge a table in Column Properties view to see all of the properties for its columns without having to scroll the table horizontally. For details about table views, see Changing a Table View.

A minimized table can be resized only horizontally.

To automatically adjust the table size

  1. Select the table(s) you want to resize.

  2. Right-click the table and choose Autosize Selected Tables from the shortcut menu.

    The table and the columns within the table are adjusted to show all the information in the displayed columns.

To manually adjust the table size

  1. Position the pointer over the table border.
    To adjust the table… | Position the pointer over the table’s… | Until the pointer changes to…
    height | top or bottom edge
    width | left or right edge
    height and width | corner | or
  2. Hold down the left mouse button and drag the table border to its new size.

  3. Release the mouse button.


Copying a Table Across Database Diagrams

You can copy a table from one database diagram to another in the same database.

Copying a table from one database diagram to another diagram merely adds a reference to the table in the second diagram. The table is not duplicated in your database. For example, if you copy the authors table from one database diagram to another, each diagram references the same authors table in the database.

To copy a table from another database diagram

  1. Make sure you’re connected to the database whose table you want to copy.

  2. Open a database diagram and select the table that you want to copy to your other database diagram.

  3. Click the Copy button on the toolbar. This action places the selected table definition on the Clipboard.

  4. Switch to the diagram where you want to paste the selection. This diagram must be in the same database as the diagram that you’re copying from.

  5. Click the Paste button on the toolbar. The Clipboard contents appear at the new location and remain highlighted until you click elsewhere. If relationships exist between the selected tables and other tables in your diagram, relationship lines are automatically drawn.

When you edit the table in either diagram, your changes are reflected in both diagrams. Similarly, once you save the table in either diagram, the table is no longer considered "modified" in either diagram.


 Duplicating a Table in a Database Diagram

Duplicating a Table in a Database Diagram

A table can appear only once in a database diagram. However, if you want to create a new table that contains some of the same columns as an existing table in your diagram, you can duplicate the existing table as the first step in creating your new table. Then in your new table, you can delete unwanted columns, add new columns, and assign a unique table name.

Use the same technique for duplicating tables across database diagrams.

To duplicate a table

  1. In the database diagram where you want to duplicate the table, right-click the diagram and choose New Table from the shortcut menu.

    A blank table is added to your diagram.

  2. In the Choose Name dialog box, change the system-assigned name of the new table.

  3. In the table you want to duplicate, select all the columns. This table can be in the same diagram, a different diagram in the same database, or a diagram in a different database.

  4. Copy the columns to the blank table. For details about copying columns, see Copying Columns from One Table to Another.


 Renaming a Table

Renaming a Table

When you rename a table, the table name is automatically updated in every database diagram in which the table appears. It is updated in the database when you save the table or diagram.

To rename a table

  1. In your database diagram, select the table you want to rename.

  2. Right-click the table, and choose Properties from the shortcut menu.

  3. Choose the Tables tab.

  4. In the Table name box, type a new name. Be sure to choose a name that doesn’t duplicate one in the Selected table list.

    To cancel this action, press the ESC key before leaving this field.

The table is renamed in the diagram as soon as you exit the Table name box.

Note Because the table name is used to automatically create and name relationships, indexes, and constraints, it is recommended that you make any changes to the name of your table before you create these database objects. If you change the table name, you'll need to update any references to it in other database objects such as views, or Microsoft Access project objects, such as forms or reports.


 Removing a Table from a Database Diagram

Removing a Table from a Database Diagram

Remove a table from your database diagram if you do not want it to appear in the diagram. Removing a table does not alter your server database. The table and its relationships to other tables continue to exist in the database.

If you remove a table that has been changed either by you or another user, a message prompts you to save the table before removing it:

  • If you save the table before removing it, the database is updated with the changes.

  • If you discard changes to the table before removing it, the table remains in memory in its modified state until you save the table or close the last open database diagram, even though the table no longer appears in your diagram.

For example, suppose you add a table to your diagram so that you can copy its column definitions for address data to a new table you are creating. If you cut the column definitions in the existing table instead of copying them, that table would be marked as modified. In this case, you would discard your changes to that table before removing it. However, if you wanted to move those column definitions to your new table and then remove the existing table from your diagram, you would save your changes to the existing table before removing it.

To remove a table from a database diagram

  1. In your database diagram, select the table you want to remove.

  2. Right-click the table and choose Hide Table from the shortcut menu.

    -or-

    Click the Hide Table button on the Database Diagram toolbar.

    If the table has unsaved changes as a result of edits made in the database diagram by you or another user, a message prompts you to save the table before removing it.

The table is removed from your diagram but it continues to exist in the database.

Note If you create a new table, then remove it from the diagram before saving it to the database, the table name remains in memory until you close the database diagram. Also, if you delete an existing table from the database, the table name remains in memory. To use the table name again, close and restart the Database Diagram Designer.


 Deleting a Table from a Database Diagram and the Database

Deleting a Table from a Database Diagram and the Database

Delete a table from your database diagram when you want to:

  • Remove the table from your diagram.

  • Remove the table from every other diagram in which it appears.

  • Mark the table for deletion from the database.

A table that is marked for deletion is permanently deleted from the database when you save your diagram. A reference to that table continues to exist in memory until you save the diagram. If you close the diagram without saving it, the table will continue to exist in your database and appear in your diagram and every other diagram in which it appeared before you marked it for deletion.

To delete a table from the database

  1. In your database diagram, select the table you want to delete.

  2. Right-click the table and choose Delete Table from Database from the shortcut menu.

  3. A message box prompts you to confirm the deletion. Choose Yes.

    Note Deleting a table in a database diagram automatically removes any relationships to it.


 Work with a table in table Design view

Work with a table in table Design view

In Help topics about working with tables, Microsoft Access Help assumes that you are working in the Database Diagram Designer; however, you can use table Design view to work with a single table if you prefer.

  1. In the Database window, click Tables [image] under Objects.

  2. Do one of the following:
    • To create a new table, click the New button on the Database window toolbar.

    • To open an existing table in Design view, click the table name, and then click the Design button on the Database window toolbar.

The table opens in Design view, which is equivalent to Column Properties view for a table in a database diagram.

Note Having any database diagram open while you have a table open in table Design view, regardless of whether the table exists on the diagram, can affect how table changes are saved. If you make changes to the table in Design view and then close the table without saving it, the changes are still in memory. Therefore, if you save the database diagram, the table changes are saved, too. To discard the changes, you need to close the database diagram without saving it.

See the following topics for more information about modifying or designing the table.

Columns in a Database Table

Constraints

Indexes for a table


Columns in a Database Table

In a table, data is arranged into columns. Each column stores one data element, such as a first name, one line of an address, a price, or any similar discrete unit of information.

When columns are created in a table, they are given a name that identifies their purpose, such as FirstName or Address1. In most databases, you must also specify additional properties, such as how long the longest entry in the column will be, and what type of data the column will contain - characters, integers, floating-point numbers, dates or times, and so on. Other column properties can include whether the column is the table's primary key, whether users must enter a value into it, and what its default value is.

You can edit the column properties for tables directly in the database diagram. For details about which properties are available in your database, see your database documentation.

To | See
Add new column definitions to the end of a table | Inserting Columns into a Table
Copy the column definitions from one table to another table in the same diagram or in different diagrams | Copying Columns from One Table to Another
Move the column definitions from one table to another table in the same database diagram or in a different diagram | Moving Columns from One Table to Another
Delete columns from a table and from the database | Deleting Columns from a Table
Set or edit the column definition (properties) for a database table | Column Properties


 Inserting Columns into a Table

Inserting Columns into a Table

You can add new column definitions to a table to capture additional data that isn’t already stored in an existing column. The Column Properties view, which shows a table with all of its currently defined columns, provides blank grid rows so that you can easily add new column definitions to your database table.

To insert columns into a table

  1. In your database diagram, select the table that you want to add new columns to.

  2. If the table is not already in Column Properties view, right-click the table and choose Column Properties from the shortcut menu.

  3. Right-click a row in the table and select Insert Rows from the shortcut menu. A blank column row is inserted.

    -or-

    Place the cursor in the first blank cell in the Column Name column.

  4. In the Column Name column, type the column name in the cell. The Column Name is a required value.

  5. Press the TAB key to go to the Datatype cell. This is a required value.

The default values for your database are added when you create a new column. Define other properties for the column as needed. You can change any of these values and set additional properties at any time according to the rules of your database. For more information about the column properties available to you, refer to your database documentation.


 Copying Columns from One Table to Another

Copying Columns from One Table to Another

You can copy columns from one table to another table in the same diagram or in different diagrams. Copying a column involves only the column definition. The data itself is not automatically transferred to the second table as part of this process.

To copy columns from one table to another

  1. In your database diagram, select the columns that you want to copy.

  2. Click the Copy button on the toolbar. This action copies the selection from the table and places the column and its current set of properties on the Clipboard.

  3. Position the cursor in the table at the location where you want to insert the columns.

  4. Click the Paste button on the toolbar. The column and its properties are inserted at the new location and remain highlighted until you click elsewhere.

When you copy a database column that has a user-defined data type from one database to another, the user-defined data type may not be available in the destination database. In such a case, the column will be assigned the nearest matching base data type available in that database.


 Moving Columns from One Table to Another

Moving Columns from One Table to Another

You can move columns from one table to another table in the same database diagram or in a different diagram. Moving columns in the database diagram moves the column definition only. The data itself is not automatically transferred to the second table as part of this process.

To move columns without data from one table to another

  1. In your database diagram, select the columns that you want to move.

  2. Click the Cut button on the toolbar. This action deletes the selection from the table and places the column and its current set of properties on the Clipboard.

  3. Position the cursor in the new table at the location where you want to insert the columns.

  4. Click the Paste button on the toolbar. The columns are inserted at the new location and remain highlighted until you click elsewhere.


 Deleting Columns from a Table

Deleting Columns from a Table

Delete columns from a table when they’re no longer needed to store data. When a column is deleted from the table in the database diagram, it is also deleted from the database.

Caution This action cannot be undone once the database diagram or table is saved. The only way to restore a deleted column is to close the table or database diagram without saving changes.

To delete columns from a table

  1. In your table or database diagram, select the row for the column you want to delete.

  2. Right-click the row and choose Delete Rows from the shortcut menu.

  3. If the column participates in a relationship, a message prompts you to confirm the deletion of the selected columns and their relationships. Choose OK.

The column, any constraints attached to it, any relationships it participates in, as well as the data that’s stored in the column are removed from the database diagram. They are deleted from the database when you save the table or database diagram.


 Column Properties on a Table

Column Properties on a Table

Each column in a table has a set of properties. Each property defines one characteristic, such as the name, data type or length, of a column. The entire set of properties for a column makes up that column’s definition in your database table.

You can set column properties directly in your database table in a database diagram. Three column properties are required — the column name, data type, and length — before you can save a table in your database. You can redefine a column by editing any of its properties. For example, you can rename a column, alter its length, specify a default value, and so on.

When you view your table in Column Properties view, the column properties are laid out in a grid. In this grid, you can choose which properties you want to see. You can hide the properties that you rarely define and show the properties that you define more frequently. You can also resize the columns in the grid so that the properties are easy to read.

Table in Column Properties view

For more information about showing, hiding, and resizing property columns, see:

  • Setting Column Properties

  • Resizing Property Columns

  • Changing Which Properties Appear

  • Renaming a Column

For more information about the specific column properties available in your database, see your database documentation.


 Setting Column Properties on a Table

Setting Column Properties on a Table

You can set or change the properties of a column within the grid that appears when you view the table in Column Properties view or when you design a single table in table Design view.

To set column properties

  1. In your database diagram, select the table whose column properties you want to define.

  2. If you're not already in Column Properties view, right-click the table and choose Column Properties from the shortcut menu.

  3. Click inside the cell that shows the property setting that you want to change. You may have to scroll or enlarge the table to see the property.

  4. Type or select a new setting.

Note The data types available in your database typically have default values. Many databases have rules concerning allowable property values. For example, a binary data type is often limited to a length between 1-255. If you type an invalid value for properties with such limitations, a message box will appear.

The new setting takes effect in the database diagram as soon as you press the TAB key or click outside the cell. The new setting is saved in the database when you save the table or your diagram.

Note You can also set column properties in Custom view for any columns you've chosen to display in this view. For more information about Custom view, see Changing a Table View.


 Resizing Property Columns in a Table

Resizing Property Columns in a Table

You can manually change the width of a property column in a database table by resizing it in Column Properties view. For example, you can widen the Datatype column if it contains user-defined data type names that are too long to see in their entirety. You can also automatically resize a property column to fit its widest entry.

To manually change the width of a property column

  1. In your database diagram, select the table whose property columns you want to resize.

  2. Position the pointer along the right border of the column header for the column that you want to resize. The cursor changes from an arrow to a splitter pointer Splitter pointer.

  3. Drag the column border to the left to reduce its width or to the right to increase its width.

  4. Release the mouse button.

To resize a property column to fit the widest entry

  1. In your database diagram, select the table whose columns you want to resize.

  2. Position the pointer along the right border of the column header for the column that you want to resize. The cursor changes from an arrow to a splitter pointer Splitter pointer.

  3. Double-click the splitter pointer.

Note You can also resize property columns in Custom view for any columns you've chosen to display in this view.


 Changing Which Properties Appear for a Table

Changing Which Properties Appear for a Table

When you show a database table in Column Properties view, most but not all of that table’s property columns are visible without scrolling. You can customize this view by choosing whether to hide or show each property column in a database table. For example, you could hide the Precision and Scale properties, which you rarely change, in order to show more of the frequently changed properties.

To hide a property column

  1. In your database diagram, select the table whose property column you want to hide.

  2. Position the pointer along the right border of the column header for the column that you want to hide. The cursor changes from an arrow to a splitter pointer Splitter pointer.

  3. Drag the column border to the left until it meets the column’s left border.

  4. Release the mouse button.

To show a property column that is hidden

  1. In your database diagram, select the table whose property column you want to show.

  2. Position the pointer along the right border of the previous column’s header. The cursor changes from an arrow to a splitter pointer Splitter pointer.

  3. Double-click the splitter pointer. The hidden column resizes to fit the widest entry.

    Note You can also set which column properties you want to display for database tables in a database diagram by using Custom view. For information on this view, see Changing a Table View.


 Renaming a Column in a Table

Renaming a Column in a Table

The name of a column in a table in your database diagram shows the name of the column as it is stored in the database. You can rename a column directly in your table in the database diagram and the database will be updated with the new name when you save the table or diagram.

Column names are stored in the case (uppercase or lowercase) in which they appear in your diagram. They cannot contain blank spaces.

Warning Because renaming a column may affect triggers, stored procedures, and constraints, it’s recommended that you rename a column before you create these other objects. For more information about these database objects, see Working with Database Objects.

To rename a column

  1. In your database diagram, select the table whose column you want to rename.

  2. If only the table name is shown in the database diagram, right-click the table and select Column Properties, Column Names, or Keys from the shortcut menu.

  3. In the cell that shows the column name you want to change, type a new column name. Make sure that it doesn’t duplicate another column name in the same table.

The column is renamed in your table or diagram as soon as you exit the cell that shows the column name. The column is renamed in your database when you save the table or diagram.


 Constraints

Constraints

Constraints are business logic that your database server enforces for you. They limit the possible values that users can enter into specified columns, enforcing referential integrity. When you create constraints in the Database Diagram Designer, they conform to the ANSI standard for creating and altering tables.

The Database Diagram Designer accepts five types of constraints:

  • Check Constraints

  • Default Constraints

  • Unique Constraints

  • Primary Key Constraints

  • Foreign Key Constraints


 Default Constraints

Default Constraints

A default constraint enables you to define the value that will be supplied for a column whenever a user fails to enter a value. For example, in a table with a column called payterms, you can instruct your database server to enter "???" or "fill in later" if the user leaves it blank.

In database diagrams, you define a default constraint as a property of a column in your table. You define this type of constraint for a column by specifying a default value inside a table in Column Properties view. Be sure to specify the constraint with the correct delimiters. For example, strings must be surrounded with single quotes.

Note If you set the DefaultValue property for a field in a table, Microsoft Access will not display the value for a new record in a form based on the table until you save the record. If you want the default value to display automatically when entering a new record in a form, you must set the DefaultValue property on the form field's control.

For more information about defining default constraints, see Setting Column Properties.


 Check Constraints

Check Constraints

A check constraint specifies the data values or formats that are acceptable in one or more columns in a table. For example, you can require the zip column of the authors table to allow only five-digit numeric entries.

Note Some databases have different functionality for check constraints. Consult your database documentation for details about how your database works with check constraints.

You can define many check constraints for a table. You use the Tables property pages to create, modify, or delete each check constraint.

To | See
Attach a check constraint to a table to specify the data values that are acceptable in one or more columns | Attaching a New Check Constraint to a Table or Column
Create a constraint expression to check data for a condition | Defining a Check Constraint Expression
Change the constraint expression or the options that enable or disable the constraint for specific conditions | Modifying a Check Constraint
Apply constraints either to new data only or to existing data as well | Checking Existing Data When Creating a Check Constraint
Disable a check constraint when data is added to, updated in, or deleted from a table | Disabling a Check Constraint with INSERT and UPDATE Statements
Disable a check constraint when your table is replicated in another database | Disabling a Check Constraint for Replication
Remove the limitations on data values in a column | Deleting a Check Constraint


 Attaching a New Check Constraint to a Table or Column

Attaching a New Check Constraint to a Table or Column

Attach a check constraint to a table to specify the data values that are acceptable in one or more columns.

Note Some databases have different functionality for check constraints. Consult your database documentation for details about how your database works with check constraints.

To attach a new check constraint

  1. In your database diagram, select the table where you want to add a check constraint.

  2. Right-click the table and select Properties.

  3. Choose the Tables tab.

  4. Under CHECK constraints for tables and columns, choose New. The Selected constraint box displays the system-assigned name of the new constraint. System-assigned names begin with "CK_" followed by the table name.

  5. In the Constraint expression box, type the SQL expressions for the check constraint. For example, to limit the entries in the state column of the authors table to New York, type:
    state = 'NY'

    Or, to require entries in the zip column to be 5 digits, type:

    zip LIKE '[0-9][0-9][0-9][0-9][0-9]'

    Important Make sure to enclose any non-numeric constraint values in single quotation marks ('). For additional details, see Defining a Check Constraint Expression.

  6. If you want to give the constraint a different name, type the name in the Constraint name box.

When you create a check constraint, it is automatically bound to the specified columns. It takes effect when you save the table or diagram. When you delete a table, all the check constraints attached to that table are automatically deleted.

Note In a form based on a table with check constraints defined, Microsoft Access will not validate the values you enter in fields until the record is saved. If you want a value checked as soon as you leave the field, you must set the ValidationRule property on that field's control.


 Defining a Check Constraint Expression

Defining a Check Constraint Expression

When you attach a check constraint to a table or column, you must include an SQL expression. For details about this operation, see Attaching a New Check Constraint to a Table or Column.

You can create a simple constraint expression to check data for a simple condition; or you can create a complex expression, using Boolean operators, to check data for several conditions. For example, suppose the authors table has a zip column where a 5-digit character string is required. This sample constraint expression guarantees that only 5-digit numbers are allowed:

zip LIKE '[0-9][0-9][0-9][0-9][0-9]'

Or suppose the sales table has a column called qty which requires a value greater than 0. This sample constraint guarantees that only positive values are allowed:

qty > 0

Or suppose the orders table limits the type of credit cards accepted for all credit card orders. This sample constraint guarantees that if the order is placed on a credit card, then only Visa, MasterCard, or American Express is accepted:

NOT (payment_method = ‘credit card’) OR
    (card_type IN (‘VISA’, ‘MASTERCARD’, ‘AMERICAN EXPRESS’))

Note Some databases have different functionality for check constraints. Consult your database documentation for details about how your database works with check constraints.

To define a constraint expression

  • In the Tables tab of the property pages, type the expression in the Constraint expression box using the following syntax:

    {constant | column_name | function | (subquery)}
    [{operator | AND | OR | NOT}
    {constant | column_name | function | (subquery)}…]

    Note This syntax is Microsoft® SQL Server specific.

The SQL syntax is made up of the following parameters:

Parameter | Description
constant | A literal value, such as numeric or character data. Character data must be enclosed within single quotation marks (').
column_name | Specifies a column.
function | A built-in function. For details about functions, see "Functions" in SQL Server Books Online, or Transact-SQL Reference in Microsoft Access Help.
operator | An arithmetic, bitwise, comparison, or string operator. For details about operators, see "Operators" in SQL Server Books Online, or Transact-SQL Reference in Microsoft Access Help.
AND | Use in Boolean expressions to connect two expressions. Results are returned when both expressions are true. When AND and OR are both used in a statement, AND is processed first. You can change the order of execution by using parentheses.
OR | Use in Boolean expressions to connect two or more conditions. Results are returned when either condition is true. When AND and OR are both used in a statement, OR is evaluated after AND. You can change the order of execution by using parentheses.
NOT | Negates any Boolean expression (which can include keywords, such as LIKE, NULL, BETWEEN, IN, and EXISTS). When more than one logical operator is used in a statement, NOT is processed first. You can change the order of execution by using parentheses.


 Modifying a Check Constraint

Modifying a Check Constraint

Modify a check constraint when you want to change the constraint expression or the options that enable or disable the constraint for specific conditions.

To modify a check constraint

  1. In your database diagram, select the table whose check constraint you want to modify.

  2. Right-click the table and select Properties.

  3. Choose the Tables tab.

  4. Select the constraint you want to change from the Selected constraint list.

  5. Complete an action from the following table:

    Note Some databases have different functionality for check constraints. Consult your database documentation for details about how your database works with check constraints.

    To | Follow these steps
    Edit the constraint expression | Type the new expression in the Constraint expression box. For details, see Defining a Check Constraint Expression.
    Rename the constraint | Type a new name in the Constraint name box. Make sure that your new name doesn’t duplicate a name in the Selected constraint list.
    Apply the constraint to existing data (Microsoft SQL Server only) | Select the Check existing data on creation option. For details, see Checking Existing Data When Creating a Check Constraint.
    Disable the constraint when new data is added to the table or when existing data is updated in the table (Microsoft SQL Server only) | Clear the Enable constraint for INSERT and UPDATE option. For details, see Disabling a Check Constraint with INSERT and UPDATE Statements.
    Disable the constraint when the table is replicated in another database(Microsoft SQL Server only) | Clear the Enable constraint for replication option. For details, see Disabling a Check Constraint for Replication.

The constraint is updated in the database when you save your table or diagram.


 Checking Existing Data When Creating a Check Constraint

Checking Existing Data When Creating a Check Constraint

When you create a check constraint, you can set an option to apply it either to new data only or to existing data as well. The option of applying the constraint to new data only is useful when you know that the existing data already meets the new check constraint, or when a business rule requires the constraint to be enforced only from this point forward.

For example, you may have required zip codes to be limited to five digits in the past, but now want new data to allow nine-digit zip codes. Old data with five-digit zip codes will coexist with new data that contains nine-digit zip codes.

Note Some databases have different functionality for check constraints. Consult your database documentation for details about how your database works with check constraints.

To check existing data when creating a check constraint

  1. In your database diagram, select the table that the check constraint is attached to.

  2. Right-click the table and select Properties.

  3. Choose the Tables tab.

  4. Select the constraint from the Selected constraint list.

  5. Select the Check existing data on creation check box. This option is selected by default.

The check constraint will be applied when you save the table or the database diagram. If any constraint violations are encountered during the save process, the table cannot be saved.


 Disabling a Check Constraint with INSERT and UPDATE Statements

Disabling a Check Constraint with INSERT and UPDATE Statements

You can disable a check constraint when data is added to, updated in, or deleted from a table. Disabling a constraint enables you to perform the following transactions:

  • Add a new row of data to a table (using the INSERT statement) where the existing rows were required to meet specific business rules that no longer apply (Microsoft SQL Server only). For example, you may have required postal codes to be limited to five digits in the past, but now want new data to allow nine-digit postal codes. Old data with five-digit postal codes will coexist with new data that contains nine-digit postal codes.

  • Modify existing rows (using the UPDATE statement) where the existing rows were required to meet specific business rules that no longer apply. For example, you may want to update all existing five-digit postal codes to nine-digit postal codes.

Select the option to disable a check constraint during INSERT and UPDATE transactions if you know that new data will violate the constraint, or if the constraint applies only to the data already in the database.

Note Some databases have different functionality for check constraints. Consult your database documentation for details about how your database works with check constraints.

To disable a check constraint with INSERT and UPDATE statements

  1. In your database diagram, select the table that the check constraint is attached to.

  2. Right-click the table and select Properties.

  3. Choose the Tables tab.

  4. Select the constraint from the Selected constraint list.

  5. Clear the Enable constraint for INSERT and UPDATE check box.

    You can select this option after you add or modify data to guarantee that the constraint applies to subsequent data modifications.


 Disabling a Check Constraint for Replication

Disabling a Check Constraint for Replication

You can disable a check constraint when your table is replicated in another database. When you replicate a table, the table definition and data are copied from the source database to a destination database. These two databases are usually (but not necessarily) on separate servers. If the check constraints are specific to the source database, they may unnecessarily prevent new data from being entered in the destination database.

Note Some databases have different functionality for check constraints. Consult your database documentation for details about how your database works with check constraints.

To disable a check constraint for replication

  1. In your database diagram, select the table that the check constraint is attached to.

  2. Right-click the table and select Properties.

  3. Choose the Tables tab.

  4. Select the constraint from the Selected constraint list.

  5. Clear the Enable constraint for replication check box.

When you replicate a database at a remote site, you should not re-apply check constraints because:

  • The integrity of the data was checked when it was entered into the original database.

  • The replication will fail if data violates the check constraints.


 Deleting a Check Constraint

Deleting a Check Constraint

Delete a check constraint when you want to remove the limitations on data values that are accepted in the column or columns included in the constraint expression.

Note Some databases have different functionality for check constraints. Consult your database documentation for details about how your database works with check constraints.

To delete a check constraint

  1. In your database diagram, select the table whose check constraint you want to delete.

  2. Right-click the table and select Properties.

  3. Choose the Tables tab.

  4. Select the constraint from the Selected constraint list.

  5. Choose Delete.

    Caution Choosing Delete will result in an action that cannot be undone without losing all other changes made to the database diagram. To undo this action, close this database diagram and all other open database diagrams without saving the changes.

The constraint is deleted from the database when you save the table or diagram.


 Unique Constraints

Unique Constraints

A unique constraint ensures no duplicate values are entered into specified columns that are not a table’s primary key. For example, in the employee table in which the emp_id column is the primary key, you can define a unique constraint that requires entries in the Social Security number (ssn) column to be unique within the table.

In database diagrams, you use the Indexes/Keys property page to create, modify, or delete unique constraints.

To | See
Ensure no duplicate values are entered in specific columns | Creating a Unique Constraint
Change the columns that the constraint is attached to, change the constraint name, or set additional properties for the constraint | Modifying a Unique Constraint
Remove the requirement for uniqueness for values entered in the column | Deleting a Unique Constraint


 Creating a Unique Constraint

Creating a Unique Constraint

Create a unique constraint to ensure no duplicate values are entered in specific columns that do not participate in a primary key. While both a unique constraint and a primary key enforce uniqueness, you should attach a unique constraint instead of a primary key constraint to a table if:

  • You want to enforce uniqueness in a column or combination of columns. You can attach multiple unique constraints to a table, whereas you can attach only one primary key constraint to a table.

  • You want to enforce uniqueness in a column that allows null values. You can attach unique constraints to columns that allow null values, whereas you can attach primary key constraints only to columns that do not allow null values.

To create a unique constraint

  1. In your database diagram, select the table where you want to add a unique constraint.

  2. Right-click the table and select Properties.

  3. Choose the Indexes/Keys tab.

  4. Choose New. A system-assigned name appears in the Index name box.

  5. Under Column name, expand the list of columns and select the column that you want to attach the constraint to. To attach the constraint to multiple columns, select the additional columns in subsequent rows.

  6. Select the Create UNIQUE check box.

  7. Select the Constraint option.

The unique constraint is created in the database when you save the table or the diagram. If you want to control the sort order of key values and the action taken when duplicate keys exist, you should create a unique index instead of a unique constraint. For more information, see Creating a Unique Index.


 Modifying a Unique Constraint

Modifying a Unique Constraint

Modify a unique constraint when you want to change the columns that the constraint is attached to, change the constraint name, or set additional properties for the constraint.

To modify a unique constraint

  1. In your database diagram, select the table whose unique constraint you want to modify.

  2. Right-click the table and select Properties.

  3. Choose the Indexes/Keys tab.

  4. Select the constraint you want to change from the Selected index list.

  5. Complete an action from the following table:

    To | Follow these steps
    Change the columns that the constraint is attached to | In the Column name grid, expand the list and select the columns you want to attach the constraint to.
    Rename the constraint | Type a new name in the Index name box. Make sure that your new name doesn’t duplicate a name in the Selected index list.
    Set the clustered option (Microsoft SQL Server only) | Select the Create as CLUSTERED check box. Only one clustered index can exist per table. If a clustered index already exists, you must first clear this setting on that index.
    Define a fill factor (Microsoft SQL Server only) | Type an integer from 0 to 100 in the Fill factor box. Type 0 to accept the default fill factor.

The constraint is updated in the database when you save your table or diagram.


 Deleting a Unique Constraint

Deleting a Unique Constraint

Delete a unique constraint when you want to remove the requirement for uniqueness for values entered in the column or combination of columns included in the constraint expression.

To delete a unique constraint

  1. In your database diagram, select the table whose unique constraint you want to delete.

  2. Right-click the table and select Properties.

  3. Choose the Indexes/Keys tab.

  4. Select the unique constraint from the Selected index list.

  5. Choose Delete.

    Caution Choosing Delete will result in an action that cannot be undone without losing all other changes made to the database diagram. To undo this action, close this database diagram and all other open database diagrams without saving the changes.

The constraint is deleted from the database when you save the table or diagram.


 Primary Key Constraints

Primary Key Constraints

A primary key constraint ensures no duplicate values are entered in particular columns and that NULL values are not entered in those columns. You can use primary key constraints to enforce uniqueness as well as referential integrity. For example, the au_id column uniquely identifies each author stored in the authors table.

You create primary key constraints directly in a database diagram.

Note Some databases have different functionality for primary key constraints. Consult your database documentation for details about how your database works with primary key constraints.

To | See
Enforce uniqueness for values entered in specified columns | Defining a Primary Key
Change the column order, index name, clustered option, or fill factor | Modifying a Primary Key
Copy column properties from a primary key column to a foreign key column to relate the two columns | Copying Column Properties to a Foreign Key Column
Remove the requirement for uniqueness for the values entered in a column | Deleting a Primary Key Constraint


 Defining a Primary Key

Defining a Primary Key

Define a primary key to enforce uniqueness for values entered in specified columns that do not allow nulls. If you define a primary key for a table in your database, you can relate that table to other tables, thus reducing the need for redundant data. A table can have only one primary key.

Note Some databases have different functionality for primary key constraints. Consult your database documentation for details about how your database works with primary key constraints.

To define a primary key

  1. In your database diagram, click the row selector for the database column you want to define as the primary key. If you want to select multiple columns, hold down the CTRL key while you click the row selectors for the other columns.

  2. Right-click the row selector for the column and select Primary Key. A primary key index, named "PK_" followed by the table name, is automatically created on the Indexes/Keys tab of the property pages.

    Warning If you want to redefine the primary key, any relationships to the existing primary key must be deleted before the new primary key can be created. A message will warn you that existing relationships will be automatically deleted as part of this process.

A primary key column is identified by a primary key symbol Primary key symbol in its row selector.

If a primary key consists of more than one column, duplicate values are allowed in one column, but each combination of values from all the columns in the primary key must be unique.

If you define a compound key, the order of columns in the primary key matches the order of columns as shown in the table in your diagram. However, you can change the order of columns after the primary key is created.


 Modifying a Primary Key

Modifying a Primary Key

Modify a primary key if you want to change the column order, index name, clustered option, or fill factor.

To modify a primary key

  1. In your database diagram, select the table whose primary key you want to modify.

  2. Right-click the table and select Properties.

  3. Choose the Indexes/Keys tab.

  4. Select the primary key index from the Selected index list.

  5. Complete an action from the following table:

    Note Some databases have different functionality for primary key constraints. Consult your database documentation for details about how your database works with primary key constraints.

    To | Follow these steps
    Change the column order In the Column name grid, expand the list of columns and select the column that you want to order first in the primary key. Repeat this step in subsequent rows of the Column name grid to reorder the remaining columns in the primary key.

    Note Each column name must be unique in a primary key. If you select the same column name in more than one row of the Column name grid, an error will prevent you from saving the table.
    Rename the primary key | Type a new name in the Index name box. Make sure that your new name doesn’t duplicate a name in the Selected index list.
    Set the clustered option | (Microsoft SQL Server only.) Select the Create as CLUSTERED check box. Only one clustered index can exist per table. If this option is not available for your index, you must first clear this setting on the existing clustered index.
    Define a fill factor | (Microsoft SQL Server only.) Type an integer from 0 to 100 in the Fill factor box. Type 0 to accept the default fill factor.

The constraint is updated in the database when you save your table or diagram.


 Deleting a Primary Key Constraint

Deleting a Primary Key Constraint

Delete a primary key constraint when you want to remove the requirement for uniqueness for the values entered in a column or a combination of columns.

To delete a primary key constraint

  1. In your database diagram, select the primary key columns for the table whose primary key constraint you want to delete. A primary key column is identified by a primary key symbol Primary key symbol in its row selector.

  2. Right-click the row selector for the column and select Primary Key.

    –or–

  3. In your database diagram, select the table whose primary key constraint you want to delete.

  4. Right-click the table and select Properties.

  5. Choose the Indexes/Keys tab.

  6. Select the primary key index from the Selected index list.

  7. Choose Delete.

    Caution Choosing Delete will result in an action that cannot be undone without losing all other changes made to the database diagram. To undo this action, close this database diagram and all other open database diagrams without saving the changes.

The constraint is deleted from the database when you save the table or diagram.


 Foreign Key Constraints

Foreign Key Constraints

A foreign key constraint works in conjunction with primary key or unique constraints to enforce referential integrity among specified tables. For example, you can place a foreign key constraint on the title_id column in the publishers table to ensure that a value entered in that column matches an existing value in the title_id column of the titles table.

In database diagrams, a foreign key constraint is automatically placed on specified columns when you create a relationship to a table from another table to which a primary key or unique constraint is attached. For more information about creating relationships, see Creating a Relationship Between Tables.

To | See
See which columns participate in the foreign key side of a relationship | Viewing Foreign Key Attributes
Change which columns are related to columns in the primary key table | Modifying a Foreign Key
Check existing data when creating a relationship | Checking Existing Data when Creating a Relationship
Disable a foreign key constraint during INSERT and UPDATE transactions | Disabling a Foreign Key Constraint with INSERT and UPDATE Statements
Disable a foreign key constraint during replication of the table | Disabling a Foreign Key Constraint for Replication
Remove the requirement to enforce referential integrity between primary key columns and the related columns in another table | Deleting a Foreign Key Constraint


 Viewing Foreign Key Attributes

Viewing Foreign Key Attributes

View the foreign key attributes of a relationship if you want to see which columns participate in the foreign key side of a relationship. If the foreign key columns are related to a primary key, the primary key columns are identified in your database diagram by a primary key symbol in the row selector: Primary key symbol.

To view the foreign key attributes of a relationship

  1. In your database diagram, select a relationship line.

  2. Right-click the table and select Properties.

  3. Choose the Relationships tab.

  4. Make sure the relationship is selected in the Selected relationship list.

  5. The Foreign key table column displays the name of each column that participates in the foreign key side of the relationship.


 Modifying a Foreign Key

Modifying a Foreign Key

Modify the foreign key side of a relationship if you want to change which columns are related to columns in the primary key table.

To modify a foreign key

  1. In your database diagram, select the relationship line that you want to modify.

  2. Right-click the table and select Properties.

  3. Choose the Relationships tab.

  4. Select the relationship from the Selected relationship list.

  5. In the Foreign key table column, expand the list in the first row.

  6. Select a different table column from the list. The foreign key column must match the data type and size of the primary key column, with these exceptions:
    • A char column or sysname column can relate to a varchar column.

    • A binary column can relate to a varbinary column.

    • A user-defined data type can relate to its base type.

Any changes you make to the relationship’s properties take effect as soon as you move outside the grid in the property pages. The constraint is updated in the database when you save your table or diagram.

Note Modifying a relationship in a database diagram marks both of the related tables as modified. Consequently, each table will also be marked as modified in any other diagrams in which it appears.


 Copying Column Properties to a Foreign Key Column in a Database Diagram

Copying Column Properties to a Foreign Key Column in a Database Diagram

When you copy a column from one table to another table, the column name and many of the other properties you defined for that column in the table are copied to the new location. You can copy column properties from a primary key column to a foreign key column if you want to relate the two columns. Related columns must have the same data type (or data types that can be related) and Length property settings.

To copy primary key column properties to a foreign key column

  1. In your database diagram, select the primary key columns that you want to copy. Primary key columns are indicated by a key symbol Primary key symbol in their row selector.

  2. Copy the columns to the foreign key table. For details, see Copying Columns from One Table to Another.

  3. Drag a relationship line from the columns in the primary key table to the same columns in the foreign key table. For details, see Creating a Relationship Between Tables.


 Disabling a Foreign Key Constraint with INSERT and UPDATE Statements

Disabling a Foreign Key Constraint with INSERT and UPDATE Statements

Select the option to disable a foreign key constraint during INSERT and UPDATE transactions if you know that new data will violate the constraint or if the constraint applies only to the data already in the database.

To disable a foreign key constraint with INSERT and UPDATE statements

  1. In your database diagram, select the table that the foreign key constraint is attached to.

  2. Right-click the table and select Properties.

  3. Choose the Relationships tab.

  4. Select the relationship from the Selected relationship list.

  5. Clear the Enable relationship for INSERT and UPDATE check box.

After you add or modify data, you should select this option if you want to ensure the constraint applies to subsequent data modifications.

Note If you plan to use triggers to implement database operations, such as cascade updates or cascade deletes, you must disable foreign key constraints in order for the trigger to run.


 Disabling a Foreign Key Constraint for Replication

Disabling a Foreign Key Constraint for Replication

Select the option to disable a foreign key constraint during replication if the constraint is specific to the source database and may unnecessarily prevent new data from being entered into the destination database.

To disable a foreign key constraint for replication

  1. In your database diagram, select the table that the foreign key constraint is attached to.

  2. Right-click the table and select Properties.

  3. Choose the Relationships tab.

  4. Select the relationship from the Selected relationship list.

  5. Clear the Enable relationship for replication check box.


 Deleting a Foreign Key Constraint

Deleting a Foreign Key Constraint

Delete a foreign key constraint when you want to remove the requirement to enforce referential integrity between primary key columns and the related columns in another table.

To delete a foreign key constraint

  • In your database diagram, delete the relationship line that represents the foreign key constraint you want to delete. For details, see Deleting a Relationship.

Note Deleting a relationship from a database diagram marks the related tables as modified in all diagrams in which they appear.


 Indexes for a table

Indexes for a table

You can use an index to gain fast access to specific information in a database table. An index is a structure that orders the values of one or more columns in a database table, for example the last name (lname) column of the employee table. If you were looking for a specific employee by his or her last name, the index would enable you to get that information faster than if you had to search all the rows in the table, which is sorted by employee ID.

The index provides pointers to the data values stored in specified columns of the table, and then orders those pointers according to the sort order you specify. The database uses the index much as you use an index in a book: it searches the index to find a particular value and then follows the pointer to the row containing that value.

In database diagrams, you can create, edit, or delete each type of index in the Indexes/Keys property page for a selected table. An index is saved in the database when you save the table that it’s attached to, or when you save the diagram in which that table appears. For details, see Creating an Index.

Note Not all databases work with indexes in the same way. For more information, consult your database documentation.

As a rule of thumb, you should create an index on a table only if the data in the indexed columns will be queried frequently. Indexes take up disk space and slow the adding, deleting, and updating of rows. In most situations, the speed advantages of indexes for data retrieval greatly outweigh these disadvantages. However, if your application updates data very frequently or if you have disk space constraints, you might want to limit the number of indexes.

Before creating an index, you have two important tasks:

  • Deciding Which Columns to Index

  • Choosing the Type of Index

Deciding Which Columns to Index

You can create indexes based on a single column or on multiple columns in a database table. Multiple-column indexes enable you to distinguish between rows in which one column may have the same value.

Indexes are also helpful if you often search or sort by two or more columns at a time. For example, if you often set criteria for last name and first name columns in the same query, it makes sense to create a multiple-column index on those two columns.

To determine the usefulness of an index:

  • Examine the WHERE and JOIN clauses of your queries. Each column included in either clause is a possible candidate for an index.

  • Experiment with the new index to examine its effect on the performance of running queries.

  • Consider the number of indexes already created on your table. It’s best to avoid a large number of indexes on a single table.

  • Examine the definitions of the indexes already created on your table. It’s best to avoid overlapping indexes that contain shared columns.

  • Examine the number of unique data values in a column and compare that number with the number of rows in the table. The result is the selectivity of that column, which can help you decide if a column is a candidate for an index and, if so, what type of index.

Choosing the Type of Index

Depending on the functionality of your database, you can create three types of indexes - unique, primary key, and clustered - in the Database Diagram Designer. For details about the indexing functionality supported by your database, see your database documentation.

Tip Although a unique index will help locate information, for the best performance results it is recommended that you use primary key or unique constraints instead. For more information about these constraints, see Primary Key Constraints and Unique Constraints.

Unique Index

A unique index is one in which no two rows are permitted to have the same index value.

Most databases prevent you from saving a table with a newly created unique index when there are duplicate key values in the existing data. Your database may also prevent the addition of new data that would create duplicate key values in the table. For example, if you create a unique index on the employee’s last name (lname) in the employee table, then no two employees can share the same last name.

For more information about unique indexes, see Creating a Unique Index.

Primary Key Index

A database table often has a column or combination of columns whose value uniquely identifies each row in the table. This column is called the primary key of the table.

Defining a primary key for a table in a database diagram automatically creates a primary key index that is a specific type of unique index. This index requires each value in the primary key to be unique. It also permits fast access to data when you use the primary key index in queries. For more information about primary keys, see Defining a Primary Key.

Clustered Index

In a clustered index, the physical order of the rows in the table is the same as the logical (indexed) order of the key values. A table can contain only one clustered index.

If an index is not clustered, the physical order of the rows in the table does not match the logical order of the key values. A clustered index usually provides faster access to data than does a nonclustered index.

For more information about using a clustered index, see Creating a Clustered Index.


 Creating an Index

Creating an Index

You can use an index to speed access to data in a database table. You create an index by selecting one or more columns in a table that you want to be able to search on. You can use the index once you save the table.

To create an index

  1. In your database diagram, select the table you want to index.

  2. Right-click the table, and choose Properties from the shortcut menu.

  3. Choose the Indexes/Keys tab.

  4. Choose New. The Selected index box displays the system-assigned name of the new index.

  5. Under Column name, select the columns you want to index. You can select up to 16 columns. For optimal performance, select only one or two columns.

  6. Specify any other desired settings for the index.

The index is created in the database when you save the table or diagram.

Note Not all databases work with indexes in the same way. For more information, consult your database documentation.


 Creating a Unique Index

Creating a Unique Index

Create a unique index when uniqueness is a characteristic of the data itself, but the combination of indexed columns is not the same as the table’s primary key. For example, if you plan to query frequently on the Social Security number (ssn) column in the employee table (where the primary key is emp_id), and you want to ensure Social Security numbers are unique, create a unique index on ssn. If the user enters the same Social Security number for more than one employee, the database displays an error and cannot save the table.

Tip Although a unique index will help locate information, for the best performance results it is recommended that you use primary key or unique constraints instead. For more information about these constraints, see Primary Key Constraints and Unique Constraints.

When you create or modify a unique index, you can set an option to ignore duplicate keys. If this option is set and you attempt to create duplicate keys by adding or updating data that affects multiple rows (with the INSERT or UPDATE statement), the row that causes the duplicates is not added or, in the case of an update, discarded. Neither the new value nor the original value of the row that would produce the duplicate exists in the updated table.

For example, if you try to update "Smith" to "Jones" in a table where "Jones" already exists, you end up with one "Jones" and no "Smith" in the resulting table. The original "Smith" row is lost because an UPDATE statement is actually a DELETE followed by an INSERT. "Smith" was deleted and the attempt to insert an additional "Jones" failed. The whole transaction can’t be rolled back because the purpose of this option is to allow a transaction in spite of the presence of duplicates.

Caution If you do not set the Ignore duplicate keys option and you try to update a row in a way that creates a duplicate key, the original row is discarded. The new value rather than the original value of the row that would produce the duplicate is retained in the updated table. This transaction cannot be rolled back.

To create a unique index

  1. In your database diagram, select the table you want to index.

  2. Right-click the table, and choose Properties from the shortcut menu.

  3. Choose the Indexes/Keys tab.

  4. Choose New. The Selected index list displays the system-assigned name of the new index.

  5. Under Column name, select the columns you want to index. You can select up to 16 columns. For optimal performance, select only one or two columns per index.

  6. Select the Create UNIQUE check box.

  7. Select the Index option.

  8. Select the Ignore duplicate keys option if you want to ignore new or updated data that would create a duplicate key in the index (with the INSERT or UPDATE statement).

The index is created in the database when you save the table or diagram.

Note You cannot create a unique index on a single column if that column contains NULL in more than one row. Similarly, you cannot create a unique index on multiple columns if the combination of columns contains NULL in more than one row. These are treated as duplicate values for indexing purposes.

Note Not all databases work with indexes in the same way. For more information, consult your database documentation.


 Specifying a Fill Factor for an Index

Specifying a Fill Factor for an Index

In Microsoft® SQL Server™ databases, you can identify a fill factor to specify how full each index page can be. The amount of empty space on an index page is important because when an index page fills up, the system must take time to split it to make room for new rows.

It is seldom necessary to specify a fill factor when you create an index. The option is provided for fine-tuning performance. It is useful when you are creating a new index on a table with existing data, and particularly when you can accurately predict future changes in that data.

To specify a fill factor for an index

  1. In your database diagram, select the table for which you want to specify a fill factor.

  2. Right-click the table, and choose Properties from the shortcut menu.

  3. Choose the Indexes/Keys tab.

  4. Select the index from the Selected index list.

  5. In the Fill factor box, type a percentage from 0 to 100.

By default, the fill factor is set to zero. If you change a fill factor after the index has been created, the database does not dynamically update the specified percentage of empty space in the pages. The value of the original fill factor is stored with the index in the database catalog.

For more information about fill factors and their uses, see "Fill Factor" in SQL Server Books Online.


 Creating a Clustered Index

Creating a Clustered Index

In Microsoft® SQL Server™ databases you can create a clustered index. In a clustered index, the physical order of the rows in the table is the same as the logical (indexed) order of the key values. A table can contain only one clustered index. UPDATE and DELETE operations are often accelerated by clustered indexes because these operations require large amounts of data to be read.

Consider using a clustered index for:

  • Columns that contain a limited number of unique values, such as a state column that contains only 50 unique state codes.

  • Queries that return a range of values, using operators such as BETWEEN, >, >=, <, and <=.

  • Queries that return large result sets.

You can also use a clustered index to control what happens when a duplicate key or duplicate row is created as a result of adding or updating data to the indexed table (with the INSERT or UPDATE statement).

To create a clustered index

  1. In your database diagram, select the table whose index you want to modify.

  2. Right-click the table, and choose Properties from the shortcut menu.

  3. Choose the Indexes/Keys tab.

  4. Create a new index. For details, see Creating an Index.

    To modify an existing index, select the index from the Selected index list.

  5. Select the Create as CLUSTERED check box.

  6. For SQL Server 6.5, select one of the duplicate row options:
    Option | Treatment of duplicate rows
    Disallow duplicate rows | The default option. If duplicate rows exist, the index cannot be created when you attempt to save the table.
    Ignore duplicate rows | If duplicate rows exist, the index is created but duplicate rows are deleted when you save the table. When new rows are inserted, duplicates are not accepted and a SQL Server error appears when you attempt to save the table.
    Allow duplicate rows | Duplicate rows are accepted in new and existing data.

The index is created in the database when you save the table or diagram.


 Sorting Data in a Clustered Index

Sorting Data in a Clustered Index

When you create or modify a clustered index in Microsoft® SQL Server™ 6.5 databases, you set an option to control when data is sorted in the index. You can either sort the data when the index is created, or sort and reorganize the data when the table has become fragmented. For details about what causes table fragmentation and for recommended solutions, see the DBCC statement in your database documentation.

The option to sort the data when the index is created is always the faster of these two options because it doesn’t require the data to be copied or nonclustered indexes to be rebuilt.

To sort index values

  1. In your database diagram, select the table whose index values you want to sort.

  2. Right-click the table, and choose Properties from the shortcut menu.

  3. Choose the Indexes/Keys tab.

  4. Select the index from the Selected index list.

  5. Make sure the Create as CLUSTERED option is selected.

  6. Choose one of the sort options:
    Option | Action
    Sort data | The default option. Sorts the data when the index is created.
    Data already sorted Eliminates the sort performed when a clustered index is created and verifies that the data has been sorted by checking each index value to determine whether it is higher than the previous one. If any row fails this check, the index cannot be created when you attempt to save the table.

    When the data satisfies the check, this option will always be faster than the Reorganize sorted data option because the data is not copied and nonclustered indexes will not be rebuilt. This option is useful when a fill factor is specified to compact or expand the pages on which a table is stored.

    For more information about fill factors, see Specifying a Fill Factor for an Index.
    Reorganize sorted data | Same as Data already sorted, except that this option will always be slower because the data is copied and nonclustered indexes will be rebuilt. Reorganizing the data is a good idea when a table becomes fragmented and you want to re-sort index values.

Note Data already sorted creates the clustered index with the SORTED_DATA option. Reorganize sorted data creates the clustered index with the SORTED_DATA_REORG option. If you select either option and any row fails the check, the attempt to create the index when you save the table will fail. In the event of such a failure, you can either fix the data or choose the Sort data option.


Saving, Displaying, and Updating an Index Definition

Your index is automatically saved in the database (and defined in the database catalog) when you save your table or database diagram. The index is available for modification as soon as you create it.

To display and update index definitions

  1. In your database diagram, select the table whose index definitions you want to display.

  2. Right-click the table, and choose Properties from the shortcut menu.

  3. Choose the Indexes/Keys tab.

  4. To update the definition, select the field you want to update and change its value or setting.

Your changes are saved to the database when you save the table or diagram.


 Renaming an Index

Renaming an Index

New indexes are automatically given system-defined names based on the database table name. If you create multiple indexes on a table, the index names are appended with "_1", "_2", and so on. You can rename an index as long as index names are unique within the table.

Note When you create a primary key or unique constraint for a table, an index with the same name as the constraint is automatically created for the table. Because index names must be unique for a table, you cannot create or rename an index to have the same name as the primary key or unique constraint for the table.

To rename an index

  1. In your database diagram, select the table whose index you want to rename.

  2. Right-click the table, and choose Properties from the shortcut menu.

  3. Choose the Indexes/Keys tab.

  4. Select the index from the Selected index list.

  5. Type a new name in the Index name box. Make sure that it doesn’t duplicate a name in the Selected index list. If you type the same name as an existing index on this table, an error message appears.

The index is renamed in your diagram when you exit the Index name box. It is renamed in the database when you save the table or diagram.


Deleting an Index

Indexes can slow INSERT, UPDATE, and DELETE performance. If you find that an index hinders overall performance or you no longer need it, you can delete it.

To delete an index

  1. In your database diagram, select the table whose index you want to delete.

  2. Right-click the table, and choose Properties from the shortcut menu.

  3. Choose the Indexes/Keys tab.

  4. From the Selected index list, select the index you want to delete.

  5. Choose Delete.

    Caution Choosing Delete will result in an action that cannot be undone without loosing all other changes made to the database diagram. To undo this action, close this database diagram and all other open database diagrams without saving the changes.

The index is deleted from the database when you save your table or diagram.


 Table Relationships

Table Relationships

You can create relationships between your tables in a database diagram to show how the columns in one table are linked to columns in another table.

In a relational database, relationships enable you to prevent redundant data. For example, if you are designing a database that will track information about books you might have a table called titles that stores information about each book, such as the book’s title, date of publication, and publisher. There is also information you might want to store about the publisher, such as the publisher's phone number, address, and zip code. If you were to store all of this information in the titles table, the publisher’s phone number would be duplicated for each title that the publisher prints.

A better solution is to store the publisher information only once in a separate table, publishers. You would then put a pointer in the titles table that references an entry in the publisher table.

To make sure your data is not out of sync, you can enforce referential integrity between the titles and publishers tables. Referential integrity relationships help ensure information in one table matches information in another. For example, each title in the titles table must be associated with a specific publisher in the publishers table. A title cannot be added to the database for a publisher that does not exist in the database.

For a better understanding of table relationships, see:

  • Defining Table Relationships

  • Enforcing Referential Integrity

Defining Table Relationships

A relationship works by matching data in key columns — usually columns with the same name in both tables. In most cases, the relationship matches the primary key from one table, which provides a unique identifier for each row, with an entry in the foreign key in the other table. For example, sales can be associated with the specific titles sold by creating a relationship between the title_id column in the titles table (the primary key) and the title_id column in the sales table (the foreign key).

There are three types of relationships between tables. The type of relationship that is created depends on how the related columns are defined.

  • One-to-Many Relationships

  • Many-to-Many Relationships

  • One-to-One Relationships

One-to-Many Relationships

A one-to-many relationship is the most common type of relationship. In this type of relationship, a row in table A can have many matching rows in table B, but a row in table B can have only one matching row in table A. For example, the publishers and titles tables have a one-to-many relationship: each publisher produces many titles, but each title comes from only one publisher.

A one-to-many relationship is created if only one of the related columns is a primary key or has a unique constraint.

Many-to-Many Relationships

In a many-to-many relationship, a row in table A can have many matching rows in table B, and vice versa. You create such a relationship by defining a third table, called a junction table, whose primary key consists of the foreign keys from both table A and table B. For example, the authors table and the titles table have a many-to-many relationship that is defined by a one-to-many relationship from each of these tables to the titleauthors table. The primary key of the titleauthors table is the combination of the au_id column (the authors table’s primary key) and the title_id column (the titles table’s primary key).

One-to-One Relationships

In a one-to-one relationship, a row in table A can have no more than one matching row in table B, and vice versa. A one-to-one relationship is created if both of the related columns are primary keys or have unique constraints.

This type of relationship is not common because most information related in this way would be all in one table. You might use a one-to-one relationship to:

  • Divide a table with many columns.

  • Isolate part of a table for security reasons.

  • Store data that is short-lived and could be easily deleted by simply deleting the table.

  • Store information that applies only to a subset of the main table.

Enforcing Referential Integrity

Referential integrity is a system of rules that ensure relationships between rows in related tables are valid and that you don't accidentally delete or change related data.

When referential integrity is enforced, you must observe the following rules:

  • You can't enter a value in the foreign key column of the related table if that value doesn't exist in the primary key of the related table. However, you can enter a null in the foreign key column. For example, you can't indicate that a job is assigned to an employee who isn’t included in the employee table, but you can indicate that an employee has no assigned job by entering a null in the job_id column of the employee table.

  • You can't delete a row from a primary key table if rows matching it exist in a related table. For example, you can't delete a row from the jobs table if there are employees assigned to the job represented by that row in the employee table.

  • You can't change a primary key value in the primary key table if that row has related rows. For example, you can't delete an employee from the employee table if that employee is assigned to a job in the jobs table.

You can set referential integrity when all of the following conditions are met:

  • The matching column from the primary table is a primary key or has a unique constraint.

  • The related columns have the same data type and size.

  • Both tables belong to the same database.

Enforced and Unenforced Relationships in Database Diagrams

Creating a relationship line in a database diagram automatically enforces referential integrity by creating a foreign key constraint on the related table. An enforced relationship appears in your database diagram as a solid line. For example:

Relationship line for enforced relationships

An unenforced relationship, whose foreign key constraint is disabled, appears in your diagram as a dashed line. For example:

Relationship line for unenforced relationships

Depending on the features of your database, you can set options to disable the foreign key constraint for certain conditions, for example, during INSERT and UPDATE transactions.

To | See
Create relationships between database tables in a database diagram | Creating a Relationship Between Tables
Ensure each value entered in a foreign key column matches an existing value in the related primary key column | Enforcing Referential Integrity Between Tables
Link a column in a table with another column in the same table | Drawing a Single-Table Reflexive Relationship
Relate many rows in one table to many rows in another table | Mapping Many-to-Many Relationships to a Database Diagram
Change the name of a relationship | Renaming a Relationship
Remove the relationship between two tables | Deleting a Relationship
Disable a foreign key constraint | Disabling a Foreign Key Constraint with INSERT and UPDATE Statements and Disabling a Foreign Key Constraint for Replication


 Creating a Relationship Between Tables

Creating a Relationship Between Tables

You create a relationship between two tables when you want them to share data. You can store data in one of the tables, but make it available to both. You can also create a relationship to enforce referential integrity between related tables.

Before you create a relationship, you must first define a primary key or unique constraint in at least one of the tables. You then relate the primary key columns to matching columns in another table. Once you create the relationship, those matching columns become the foreign key of the related table. For more information, see Defining a Primary Key or Creating a Unique Constraint.

To create a relationship between tables

  1. In your database diagram, click the row selector Row selector for the database column or combination of columns that you want to relate to a column in another table.

  2. While the pointer is positioned over the row selector, drag the pointer to the related table. To relate the selected columns to the primary key of the related table, drag the pointer to the related table’s title bar.

    Dragging a table's primary key to another table to create a relationship

  3. Release the mouse button. The Create Relationship dialog box appears and attempts to match the columns you selected with columns of the same name and data type in the related table.

  4. In the Create Relationship dialog box, confirm that the columns you want to relate are shown in the Primary key table and Foreign key table lists.

  5. Choose OK to create the relationship.

The primary key side of the relationship is denoted by a key Primary key symbol symbol. In one-to-one relationships, the table that initiated the relationship determines the primary key side. For example, if you create a relationship from the pub_id column in the publishers table to the pub_id column in the pub_info table, then the publishers table is on the primary key side of the relationship.

The foreign key side of a relationship is denoted by a key Foreign key symbol symbol for a one-to-one relationship or an infinity Infinity symbol symbol for a one-to-many relationship.

Tip If you want to see labels for relationship lines, use the Show Relationship Labels command. For more information on relationship labels and this command, see Adding Labels to Relationship Lines.


 Enforcing Referential Integrity Between Tables

Enforcing Referential Integrity Between Tables

Referential integrity between tables is enforced by default when you create a relationship in your database diagram. An enforced relationship ensures each value entered in a foreign key column matches an existing value in the related primary key column.

You can change the conditions under which referential integrity is enforced by editing the relationship’s properties.

To change referential integrity options for a new relationship

  1. In your database diagram, create a relationship line. For details, see Creating a Relationship Between Tables.

  2. In the Create Relationship dialog box, clear or select one or more of the options.

    For information about the options available for SQL Server databases, see Database Diagram Designer Considerations for SQL Server Databases.

To change referential integrity options for an existing relationship

  1. In your database diagram, select the relationship line.

  2. Right-click the relationship line and select Properties.

  3. Choose the Relationships tab.

  4. Select the relationship from the Selected relationship list.

  5. Clear or select one or more of the options.

    For information about the options available for SQL Server databases, see Database Diagram Designer Considerations for SQL Server Databases.

The relationship is updated in the database when you save the diagram or either of the related tables.


 Drawing a Single-Table Reflexive Relationship

Drawing a Single-Table Reflexive Relationship

You create a reflexive relationship to link a column in a table with another column in the same table. For example, suppose the employee table has an emp_id column and a mgr_id column. Because each manager is also an employee, you relate these two columns by drawing a relationship line from the table to itself. This relationship ensures each manager ID that is added to the table matches an existing employee ID.

Before you create a relationship, you must first define a primary key or unique constraint for your table. You then relate the primary key column to a matching column. Once you create the relationship, the matching column becomes the foreign key of the table.

To draw a reflexive relationship

  1. In your database diagram, click the row selector Row selector for the database column that you want to relate to another column.

  2. While the pointer is positioned over the row selector, drag the pointer outside the table until a line appears.

  3. Drag the line back to the selected table.

  4. Release the mouse button. The Create Relationship dialog box appears and attempts to match the primary key columns with the non-key columns you dragged the line to.

  5. Confirm that the columns you want to relate are shown in the Primary key table and Foreign key table lists.

  6. Choose OK to create the relationship.

When you run queries against a table, a reflexive relationship is called a self-join. For information about querying tables with joins, see Querying Using Multiple Tables.


 Mapping Many-to-Many Relationships to a Database Diagram

Mapping Many-to-Many Relationships to a Database Diagram

Many-to-many relationships enable you to relate many rows in one table to many rows in another table. For example, you could create a many-to-many relationship between the authors table and the titles table to match multiple authors to all of their books. Creating a one-to-many relationship from either table would incorrectly assume a book can have only one author, or that an author can write only one book.

Many-to-many relationships between tables are accommodated in database diagrams by means of junction tables. A junction table contains the primary key columns of the two tables you want to relate. You then create a relationship from the primary key columns of each of those two tables to the matching columns in the junction table.

To create a many-to-many relationship between tables

  1. In your database diagram, add the tables that you want to create a many-to-many relationship between.

  2. Create a third table by right-clicking the diagram and choosing New Table from the shortcut menu. This will become the junction table. For details, see Adding Tables to a Database Diagram.

  3. In the Choose Name dialog box, change the system-assigned table name. For example, the junction table between the titles table and the authors table is now named titleauthors. For details, see Renaming a Table.

  4. Copy the primary key columns from each of the other two tables to the junction table. You can add other columns to this table, just as you can to any other table. For details, see Copying Columns from One Table to Another.

  5. In the junction table, set the primary key to include all the primary key columns from the other two tables. For details, see Defining a Primary Key.

  6. Define a one-to-many relationship between each of the two primary tables and the junction table. For details, see Creating a Relationship Between Tables.

    Note The creation of a junction table in a database diagram does not insert data from the related tables into the junction table.


 Checking Existing Data when Creating a Relationship

Checking Existing Data when Creating a Relationship

Select the option to check existing data when you create a relationship if the foreign key constraint should apply to existing data as well as to new data.

Note Some databases have different functionality for foreign key constraints. Consult your database documentation for details about how your database works with foreign key constraints.

To check existing data when creating a relationship

  1. In your database diagram, select the table that the foreign key constraint is attached to.

  2. Right-click the table and select Properties.

  3. Choose the Relationships tab.

  4. Select the relationship from the Selected relationship list.

  5. Select the Check existing data on creation check box.

This option is not selected by default. The foreign key constraint is applied when you save the table or diagram. If any constraint violations are encountered during the save process, the table cannot be saved.


Renaming a Relationship

You can rename a relationship if you want to abbreviate the system-assigned relationship name, or if you want to replace it with a user-defined name. When you rename a relationship, the relationship name is automatically updated in the current diagram and any other diagram in which it appears.

To rename a relationship

  1. In your database diagram, select the line representing the relationship that you want to rename.

  2. Right-click the relationship line and select Properties.

  3. Choose the Relationships tab.

  4. In the Relationship name box, type a new name. Make sure that it doesn’t duplicate any of the names in the Selected relationship list.

The relationship is renamed in the diagram and any other diagram in which it appears as soon as you exit the Relationship name box; it is renamed in the database when you save either of the related tables or the diagram.

Tip If you want to see labels for relationship lines, use the Show Relationship Labels command. For more information on relationship labels and this command, see Adding Labels to Relationship Lines.


Deleting a Relationship

Delete a relationship when you no longer want to relate columns in two related tables. When you redesign tables, it’s often necessary to delete relationships and then recreate them after your new design is complete. For example, if you decide to normalize a database and store all address data in one table, you would delete all the relationships to address columns between existing tables, create a new table containing the address columns, and then create relationships from the new address table to every table that requires an address.

To delete a relationship

  1. In your database diagram, select the line that represents the relationship that you want to delete from the diagram.

  2. Right-click the relationship line and choose Delete Relationship from Database from the shortcut menu.

  3. A message box prompts you to confirm the deletion. Choose Yes.

Note When you delete a relationship, the relationship line is removed from your diagram and every other diagram in which it appears. It is deleted from the database when you save the diagram or either of the tables that it related.


 Triggers

Triggers

A trigger is a special kind of stored procedure that goes into effect when you modify data in a specified table using one or more data modification operations: UPDATE, INSERT, or DELETE. Triggers can query other tables and can include complex SQL statements. They are primarily useful for enforcing complex business rules or requirements. For example, you could control whether to allow an order to be inserted based on a customer's current account status.

Triggers are also useful for enforcing referential integrity, which preserves the defined relationships between tables when you add, update, or delete the rows in those tables. However, the best way to enforce referential integrity is to define primary key and foreign key constraints in the related tables. If you use database diagrams, you can create a relationship between tables to automatically create a foreign key constraint. For details, see Table Relationships.

Advantages of Using Triggers

Triggers are useful in these ways:

  • Triggers are automatic: they are activated immediately after any modification to the table’s data, such as a manual entry or an application action.

  • Triggers can cascade changes through related tables in the database. For example, you can write a delete trigger on the title_id column of the titles table to cause a deletion of matching rows in other tables. The trigger uses the title_id column as a unique key to locate matching rows in the titleauthor, sales, and roysched tables.

  • Triggers can enforce restrictions that are more complex than those defined with check constraints. Unlike check constraints, triggers can reference columns in other tables. For example, a trigger can roll back updates that attempt to apply a discount (stored in the discounts table) to books (stored in the titles table) with a price of less than $10.

For details about working with triggers, see the following topics:

To | See
Create new triggers | Creating a Trigger
Open existing triggers | Opening a Trigger
Save triggers to your project | Saving a Trigger
Change the name of a trigger | Renaming a Trigger
Delete stored triggers | Deleting a Trigger


 Creating a Trigger

Creating a Trigger

A trigger is a database object that you create by specifying:

  • The current table.

  • The data modification transactions that activate the trigger: adding new data (INSERT), updating existing data (UPDATE), or deleting existing data (DELETE).

  • The actions that the trigger will take immediately following the transactions you specified.

You write triggers in Transact-SQL for Microsoft® SQL Server™ databases.

To create a trigger

  1. In the Database window, click Tables [image] under Objects.

  2. Right-click the name of the table that you want to create a trigger on.

  3. Choose Triggers from the shortcut menu.

  4. In the Triggers for Table: <table name> dialog box, click New.

    A new trigger is created in a source code editor with the default SQL statements already defined for you.

    Trigger in the source code editor

  5. Modify the default trigger text as follows:
    Replace | With
    TABLE1_Trigger1 | The name you want to assign to the trigger
    dbo.TABLE1 | The name of the table you want to attach the trigger to
    /*Insert, Update, Delete*/ | The type of transactions that will activate this trigger
    /*If Update (column_name) …*/ | The transactions that will take place
  6. Write the remaining trigger text in SQL.

For syntax and examples of triggers, see your database documentation.

Note Include both a RAISERROR statement and ROLLBACK transaction together in a trigger for situations when the trigger determines that a modification must be disallowed. This will ensure that the client record set stays in synch with the data at the server. If you include only the RAISERROR statement or ROLLBACK transaction, but not both, the client record set will not reflect the current state of the data at the server. The RAISERROR statement should be defined with a severity level greater than 10. For more information, see RAISERROR and ROLLBACK Transaction in your database documentation.


 Opening a Trigger

Opening a Trigger

You can open a trigger to view or edit the text of an existing trigger that is stored in your database. Triggers are scripted in Transact-SQL for Microsoft® SQL Server™ databases.

To open a trigger

  1. In the Database window, click Tables [image] under Objects.

  2. Right-click the name of the table whose trigger you want to open and choose Triggers from the shortcut menu.

  3. In the Triggers for Table: <table name> dialog box, select the trigger you want to open from the Trigger Name list, and then click Edit.

The trigger is opened in a source code editor that you can use to edit the SQL statements. For details about editing the Transact-SQL syntax of a trigger for your database, search for "CREATE TRIGGER Statement" in the Transact SQL Reference in Microsoft Access Help.


 Saving a Trigger

Saving a Trigger

To add a new trigger to the database or to update an existing trigger that you have modified, you can save a trigger.

To save a trigger

  1. From the File menu, choose Save.

  2. If you are updating an existing trigger, a message box prompts you to confirm the save action. Choose Yes.


 Renaming a Trigger

Renaming a Trigger

When you change the name of a trigger, the trigger name is updated in your database as soon as you save the trigger. However, you'll need to update any references to the previous name in other areas where you've referenced it, such as in code.

To rename a trigger

  1. Open the trigger. For details, see Opening a Trigger.

  2. In the source code editor, replace the existing trigger name with the new name. (The trigger name appears after the Create Trigger statement.)

  3. Save the trigger. For details, see Saving a Trigger.

  4. Delete the old trigger (unless you want two identical triggers with different names). For details, see Deleting a Trigger.

The new trigger name is now in the database.

For more information about editing the Create Trigger statement, see Creating a Trigger.


 Deleting a Trigger

Deleting a Trigger

When you want to disable the actions defined in the trigger that are automatically carried out on your database immediately following the specified transactions, you can delete a trigger.

You might also want to delete any triggers that enforce referential integrity between related tables if you use database diagrams to design your database. Database diagrams use relationships instead of triggers for this purpose. Thus, if a trigger duplicates a relationship in a database diagram, you should delete either the trigger or the relationship. For information about deleting relationships, see Deleting a Relationship.

To delete a trigger

  1. In the Database window, click Tables [image] under Objects.

  2. Right-click the table whose trigger you want to delete and choose Triggers from the shortcut menu.

  3. In the Triggers for Table: <table name> dialog box, select the trigger you want to delete from the Trigger Name list, and then click Delete.

  4. A message prompts you to confirm the deletion. Choose Yes.


 Designing Queries

Designing Queries

In a Microsoft Access project, "queries" are views, and SQL statements stored in the RecordSource property of a form, report, or section of a data access page. You create views from scratch, whereas Microsoft Access creates SQL statements in the RecordSource property for you. It creates the SQL statements when you use a wizard to create a single form (not a form with a subform or linked form), report, or data access page based on more than one table.

To create a view, or to modify the underlying view or SQL statement for a form or report, you use the Query Designer. The Query Designer is displayed when you open a view in Design view from the Database window or when you click the Build button next to the RecordSource property of a form or report that has a view or SQL statement as the record source.

Note Though a stored procedure is also a query, you don't use the Query Designer to create it. Instead, you use the Stored Procedure window in Design view. For information about creating and working with stored procedures, search Help for "stored procedures."

To | See
Learn what a view is and how it's used | Working with Views
Read about the user interface for the Query Designer | Query Designer Layout
Learn about what types of queries you can create in the Query Designer | Supported Query Types
Read about the basic steps involved in creating or modifying a query | Creating or modifying a Query
Move around in the different panes of the Query Designer | Navigating in the Query Designer
Use data in different languages in the Query Designer | Using Query Designer With International Data

What You Can Do in the Query Designer

Using the Query Designer, you can:

  • Create or modify queries to retrieve data from Microsoft® SQL Server™ database.

  • Specify elements, such as which tables (or views) and columns to display, how to order query results (except for views), and what values to search for.

  • Join tables to create multi-table queries.

If you are familiar with SQL, you can also enter SQL statements directly or edit the SQL statements created by the Query Designer.


 Supported Query Types

Supported Query Types

Whether you're creating a view, or modifying a view or SQL statement stored in the RecordSource property of a form or report, the Query Designer supports Select queries. If you want to run Insert Values (Append), Update, Delete, Make-Table, or other special-purpose queries, you must use a stored procedure. If you want to run Parameter queries, you can use either a stored procedure, or a SQL statement in the RecordSource property of a form or report.

You can design your view, or SQL statement in the RecordSource property, to group and summarize data. For SQL statements, you can also specify a sort order either in the grid or by using the ORDER BY clause in the SQL pane in the Query Designer. For views, you can't specify a sort order in the grid or SQL pane of the Query Designer. To sort the results of a view, use the Sort buttons on the toolbar available in Datasheet view.


 Working with Views

Working with Views

A view is a query that acts as a virtual table. A view looks like a real table, with a set of named columns and rows of data. However, a view does not exist as a stored set of data values in a database. Instead, it is a query result set that is maintained on the server and updated each time you open the view. You can use a view to extract and combine just the information you need from one or more existing tables.

The data displayed in a view is stored in the database tables. You can open a view and modify the data that appears inside it. When you modify the data you see in a view, you are actually changing data in the underlying database tables. Changes to data in those tables are automatically reflected in the views derived from them.

For more information about views, see Designing Queries in the Query Designer.


 Query Designer Layout

Query Designer Layout

The Query Designer consists of three panes: the Diagram pane, the Grid pane, and the SQL pane.

  • The Diagram pane displays the input sources (tables or views) which you are querying. Each window represents an input source and shows the available data columns as well as icons that indicate how each column is used in the query. Joins are indicated by lines between the input source windows. For more information, see Diagram Pane.

  • The Grid pane contains a spreadsheet-like grid in which you specify query options, such as which data columns to display, what rows to select, how to group rows, and so on. For more information, see Grid Pane.

  • The SQL pane, which you display by pointing to Show Panes on the View menu, and then choosing SQL, displays the SQL statement for the current query. You can edit the SQL statement created by the Query Designer or you can enter your own SQL statement. It is particularly useful for entering SQL statements that cannot be created using the Diagram and Grid panes, such as Union queries. For more information, see SQL Pane.

You can create or modify a query by working in all of the panes: you can specify a column to display by choosing it in the Diagram pane, entering it into the Grid pane, or making it part of the SQL statement in the SQL pane. The Diagram, Grid, and SQL panes are synchronized — when you make a change in one pane, the Query Designer updates the other panes to reflect the change.


 Navigating in the Query Designer

Navigating in the Query Designer

You can work in the Query Designer using the keyboard or the mouse. Refer to the following tables for specific methods.

Any Pane

To | Press | Click
Move among the Query Designer panes | F6, SHIFT+F6 | Anywhere in the target pane

Diagram Pane

To | Press | Click
Move between input source windows (and to join lines, if available) | TAB, SHIFT+TAB | The input source window or join line to move to
Move between columns in an input source window | Arrow keys | The column to go to
Choose the selected data column for output | SPACEBAR1 or PLUS key | The check box next to the name of the column
Remove the selected data column from the query output | SPACEBAR1 or MINUS key | The check box next to the name of the column
Remove the selected input source or join line from the query | DELETE | Right-click, and then choose Remove

1If multiple items are selected, pressing this key affects all selected items. Select multiple items by holding down the SHIFT key while clicking them. Toggle the selected state of a single item by holding down CTRL while clicking it.

Grid Pane

To | Press | Click
Move among cells | Arrow keys or TAB or SHIFT+TAB | The target cell
Move to the last row in the current column | CTRL+DOWN ARROW |
Move to the first row in the current column | CTRL+UP ARROW |
Move to the first position in the current cell or the first column in the input source window | CTRL+HOME |
Move to the last position in the current cell or the last column in the input source window | CTRL+END |
Move in a drop-down list | UP ARROW or DOWN ARROW | The button in the cell
Select an entire grid column | CTRL+SPACEBAR | The column header
Select an entire grid row |  | The button to the left of the row
Toggle between edit mode and cell selection mode | F2 |
Copy selected text in cell to the Clipboard (in edit mode) | CTRL+C |
Cut selected text in cell and place it on the Clipboard (in edit mode) | CTRL+X |
Paste text from the Clipboard (in edit mode) | CTRL+V |
Toggle between insert and overstrike mode while editing in a cell | INS |
Toggle the check box in the Output column | SPACEBAR1 | The check box
Clear the selected contents of a cell | DELETE |
Remove row containing selected data column from the query | DELETE1 |
Clear all values for a selected grid column | DELETE |
Insert row between existing rows | INS after you select grid row |
Add an Or … column | INS after you select any Or ... column |

1If multiple items are selected, pressing this key affects all selected items.

SQL Pane

You can use the standard Windows editing keys when working in the SQL pane, such as CTRL+Arrow keys to move between words, and the Cut, Copy, and Paste commands on the Edit menu.

Note You can only insert text; there is no overstrike mode.


 Using the Query Designer with International Data

Using the Query Designer with International Data

You can use the Query Designer with data in any language and in any version of Windows®. The following guidelines outline the differences you will notice, and they provide information about managing data in international applications.

Localized Information in the Grid and SQL Panes

If you are using the Grid pane to create your query, you can enter information in the format that corresponds to the Windows Regional Settings for your computer. For example, if you are searching for a date, you can enter the date in the Criteria columns using whatever format you are accustomed to using, with these exceptions:

  • Long date formats are not supported.

  • Currency symbols should not be entered in the Grid pane. However, the correct symbol will appear in Datasheet view.

    Note You may enter the $ currency symbol, but the datasheet will return the currency symbol that corresponds to the Windows Regional Settings for your computer.

  • Unary minus always appears on the left side (for example, -1) regardless of the Regional Settings options.

In contrast, data and keywords in the SQL pane must always be in ANSI (U.S.) format. For example, as the Query Designer builds a query, it inserts the ANSI form of all SQL keywords such as SELECT and FROM. If you add elements to the statement in the SQL pane, be sure to use the ANSI-standard form for the elements.

When you enter data using locale-specific format in the Grid pane, the Query Designer automatically translates it to ANSI format in the SQL pane. For example, if your Regional Settings are set to Standard German, you can enter a date in the Grid pane in a format such as "31.12.96." However, the date will appear in the SQL pane in ANSI datetime format as { ts '1996-12-31 00:00:00' } If you enter data directly in the SQL pane, you must enter it in ANSI format.

Sort Order

The sort order (collation sequence) of data in your query is determined solely by the database. Options that you set in the Windows Regional Settings dialog box do not affect sort order for queries.

Using Double-Byte Characters

You can enter DBCS characters for literals and for database object names such as table and view names or aliases. You can also use DBCS characters for parameter names and parameter marker characters. However, you cannot use DBCS characters in SQL language elements such as function names or SQL keywords.


 Query Designer Considerations for SQL Server Databases

Query Designer Considerations for SQL Server Databases

When creating queries using the Query Designer, follow Microsoft® SQL Server™ guidelines. Below you will find information about:

  • SQL Server Version

  • SQL Syntax

  • Identifying Database Objects

  • Using Quotation Marks

  • Case Sensitivity

  • Creating Aliases

  • Using Operators in Expressions

  • Entering Keywords in the Grid and SQL Panes

  • Entering Currency Values

  • Using DISTINCT

  • Creating Outer Joins

  • Using the GUID Data Type

  • Entering Blanks

  • Including Optimizer Hint Comments

  • Working with Tables from Different Data Sources

SQL Server Version

The Query Designer is designed to support version 6.5 and 7.0 of the Microsoft SQL Server. If you attempt to use a SQL Server 7.0 feature when connected to version 6.5 of the SQL Server, the server will report an error.

SQL Syntax

When the Query Designer builds a statement in the SQL pane, it will use syntax specific to SQL Server whenever possible. For example, database objects such as tables and views are qualified using SQL Server owner names.

You can also type SQL Server-specific syntax in the SQL pane yourself. In some cases when you verify a query, the Query Designer converts server-specific syntax to ANSI standard syntax. However, the changed query will always return the same results.

Identifying Database Objects

When you enter the names of database objects (tables, views, and columns) in the SQL pane, you must provide sufficient information for SQL Server to identify the object you want. Database objects are identified with unique names that consist of up to three parts (for tables and views) or four parts (for columns):

database.owner.table

database.owner.table.column

In general, you need to provide only enough qualifiers to uniquely identify the object you want to work with. For example, if you are working with a column called price in the titles table in the current database, you can simply reference the column by name, as in this SQL statement:

SELECT price
FROM titles

However, if you are working with two tables such as orders and products, and each has a column called price, you must qualify references to the column with the appropriate table name, as in this example:

SELECT products.prod_id, orders.price
FROM orders INNER JOIN products ON
 orders.prod_id = products.prod_id

When you use the Diagram pane and Grid pane to work with tables in the current database, the Query Designer automatically adds owner and table qualifiers for you. If you are not the owner of a table that you are working with, the owner’s name will appear in the table names. For example, if you work in the pubs database, the owner name dbo will appear in front of table names. If you are working with multiple tables, the Query Designer adds table name qualifiers to column names.

For compatibility with other databases, you can use [ and ] around identifier names in the SQL pane. When the SQL statement is reformatted, [ and ] are replaced with double quotation marks ("), which are used to mark database identifiers.

Using Quotation Marks

The standard delimiters for literal strings in SQL are single quotation marks ('). By default, SQL Server reserves double quotation marks (") as delimiters for database objects (see Identifying Database Objects, above).

The SQL Server OLEDB provider supports a Quoted Identifiers setting for the session or connection. If this setting is on, double quotation marks are interpreted as delimiters for identifiers. However, if you turn this setting off, double quotation marks are interpreted instead as delimiters for literal strings.

To avoid ambiguity, the Query Designer always sets Quoted Identifiers on, so that double quotation marks are always interpreted as database object delimiters. If you have previously turned Quoted Identifiers off, the Query Designer overrides your setting.

Therefore, in the Query Designer, always use single quotation marks to enclose string literals. Use double quotation marks only as needed for database objects delimiters.

Case Sensitivity

Text information in a SQL Server database can be stored in uppercase letters, lowercase letters, or a combination of both. For example, a last name can appear as "SMITH," "Smith," or "smith."

Depending on how SQL Server was installed, databases can be case-sensitive or case-insensitive. If a database is case-sensitive, when you search for text data, you must construct your search conditions using the exact combination of uppercase and lowercase letters. For example, if you are looking for a name such as "Smith," you cannot use the search conditions "=smith" or "=SMITH."

In addition, if the server was installed as case-sensitive, you must provide database, owner, table, and column names using the correct combination of uppercase and lowercase characters. If the case of the name you provide does not match exactly, SQL Server returns an error reporting an "invalid object name."

Note The server's case sensitivity settings do not affect the names of objects stored in the Microsoft Access project (forms, reports, macros, and modules), or data access pages. If any of these objects reference table or column names from the SQL Server database, case sensitivity is ignored. Therefore, if your database is case-sensitive and you have objects with the same name but different case (Authors vs. AUTHORS, for example) you may get unexpected results because the Microsoft Access project won't distinguish between the two. In addition, any local sorting performed on data won't be case sensitive. When you create queries using the Diagram and Grid panes, the Query Designer will always accurately reflect the case sensitivity of your server. However, if you enter queries in the SQL pane, you must be careful to match names to the way they will be interpreted by the server.

If the server was installed with a case-insensitive option, you can enter database object identifiers and search conditions using any combination of uppercase and lowercase characters.

Tip To determine the case sensitivity of a server, execute the stored procedure sp_server_info, and then examine the contents of row 18. If the server has been installed with the case-insensitive setting, the option for sort_order will be set to nocase.

Creating Aliases

In the SQL pane, you can use the = operator to specify an alias, as in this example:

SELECT tax = price * .1
FROM table

When you change panes or execute the query, the SQL statement is reformatted and the = is replaced with AS.

Using Operators in Expressions

The SQL Server supports all standard operators for expressions, including % for modulus. In addition, you can use the following bitwise operators in expressions:

Operator | Meaning
& | BITAND
| | BITOR
^ | BITXOR
~ | BITNOT

Entering Keywords in the Grid and SQL Panes

The Query Designer supports the use of certain SQL Server constants, variables, and reserved column names in the Grid or SQL panes. Generally, you can enter these values by typing them in, but the Grid pane will not display them in drop-down lists. Examples of supported names include:

  • IDENTITYCOL If you enter this name in the Grid or SQL pane, the SQL Server will recognize it as a reference to an auto-incrementing column.

  • Predefined global values You can enter values such as @@CONNECTIONS and @@CURSOR_ROW into the Grid and SQL panes.

  • Constants (niladic functions) You can enter constant values such as CURRENT_TIMESTAMP and CURRENT_USER in either pane.

  • NULL If you enter NULL in the Grid or SQL panes, it is treated as a literal value, not a constant.

Entering Currency Values

In the Grid pane, to specify that you want data interpreted as money, precede the value with $ or $- (for negative values). Do not include a comma or other delimiter to indicate thousands. Formatting values this way alerts the Query Designer that you are entering values to be treated as or compared to data in money or smallmoney type columns. Values are rounded to the nearest hundredth of a unit.

You can use $ no matter what currency you are working with. When a query displays values from money columns in the datasheet, it does not include the $ prefix. Depending on the setting in the Windows Regional Settings dialog box, currency data might or might not include a comma or other delimiter for thousands.

Using DISTINCT

If you are working with SQL Server version 6.5, using the DISTINCT keyword creates a query that cannot be updated in Datasheet view.

Creating Outer Joins

In the SQL pane, you can use the SQL Server-specific *= and =* operators to specify an outer join. When you change panes or execute the query, the Query Designer reformats your SQL statement, and replaces *= with LEFT OUTER JOIN and =* with RIGHT OUTER JOIN.

Using the GUID Data Type

In Microsoft SQL Server 7.0, you can include references to the new GUID data type, which is used to store globally unique identifiers. In Update and Insert queries you can call the newid( ) function to generate a new GUID to be stored in the database.

When you are creating a Select query, the only operations allowed with a GUID type column are comparisons based on equality (= and <>).

Entering Blanks

If you are working with Microsoft SQL Server 7.0, you can specify a zero-length string in an Update or Insert Values query by entering two single quotation marks, as in the following example:

UPDATE  employee
SET     minit = ''
WHERE   emp_id = 'CFS88322F'

In SQL Server 6.5, two single quotation marks are treated as a single space. For example, you can use quotation marks in the following expression: 'abc' + '' + 'def'. The resulting value would be 'abd def'.

Including Optimizer Hint Comments

If you are entering a query directly in the SQL pane, you can add optimizer hints to specify the use of specific indexes, locking methods, and so on. However, when reformatting the contents of the SQL pane, the Query Designer might not maintain these comments. Optimizer comments are not represented graphically.

For more details about optimizer hints, refer to the Microsoft SQL Server documentation.

Working with Tables from Different Data Sources

If you are using SQL Server 7.0, you can create distributed, heterogeneous queries —queries from input sources (tables and views) outside the server to which you have created a data connection. SQL Server can access any data source that supports OLE DB. You can use input sources from these outside data sources as you would any tables available on the base server (if you have proper permissions to access to the outside data source).

Microsoft SQL Server 7.0 can access outside data sources in two ways. The first is using a linked server, which is defined in the SQL Server database to point to the outside data source. A linked server makes the data source accessible using a naming convention similar to that of native SQL Server data objects. The second is to use a dynamic reference to the outside source using the OpenRowSet( ) function, which allows you to connect to any accessible data source in your query, even if no linked server is defined for it.

Input sources from outside servers do not appear as part of the list of input sources. Instead, to use them, you use syntax in the SQL pane of the Query Designer to refer to the linked server or to include the OpenRowSet( ) function. However, when you refer an outside data source in the SQL pane, the Query Designer adds an input source window to the Diagram pane to represent the outside data source.

To refer to an outside data source using a linked server

  • In the SQL pane, use the following syntax to refer to the table:
    linkserver.catalog.schema.object

    Where:

    • linkserver represents the name on the local Microsoft SQL Server 7.0 data source given to the linked server in OLE DB.

    • catalog represents the name of the database containing the object.

    • schema represents the owner of the object.

    • object represents the table or view in the database.

Note You must define the SQL Server data source (the linkserver part of the name) before you use this name in the query. Data sources you specify will not appear in the Database window. They are only used in the context of the query.

The following is an example of an SQL statement that joins data from tables from the local database with a table on a server called "hrserver":

SELECT e.id, e.lname, h.hiredate
FROM employee AS e INNER JOIN hrserver.hr.dbo.hiredata AS H
ON e.emp_id = h.emp_id

To refer to an outside data source dynamically

  • In the SQL pane, use the OpenRowset( ) function in place of a table reference, with the following syntax:
    OpenRowSet(provider,connectString,object)

    Where:

    • provider represents the friendly name of the OLEDB provider.

    • connectString represents a string that includes information for connecting to the outside data source. This parameter is optional if an ODBC connection is already established between the local server and the outside data source. The connectString parameter can take these forms:

      datasource;user id;password, which lists specific connection attributes.

      -or-

      provider string, which is a single string of named attributes with values for creating the connection, similar to the string used in a .dsn file.

    • object represents the name of a database object. You can refer to a table, view, or other database object using the standard naming convention recognized by the outside data source.

Tip The data source referenced by OpenRowSet( ) is easier to work with if you assign it a table alias.

The following examples illustrate variations on using OpenRowSet( ) to dynamically access data from an outside data source. The first two show access using a set of attributes for the connect string, the first to an Oracle database and the second to a Microsoft® Jet (Access) database. The third example shows how you can pass a connect string.

SELECT t.*
FROM OpenRowSet('MSDASQL', 'OracleDB';'user1';'pwd', pubs.dbo.titles)
AS t

SELECT n.*
FROM OpenRowSet('Microsoft.jet.OLEDB.3.51',
    'c:\nwind.mdb';'admin';'pwd', authors)
AS n

SELECT a.*
FROM OpenRowSet('MSDASQL', 'Driver=SQL Server;Server=Test;
    UID=user1;PWD=pwd', pubs.dbo.authors)
AS a


 Creating or modifying a Query

Creating or Modifying a Query

The basic process of creating or modifying a query is the same, whether it's a view, or an SQL statement in the RecordSource property of a form or report, and regardless of the options you specify. It consists of these steps:

  1. Starting a new query or opening an existing one to modify it. For details, see Work with a Query.

  2. Choosing one or more input sources (tables or views) to work with. For details, see Adding Input Sources to a Query.

  3. Specifying the data columns to work with in the query, such as the columns to display or to use in search conditions. For details, see Adding Columns to a Query.

  4. For an SQL statement in the RecordSource property, specifying the order for rows in the query output, if appropriate. For details, see Ordering Query Results.

  5. Specifying search criteria to indicate which rows to display. For details, see Specifying Search Conditions.

  6. Running the query. For details, see Executing a Query.

You can use additional Query Designer features to create more complex queries. For example, you can create queries that:

  • Join two or more tables to display data from multiple tables in one query. For details, see Querying Using Multiple Tables.

  • Produce summary information such as totals, averages, and so on. For details, see Summarizing and Grouping.


Work with a Query

The Query Designer features an easy-to-use interface for working with your queries (views, and SQL statements in the RecordSource property of a form or report). The topics in this section describe the fundamentals of working with a query, including how to choose a table or view to work with, how to add or remove data columns from the query, and how to execute the query.

To | See
Create a new view | Creating Views
Modify an existing view or SQL statement in the RecordSource property of a form or report | Modify the underlying query or SQL statement for a form or report
Add or remove input sources from a query | Adding Input Sources to a Query Removing Input Sources from a Query
Add or remove columns from a query or from the query output | Adding Columns to a Query Removing Columns from Query Output Removing Columns from the Query
Change how query results are displayed | Reordering Output Columns in a Query Ordering Query Results
Print the query results | Print the datasheet of a table, query, or Form
Create aliases for tables or columns | Creating Table Aliases in a Query Creating Column Aliases in a Query
Specify parameters in the SQL statement of the RecordSource property in a form or report | Using parameters in the SQL statement of a RecordSource property in a form or report
Check the syntax of a query | Verifying a Query
To run or stop a query | Executing a Query Stopping a Query


 Creating Views

Creating Views

To create a view

  1. In the Database window, click Views [image] under Objects.

  2. On the Database window toolbar, click New.

    The Query Designer opens with a blank view with a temporary name.

  3. Create the view as you would create any query. Include all the search condition information that will become part of your view. For details about creating queries, see Working with a Query.

  4. To save the view and assign it a name, choose Save from the File menu. In the Save As dialog box, type the name for your view, following the naming conventions for your database.

    The new view is added to the list of views in the Database window.

Microsoft® SQL Server™ enables you to encrypt a view, which prevents people from viewing or editing it.

To encrypt a view

Caution After you encrypt a view and close it, you will not be able to open and edit it again.

  1. Open the view to encrypt.

  2. Right-click anywhere in the Query Designer except on an input source window in the Diagram pane, and then choose Properties.

  3. Choose Encrypt view, and then close the property page.

The Query Designer encrypts your view the next time you save it. You can continue to work with the view until you close the Query Designer. After that, you will no longer be able to edit the view, although you will be able to use it as an input source.


 Adding Input Sources to a Query

Adding Input Sources to a Query

When you run a query, you are retrieving data from an input source: one or more tables or views. To work with input sources in your query, you add them to the Diagram pane.

To add a table or view to the query

  1. With the Query Designer open, right-click in the Diagram Pane, and then choose Show Table on the shortcut menu. In the Show Table list, select a table, view, or column, and then drag it into the Diagram pane of the Query Designer.

The Query Designer updates the SQL pane with a skeleton Select query.

If you drag an individual data column into the Diagram pane, the column is added to the query for output. If the table from which you drag the column has not already been added, the Query Designer adds the table with the specified column selected as an input source to the query.

You can also drag columns or tables from a Database Diagram, drag tables from the Database window, or paste columns and tables from the Clipboard. For information about using Database Diagrams, see Working in Database Diagrams.

Tables and views are automatically added to the query when you reference them in the statement in the SQL pane.

The Query Designer will not display data columns for an input source if you do not have sufficient access rights to the input source or if the Microsoft provider for SQL Server cannot return information about an input source you are using (for example, if no such table currently exists). In such cases, only a title bar is displayed for the input source window and the * (All Columns) check box.


 Removing Input Sources from a Query

Removing Input Sources from a Query

You can remove an input source if you no longer need that input source as part of your query.

Note Removing an input source does not delete the underlying table from the database; it only removes the input source from the current query. For details about removing a table from a database, see Deleting a Table from a Database Diagram and the Database.

To remove an input source

  • In the Diagram pane, select the input source, and then press DELETE, or right-click the input source and then choose Remove. You can select and remove multiple input sources at one time.

    –or–

  • Remove all references to the input source in the SQL pane.

When you remove an input source, the Query Designer automatically removes joins that involve that input source and removes references to the input source’s data columns in the SQL and Grid panes. However, if the query contains complex expressions that involve the table, the table name is not automatically removed until all references to the table are removed.


 Creating Table Aliases in a Query

Creating Table Aliases in a Query

Aliases can make it easier to work with table names. Using aliases is helpful when:

  • You want to make the statement in the SQL pane shorter and easier to read.

  • You refer to the table name often in your query — such as in qualifying column names — and want to be sure you stay within a specific character-length limit for your query. (Some databases impose a maximum length for queries.)

  • You are working with multiple instances of the same table (such as in a self-join) and need a way to refer to one instance or the other.

For example, you can create an alias "e" for a table name employee_information, and then refer to the table as "e" throughout the rest of the query.

You create table aliases in the SQL pane; you cannot create them in the Grid pane.

To create a table alias

  1. Add the input sources to your query.

  2. In the FROM clause in the SQL pane, add the alias name to each table you are creating an alias for. For example, to assign the alias "e" to the employee_information table and "p" to the positions table, you can create a FROM clause such as the following:
    FROM employee_information e, positions p

Note You can add the option keyword AS between the table name and alias (for example, FROM employee_information AS e). When you create a table alias, the Query Designer substitutes the alias for the corresponding table name in the Table column of the Grid pane.

Note The SQL standard specifies that when you create an alias for a table name, you must use the alias to refer to the table in the rest of the SQL statement (that is, you cannot use the original table name).


 Adding Columns to a Query

Adding Columns to a Query

To use a column in a query, you must add it to the query window. You might add a column to display it in query output, to search the contents of the column, or to summarize its contents.

When you add a column in the Diagram or Grid panes, the column you add becomes part of the query output. You can remove the column from the output and still use it for sorting, searching, and so on. For example, to find all employees in the accounting department, you might search the department column but not display it in the output.

Tip Wherever you use a column in a query, you can also use an expression that can consist of any combination of columns, literals, operators, and functions. For details, see Using Expressions in Queries.

You can add columns individually or as a group. Your choices are:

  • An individual column from one table, to use for sorting (except in views), searching, or summarizing.

  • All columns from one input source. This is the equivalent of specifying "tablename.*" in the SQL statement.

  • All columns from all input sources, which can be useful if you are working with joined tables. This option is the equivalent of specifying "*" alone in the SQL statement when more than one table is used in the query.

When you add all columns, the Query Designer does not add all individual columns to the query. If you need to work with a specific column, you must add it separately.

Note When you choose "*", all currently defined columns for the tables you are using are included. If a table definition changes, the list of columns returned by "*" changes as well. It is recommended that, if practical, you specify the columns you want to work with instead of using "*".

To add an individual column

  • In the Diagram pane, select the check box next to the data column that you want to include.

    Input source window with column names checked

    -or-

  • In the Grid pane, move to the first blank grid row where you want to add the column, click the field in the Column column, and select a column name from the list.

    Columns in the Grid pane

    Note To add a data row at a specific location in the Grid pane, select the grid row where you want to add the new column and press INS. A new column is added above that row.

To add all columns for one input source

  • In the Diagram pane, select the check box [image] next to (All Columns).

    –or–

  • Specify tablename.* in the SQL statement in the SQL pane, substituting the name of your input source for tablename.

To add all columns for all input sources

  1. Make sure no join lines between input sources in the Diagram pane are selected.

  2. Right-click in the query window and choose Properties from the shortcut menu.

  3. Choose Output all columns.

Or, instead of using the property sheet, you can specify * in the output list of the SQL statement in the SQL pane.


 Removing Columns from Query Output

Removing Columns from Query Output

If you are using a column in a Select query but don’t want to display it in the result set (that is, you don’t want it in the query’s select list), you can remove it from output. After you remove the column from the query’s output, you can still use it in a search condition, to summarize its contents, and so on.

Note If you want to remove a column from the query altogether, see Removing Columns from the Query.

To remove a column from the query output

  • In the Diagram pane, clear the check box next to the name of the column you want to remove.

    -or-

    In the Grid pane, clear the check box in the Output column for the data column you want to remove. (If you want to add the column back to the query output, you can check the Output column again.)

    -or-

  • Remove the column from the output list in the SQL pane.


 Removing Columns from the Query

Removing Columns from the Query

If you no longer want to use a column in a query, you can remove it. If you do, the Query Designer removes references to the column in the display list, the sort specification (where available), the search criteria, and any grouping specifications.

Note If you want to remove a column from just the output of a Select query, you can do so without removing it from the query altogether. For details, see Removing Columns from Query Output.

To remove a column from the query

  • In the Grid pane, select the grid row containing the column you want to remove and then press DELETE.

    -or-

  • Remove all references to the column in the SQL pane.


 Reordering Output Columns in a Query

Reordering Output Columns in a Query

The order in which you add data columns to a Select query determines the order in which they appear in the results. The first column you add to the query appears leftmost in the results, the second column next, and so on.

To control where a data column appears in the result set, or in what order it is used, you can reorder the columns.

To reorder columns for output

  • In the Grid pane, select the row containing the column by clicking the row selector button to the left of the row ( [image]).

    -or-

  • Edit the order of the column names in the SQL pane.

Tip You can add a data row at a specific location in the Grid pane by inserting a blank row into the Grid pane, and then specifying the data column to insert. For details, see Adding Columns to a Query.


 Creating Column Aliases in a Query

Creating Column Aliases in a Query

You can create aliases for column names to make it easier to work with column names, calculations, and summary values. For example, you can create a column alias to:

  • Create a column name, such as "Total Amount," for an expression such as (quantity * unit_price) or for an aggregate function. The alias is used in the column heading in the result set.

  • Create a shortened form of a column name, such as "d_id" for "discounts.stor_id." Using a column alias is particularly useful when the query contains multiple tables, because you can create short aliases to refer to fully qualified column names.

After you have defined a column alias, you can use the alias in a Select query to specify query output.

Note Column aliases do not appear in the list of data columns in the Columns column of the Grid pane. However, you can type in the name of an existing column alias to reference it in the Grid pane.

To create a column alias

  1. In the Grid pane, locate the row containing the data column for which you want to create an alias, and if necessary, mark it for output. If the data column is not already in the grid, add it.

  2. In the Alias column for that row, enter the alias. The alias must follow all naming conventions for SQL (for example, it cannot be a reserved word). If the alias name you enter contains spaces, the Query Designer automatically puts brackets around it.


Verifying a Query

To avoid problems, you can check the query you have built to ensure its syntax is correct. This option is especially useful when you enter statements in the SQL pane.

Note A statement can be valid, and therefore be verified successfully, even if it cannot be represented in the Diagram and Grid panes.

To verify an SQL statement

  • Right-click in the SQL pane, and select [image] Verify SQL Syntax from the shortcut menu.


Executing a Query

When you have finished designing your query, you can run it.

Note If you want to test whether the syntax of the query you are creating is correct, you can verify the query. For details, see Verifying a Query.

To execute a query

  • On the View menu, choose Datasheet View; or, on the Query menu, choose Run.

An SQL statement or view stored in the RecordSource property of a form, report, or section of a data access page executes automatically when you close the Query Designer and switch the form to Form or Datasheet view, the report to Print Preview, or the data access page to Page view or Internet Explorer. Microsoft Access runs queries in batches (incrementally) so that you can begin viewing results in the datasheet as soon as possible, and so that you can perform other tasks while the query is underway.

For information on working with the query's results, ask the Office Assistant about working with data in Datasheet view.


Stopping a Query

If you see that the query is not returning the results you expect, you can stop the query if it has not already finished.

To stop a query

Press CTRL+BREAK.


 Specifying Search Criteria in a Query

Specifying Search Criteria in a Query

To restrict the number of rows a Select query should return, you create search conditions or filter criteria. In SQL, search conditions appear in the WHERE clause of the statement, or if you are creating an aggregate query, in the HAVING clause.

When the query runs, the database engine examines and applies the search condition to each row in the tables you are searching. If the row meets the condition, it is included in the query. For example, a search condition that would find all the employees in a particular region might be:

region = 'UK'

Predicates in Search Conditions

A search condition consists of one or more predicates, each specifying a single condition. If the search condition includes more than one predicate, the predicates are linked with a logical AND (to narrow the search) or OR (to broaden it). The following example shows how you can use multiple conditions when searching an employee table to find the employee (or employees) with the specified first and last names:

WHERE lname = 'Smith' AND fname = 'Jean'

A single predicate follows this format:

search_expression operator search_value

In most instances, search_expression is the name of a column to search. Similarly, the most common form of search_value is a literal value to search for, which can be either a string of characters or a number.

The following two examples show literal values. The first searches for all the employees who are in the United Kingdom, and the second searches for all employees with a specific job level:

WHERE region = 'UK'

WHERE job_lvl = 100

Both search_expression and search_value can consist of any (or any combination) of the following:

  • Literal A single text, numeric, date, or logical value. The following example uses a literal to find all rows for employees in the United Kingdom:
    WHERE region = 'UK'
  • Column reference The name of a column in one of the tables being searched. The following example searches a products table for all rows in which the value of the production cost is lower than the shipping cost:
    WHERE prod_cost < ship_cost
  • Function A reference to a function that the database back end can resolve to calculate a value for the search. The following example searches for orders placed today (the GETDATE( ) function returns the current date):
    WHERE order_date = GETDATE()
  • NULL The following example searches an authors table for all authors who have a first name on file:
    WHERE au_fname IS NOT NULL
  • Calculation The result of a calculation that can involve literals, column references, or other expressions. The following example searches a products table to find all rows in which the retail sales price is more than twice the production cost:
    WHERE sales_price > (prod_cost * 2)
  • Subquery A result set generated by another query. The following example searches a products table to find all the products from Swedish suppliers. The subquery first searches the suppliers table to build a list of the suppliers located in that country. The second search then searches the products table, matching the product’s supplier ID against the list created by the subquery:
    WHERE supplier_id IN
  (SELECT supplier.supplier_id
  FROM supplier
  WHERE (supplier.country = 'Sweden'))

For more details about creating search conditions, refer to the topics listed in the following table.

For information about | See
Specifying search conditions in the Query Designer | Specifying Search Conditions
How to create expressions that you can use in search conditions | Using Expressions in Queries
The operators you can use in search conditions | Comparison Operators, Logical Operators, and Wildcard Characters
How to enter text, numbers, dates, or logical values | Entering Search Values
Finding rows that do not match a value | Selecting Rows that Do Not Match a Value
Removing duplicate rows from Select queries | Excluding Duplicate Rows
Applying multiple search conditions to the same data column | Specifying Multiple Search Conditions for One Column
Including several data columns as part of the search condition for a query | Specifying Multiple Search Conditions for Multiple Columns
Linking search conditions with AND and OR operators | Combining Search Conditions
Using subqueries | Creating Subqueries


 Specifying Search Conditions in a Query

Specifying Search Conditions in a Query

You can specify the data rows that appear in your query by specifying search conditions. For example, if you are querying an employee table, you can specify that you want to find only the employees who work in a particular region.

You specify search conditions using an expression. Most commonly the expression consists of an operator and a search value. For example, to find employees in a particular sales region, you might specify the following search criterion for the region column:

='UK'

Note If you are working with multiple tables, the Query Designer examines each search condition to determine whether the comparison you are making results in a join. If so, the Query Designer automatically converts the search condition into a join. For more information, see Joining Tables Automatically.

To enter search conditions

  1. If you have not already, add the columns or expressions that you want to search to the Grid pane.

    If you are creating a Select query and don’t want the search columns or expressions to appear in the query output, remove them as output columns.

  2. Locate the row containing the data column or expression to search, and then in the Criteria grid column, enter a search condition.

    If you do not enter an operator, the Query Designer automatically inserts the equality operator "=".

The Query Designer updates the SQL statement in the SQL pane by adding or modifying the WHERE clause.


 Creating Subqueries

Creating Subqueries

You can use the results of one query as the input for another. Typically, you use the results of a subquery as a search condition that uses the IN( ) function or EXISTS operator. However, you can also use a subquery as the FROM clause to specify a result set to be used as an input source.

You can create a subquery by entering it in either the Grid pane or SQL pane.

To define an EXISTS subquery in the Grid pane

  1. Create the primary query.

  2. In the Column column for the first empty row in the Grid pane, enter EXISTS followed by the subquery in parentheses.

  3. In the Criteria column for the row containing the subquery, enter TRUE, FALSE, =TRUE, or =FALSE. Entering FALSE or =FALSE results in a NOT EXISTS query.

    Note To create a NOT EXISTS query, create an EXISTS query as listed in the above steps, and set the Criteria column to FALSE. If you enter NOT EXISTS in the Grid pane, the Query Designer will display an error.

If you enter a subquery in the SQL pane, you will probably find it easier to use Cut and Paste commands to create the query.

To define a subquery in the SQL pane

  1. Create the primary query.

  2. In the SQL pane, select the SQL statement, and then use the Cut command to move the query to the Clipboard.

  3. Start the new query, and then use the Paste command to move the first query into the new query’s WHERE or FROM clause.

For example, imagine you have two tables, products and suppliers, and you want to create a query showing all products for suppliers in Sweden. Create the first query on the suppliers table to find all Swedish suppliers:

SELECT supplier_id
FROM supplier
WHERE (country = 'Sweden')

Use the Cut command to move this query to the Clipboard. Create the second query using the products table, listing the information you need about products:

SELECT product_id, supplier_id, product_name
FROM products

In the SQL pane, add a WHERE clause to the second query, then paste the first query from the Clipboard. Place parentheses around the first query, so that the end result looks like this:

SELECT product_id, supplier_id, product_name
FROM products
WHERE supplier_id IN
   (SELECT supplier_id
  FROM supplier
  WHERE (country = 'Sweden'))

Note When you add a subquery to the WHERE clause, the subquery appears in the Criteria column of the Grid pane. You can edit it further in either the Grid pane or SQL pane. However, the input sources, columns, and expressions referenced in the subquery are not displayed in the Diagram or Grid pane.


 Comparison Operators in Query Search Conditions

Comparison Operators in Query Search Conditions

You can use any standard SQL operators in a search condition. When you use operators in a search condition, the following rules apply:

  • The data types of the data used in the comparison must match. That is, only text can be compared to text, numbers to numbers, and so on. Some databases allow you to use a function or keyword (such as CAST) to temporarily convert data to another data type. For details, refer to the documentation for your database.

  • If you compare text data, the result depends on the character set currently in use. For example, if a table was created using Scandinavian characters, the search results might differ depending on whether your current character set (code page) is Scandinavian or another character set.

  • If a comparison value is null, the result is unknown. Nulls are not matched to any value, including other instances of null. For example, if you are searching for a name beginning with the letter "M" or higher (name >= 'M'), and some of the rows contain no value, those rows do not appear, no matter what comparison operator you use.

The following table summarizes search condition operators that are defined for standard SQL.

Note The information in this topic is derived from the rules for standard SQL-92. If you have questions about how to use operators, refer to the documentation for the database that you are using.

Operator Meaning Grid pane example1 SQL pane example
= Equal
= 'Smith'

SELECT fname, lname
FROM employees
WHERE lname = 'Smith'
<>
!= 		Not equal to
<> 'Active'

SELECT fname, lname
FROM employees
WHERE status <> 'Active'
> Greater than
> '01 Jan 1995'2

SELECT fname, lname
FROM employees
WHERE hire_date >
 '01/01/95'
< Less than
< 100

SELECT fname, lname
FROM employees
WHERE job_lvl < 100
>=
!< 		Greater than or equal to
>= 'T'

SELECT au_lname
FROM authors
WHERE au_lname >= 'T'
<=
!> 		Less than or equal to
<= '01 Jan 1995' 2

SELECT fname, lname
FROM employees
WHERE hire_date <=
 '01/01/95'
BETWEEN expr1
AND expr2 		Tests range of values
BETWEEN
'01 Jan 1995'
AND
'31 Dec 1995'2

SELECT fname, lname
FROM employees
WHERE hire_date
 BETWEEN '01/01/95'
 AND '12/31/95'
IS [NOT] NULL Tests whether contents of column or result of expression is null
IS NULL

SELECT fname, lname
FROM employees
WHERE photo_on_file IS NULL
[NOT] LIKE Performs pattern matching (usually restricted to character data types)
LIKE ('MAC%')

SELECT fname, lname
FROM employees
WHERE lname LIKE ('MAC%')
expr1 [NOT] IN
(val1, val2, …)

– or –

expr1 [NOT] IN
(subquery) 		Matches list of specific values by testing whether expr1 appears either in a list of values or in the result set of a subquery
IN ('SW', 'SE')

supplier_id IN
  (subquery)

SELECT fname, lname
FROM employees
WHERE sales_region IN ('SW', 'SE')

SELECT product_name
FROM products
WHERE supplier_id IN
  (SELECT supplier_id
  FROM supplier
  WHERE (country = 'Sweden'))
ANY (SOME) Tests whether one or more rows in the result set of a subquery meet the specified condition. (ANY and SOME are synonyms; the Query Designer will use ANY when creating an SQL statement.)
<> ANY (subquery)

SELECT au_lname, au_fname
FROM authors
where city <> any
 (SELECT city FROM publishers)
ALL Tests whether all rows in the result set of a subquery meet the specified condition
advance > ALL   (subquery)

SELECT title FROM titles
where advance > all
  (SELECT advance FROM
   publishers,titles
  where titles.pub_id
   = publishers.pub_id
  AND pub_name =
   'Alogdata Infosystems')
[NOT] EXISTS Tests whether a subquery returns any results whatsoever (not a specific result)
EXISTS (subquery)

SELECT product_name
FROM products
WHERE EXISTS
  (SELECT * FROM
   orders, products
  WHERE orders.prod_id
  = products.prod_id)

1 For clarity, the Grid pane examples include only one example for each operator and do not indicate which data column is being searched.

2 Dates can be entered in the Grid pane using the format specified in the Windows Regional Settings dialog box. For details, see Entering Search Values.


 Logical Operators in Query Search Conditions

Logical Operators in Query Search Conditions

You can combine or modify search conditions using the standard logical operators listed in the following table. The operators are listed in the order that they are evaluated.

Operator Meaning Example
NOT Logical opposite of condition
SELECT * FROM employee
WHERE NOT (fname = 'Ann')
AND Both conditions must apply
SELECT * FROM employee
WHERE lname = 'Smith' AND fname = 'Ann'
OR Either condition can apply
SELECT * FROM employee
WHERE region = 'UK' OR region = 'FRA'


 Wildcard Characters in Query Search Conditions

Wildcard Characters in Query Search Conditions

You can search for patterns within data columns or expressions by using wildcard characters. For example, you can search for all employees whose last names begin with "Mac" or end with "son."

In this topic, you can read about:

  • Wildcard Characters

  • Searching for Characters Used as Wildcard Characters

  • Searching Datetime Columns

  • Examples of Wildcard Searches

Wildcard Characters

You can use wildcard characters to search any columns that can be treated as text strings. Columns with the data type character can always be treated as text strings; those with datetime data can be treated as text strings.

To search for patterns, use the LIKE operator, and then substitute wildcard characters for one or more characters in the search string. You can use either of the following wildcard characters:

Wildcard character | Meaning
% (percent symbol) | Zero or more characters in that position
_ (underscore) | One character at that position

For example, to search for all names beginning with "Mac," you could specify the search condition LIKE 'Mac%'. To find names such as "Jan," "Jen," and "Jon," you could specify the search condition LIKE 'J_n'.

Searching for Characters Used as Wildcard Characters

In some cases, you might need to search for a string that contains one of the characters used as a wildcard character. For example, in a titles table you might want to find all the publications that contain the string "10%" as part of the title. Because "%" is part of the string you are searching for, you must specify that you mean it as a literal string and not a wildcard character.

To search for characters that can be interpreted as wildcard characters, you can specify an escape character. Place the escape character immediately in front of the "%" or "_" character that you mean literally. To specify the escape character, include an ESCAPE clause immediately after the LIKE search criterion. You can do this in either the Criteria column of the Grid pane or in the SQL pane.

For example, imagine that you want to find all titles that contain the string "10%". Suppose you want to define the character "#" as an escape character, which allows you to include "#" in front of the "%" character that is meant literally. You can enter this in the Grid pane:

LIKE '%10#%%' ESCAPE '#'

The resulting WHERE clause in the SQL statement looks like this:

WHERE title LIKE '%10#%%' ESCAPE '#'

Searching Datetime Columns

When working with a datetime data type column, you can search any portion of the date or time, including text abbreviations of the month and complete years.

For example, in a Microsoft® SQL Server™ database, you can use the following LIKE clause to search for all rows in which the date falls within 1994:

LIKE '%1994%'

The following searches for all rows in which the date falls within the month of January, regardless of year:

LIKE 'Jan%'

For the exact format of the strings you can use to search a datetime column, see the documentation for your database.

Examples of Wildcard Searches

The following examples illustrate the use of wildcard characters.

Search expression Description Sample matches
LIKE 'Mac%'
 Finds values beginning with "Mac" Mac
MacIntosh
Mackenzie
LIKE 'J%n'
 Finds values starting with "J" and ending with "n" Jon
Johnson
Jason
Juan
LIKE '%son'
 Finds values ending with "son" Son
Anderson
LIKE '%sam%'
 Finds values with "sam" anywhere in the string Sam
Samson
Grossam
LIKE '%Mar%'
 Finds values in a datetime column that fall in the month of March, regardless of year 3/1/94
01 Mar 1992
LIKE '%1994%'
 Finds values in a datetime column for the year 1994. 12/1/94
01 Jan 1994
LIKE 'Mac_'
 Finds values with exactly four characters, the first three being "Mac" Mack
Macs
LIKE '_dam'
 Finds values with exactly four characters, the last three being "dam" Adam
Odam
LIKE '%s_n'
 Finds values containing "s" and "n" at the end of the value, with any one character between them and any number of characters in front of them Anderson
Andersen
Johnson
san
sun


 Entering Search Values in a Query

Entering Search Values in a Query

This topic discusses the conventions you must use when entering the following types of literal values for a search condition:

  • Text values

  • Numeric values

  • Dates

  • Logical values

    Note The information in this topic is derived from the rules for standard SQL-92. If you have questions about how to enter search values, refer to the documentation for the database that you are using.

Searching on Text Values

The following guidelines apply when you enter text values in search conditions:

  • Quotation marks Enclose text values in single quotation marks, as in this example for a last name:
    'Smith'

    If you are entering a search condition in the Grid pane, you can simply type the text value and the Query Designer will automatically put single quotation marks around it.

    Note Terms in double quotation marks are interpreted as database objects such as column or table references.

  • Embedding apostrophes If the data you are searching for contains a single quotation mark (an apostrophe), you can enter two single quotation marks to indicate that you mean the single quotation mark as a literal value and not a delimiter. For example, the following condition searches for the value "Swann’s Way":
    ='Swann''s Way'
  • Case sensitivity For details about case sensitivity in SQL Server, see Query Designer Considerations for SQL Server Databases.

    If you are unsure about whether the database uses a case-sensitive search, you can use the UPPER or LOWER functions in the search condition to convert the case of the search data, as illustrated in the following example:

    WHERE UPPER(lname) = 'SMITH'

    For details about the functions to convert to uppercase and lowercase letters, see Functions for Expressions.

Searching on Numeric Values

The following guidelines apply when you enter numeric values in search conditions:

  • Quotation marks Do not enclose numbers in quotation marks.

  • Non-numeric characters Do not include non-numeric characters except the decimal separator (as defined in the Regional Settings dialog box of the Windows® Control Panel) and negative sign (-). Do not include digit grouping symbols (such as a comma between thousands) or currency symbols.

  • Decimal marks If you are entering whole numbers, you can include a decimal mark, whether the value you are searching for is an integer or a real number.

  • Scientific notation You can enter very large or very small numbers using scientific notation, as in this example:
    > 1.23456e-9

    Note For details about entering currency values in SQL Server, see Query Designer Considerations for SQL Server Databases.

Searching on Dates

The format you use to enter dates depends on which pane of the Query Designer you are entering the date into. The Query Designer can work with the following date formats:

  • Locale-specific The format specified for dates in the Windows Regional Settings Properties dialog box.

  • Database-specific Any format understood by the database.

    •

  • ANSI standard datetime   Similar to ANSI-standard date, but uses ‘ts’ instead of ‘d’ and adds hours, minutes, and seconds to the date (using a 24-hour clock), as in this example for December 31, 1990:

    { ts '1990-12-31 00:00:00' }

    In general, Microsoft SQL Server uses the datetime format.

    •

The following table summarizes the date format that you can use in different panes of the Query Designer.

Pane | Date format
Grid | Locale-specific Database-specific ANSI standard Dates entered in the Grid pane are converted to a database-compatible format in the SQL pane.
SQL | Database-specific ANSI standard Dates entered into the SQL pane are converted to the locale-specific format in the Grid pane.

Searching on Logical Values

The following guidelines apply when you enter logical values in search conditions:

  • To search for a value of False, use a zero, as in the following example:

    SELECT * FROM authors
WHERE contract = 0

    •

  • If you are not sure what format to use when searching for a True value, try using 1, as in the following example:

    SELECT * FROM authors
WHERE contract = 1

    •

  • Alternatively, you can broaden the scope of the search by searching for any non-zero value, as the following example:

    SELECT * FROM authors
WHERE contract <> 0

    •


 Using parameters in the SQL statement of a form or report

Using parameters in the SQL statement of a form or report

In some cases you want to create a query that you can use many times, with a different value each time. For example, you might frequently query a titles table to find all the books written by one author. You could run the same query for each request, except that the author’s ID or name would be different each time.

To create a query that can have different values at different times, you use parameters in the SQL statement specified in the RecordSource property of a form or report. A parameter is a placeholder for a value that is supplied when the query runs. For example, in this SQL statement, the question mark (?) represents the parameter for the author’s state:

SELECT au_lname, au_fname
FROM state
WHERE state = ?

Once you've specified the parameters in the query, you must map the parameters to an expression by setting the InputParameters property of the form or report. (If you don't map the parameters, Microsoft Access prompts you to enter a parameter value when you display the form in Form view or Datasheet view or the report in Print Preview.) To map the parameters to an expression that prompts for the author's state each time you run the query, type the following into the InputParameters property box:

P1 char = [Enter authors' state]

Although this example uses "P1" to represent the first parameter, use a name that's meaningful to you. However, do not use a name that starts with the at sign (@) or that duplicates the name of a field that is output in the query's results.

Note When creating parameter queries programmatically instead of in the Query Designer, you can map the parameters to a literal value in the InputParameters property instead of to an expression.

Where You Can Use Parameters

You can use parameters as placeholders for literal values — for either text or numeric values. Most commonly, parameters are used as placeholders in search conditions for individual rows or for groups (that is, in the WHERE or HAVING clauses of an SQL statement).

Specifying Parameters

Within the query, you can specify unnamed parameters. An unnamed parameter is a question mark (?) that you put anywhere in the query that you want to prompt for or substitute a literal value. For example, if you use an unnamed parameter to search for authors by state ID in a titles table, the resulting statement in the SQL pane might look like this:

SELECT au_lname, au_fname
FROM state
WHERE state = ?

As shown previously, you can assign a name to a parameter by mapping the parameter to an expression in the RecordSource property of the form or report. Named parameters are particularly useful if you have multiple parameters in a query. For example, you could use named parameters to search for an author’s first and last names in an authors table.

To specify a parameter

  1. In the Database window, click the form or report that contains the SQL statement you want to add parameters to, and open it in Design view.

  2. Double-click the form selector or the report selector to open the property sheet.

  3. Click the Build button [image] next to the RecordSource property to open the query.

  4. To the Grid pane, add the columns or expressions that you want to search

  5. Locate the row containing the data column or expression to search, and then, in the Criteria grid column, enter a question mark (?).

Note Do not use the Parameters tab on the query property page when creating parameter queries. Microsoft Access does not use these settings when running a parameter query.

Learn about mapping parameters in the InputParameters property.


 Selecting Rows that Do Not Match a Value by Using a Query

Selecting Rows that Do Not Match a Value by Using a Query

To find rows that do not match a value, use the NOT operator. For example, to find all the rows in a products table where the values in the product code column begin with a character other than "A," you can enter a search condition such as the following:

NOT LIKE 'A%'


 Excluding Duplicate Rows from a Query

Excluding Duplicate Rows from a Query

Some Select queries create result sets that contain duplicate rows. For example, the following query for an employee table displays the job code for each row in the table:

SELECT job_id
FROM employee
ORDER BY job_id

Because more than one employee can have the same job, this query can create a result set similar to the following:

job_id

2
3
4
5
5
6
6
...

Note The duplicate rows displayed by the query do not necessarily represent true duplicates in the input source for the query. Instead, they appear as duplicates in the result set because columns that would otherwise distinguish one row from another are not displayed.

If you want to see only unique values in a result set, you can specify that you want to exclude duplicates from the result set.

To exclude duplicate rows from the result set

  1. Ensure nothing is selected, then choose Property Pages from the View menu.

  2. In the Query tab of the Property pages window, select Distinct values.

    The Query Designer inserts the keyword DISTINCT in front of the list of display columns in the SQL statement.

    Note Using the DISTINCT keyword in SQL Server results in a non-editable query.


 Combining Search Conditions in a Query

Combining Search Conditions in a Query

You can create queries that include any number of search conditions, linked with any number of AND and OR operators. A query with a combination of AND and OR clauses can become complex, so it is helpful to understand how such a query is interpreted when you execute it, and how such a query is represented in the Grid and SQL panes.

Note For details about search conditions that contain only one AND or OR operator, see Specifying Multiple Search Conditions for One Column and Specifying Multiple Search Conditions for Multiple Columns.

Below you will find information about:

  • The precedence of AND and OR in queries that contain both.

  • How the conditions in AND and OR clauses relate logically to one another.

  • How the Query Designer represents in the Grid pane queries that contain both AND and OR.

To help you understand the discussion below, imagine that you are working with an employee table containing the columns hire_date, job_lvl, and status. The examples assume that you need to know information such as how long an employee has worked with the company (that is, what the employee’s hire date is), what type of job the employee performs (what the job level is), and the employee’s status (for example, retired).

Precedence of AND and OR

When a query is executed, it evaluates first the clauses linked with AND, and then those linked with OR.

Note The NOT operator takes precedence over both AND and OR.

For example, to find either employees who have been with the company for more than five years in lower-level jobs or employees with middle-level jobs without regard for their hire date, you can construct a WHERE clause such as the following:

WHERE
    hire_date < '01/01/90' AND
    job_lvl = 100 OR
    job_lvl = 200

To override the default precedence of AND over OR, you can put parentheses around specific conditions in the SQL pane. Conditions in parentheses are always evaluated first. For example, to find all employees who have been with the company more than five years in either lower or middle-level jobs, you can construct a WHERE clause such as the following:

WHERE
    hire_date < '01/01/90' AND
    (job_lvl = 100 OR job_lvl = 200)

Tip It is recommended that, for clarity, you always include parentheses when combining AND and OR clauses instead of relying on the default precedence.

How AND Works with Multiple OR Clauses

Understanding how AND and OR clauses are related when combined can help you construct and understand complex queries in the Query Designer.

If you link multiple conditions using AND, the first set of conditions linked with AND applies to all the conditions in the second set. In other words, a condition linked with AND to another condition is distributed to all the conditions in the second set. For example, the following schematic representation shows an AND condition linked to a set of OR conditions:

A AND (B OR C)

The representation above is logically equivalent to the following schematic representation, which shows how the AND condition is distributed to the second set of conditions:

(A AND B) OR (A AND C)

This distributive principle affects how you use the Query Designer. For example, imagine that you are looking for all employees who have been with the company more than five years in either lower or middle-level jobs. You enter the following WHERE clause into the statement in the SQL pane:

WHERE (hire_date < '01/01/90' ) AND
    (job_lvl = 100 OR job_lvl = 200)

The clause linked with AND applies to both clauses linked with OR. An explicit way to express this is to repeat the AND condition once for each condition in the OR clause. The following statement is more explicit (and longer) than the previous statement, but is logically equivalent to it:

WHERE     (hire_date < '01/01/90' ) AND
  (job_lvl = 100) OR
  (hire_date < '01/01/90' ) AND
  (job_lvl = 200)

The principle of distributing AND clauses to linked OR clauses applies no matter how many individual conditions are involved. For example, imagine that you want to find lower or middle-level employees who have been with the company more than five years or are retired. The WHERE clause might look like this:

WHERE
    (job_lvl = 200 OR job_lvl = 300) AND
    (hire_date < '01/01/90' ) OR (status = 'R')

After the conditions linked with AND have been distributed, the WHERE clause will look like this:

WHERE
    (job_lvl = 200 AND hire_date < '01/01/90' ) OR
    (job_lvl = 200 AND status = 'R') OR
    (job_lvl = 300 AND hire_date < '01/01/90' ) OR
    (job_lvl = 300 AND status = 'R')

How Multiple AND and OR Clauses Are Represented in the Grid Pane

The Query Designer represents your search conditions in the Grid pane. However, in some cases that involve multiple clauses linked with AND and OR, the representation in the Grid pane might not be what you expect. In addition, if you modify your query in the Grid or Diagram panes, you might find that your SQL statement has been changed from what you entered.

In general, these rules dictate how AND and OR clauses appear in the Grid pane:

  • All conditions linked with AND appear in the Criteria grid column or in the same Or … column.

  • All conditions linked with OR appear in separate Or … columns.

  • If the logical result of a combination of AND and OR clauses is that the AND is distributed into several OR clauses, the Grid pane represents this explicitly by repeating the AND clause as many times as necessary.

    Note For details about entering dates, see Entering Search Values.

For example, in the SQL pane you might create a search condition such as the following, in which two clauses linked with AND take precedence over a third one linked with OR:

WHERE (hire_date < '01/01/90' ) AND
  (job_lvl = 100) OR
  (status = 'R')

The Query Designer represents this WHERE clause in the Grid pane as follows:

Grid pane showing And and Or criteria for three columns

However, if the linked OR clauses take precedence over an AND clause, the AND clause is repeated for each OR clause. This causes the AND clause to be distributed to each OR clause. For example, in the SQL pane you might create a WHERE clause such as the following:

WHERE (hire_date < '01/01/90' ) AND
  ( (job_lvl = 100) OR
  (status = 'R') )

The Query Designer represents this WHERE clause in the Grid pane as follows:

Grid pane showing And and Or criteria for three columns

If the linked OR clauses involve only one data column, the Query Designer can place the entire OR clause into a single cell of the grid, avoiding the need to repeat the AND clause. For example, in the SQL pane you might create a WHERE clause such as the following:

WHERE (hire_date < '01/01/90' ) AND
  ((status = 'R') OR (status = 'A'))

The Query Designer represents this WHERE clause in the Grid pane as follows:

Grid pane showing And and Or criteria for two columns

If you make a change to the query (such as changing one of the values in the Grid pane), the Query Designer recreates the SQL statement in the SQL pane. The recreated SQL statement will resemble the Grid pane display rather than your original statement. For example, if the Grid pane contains distributed AND clauses, the resulting statement in the SQL pane will be recreated with explicit distributed AND clauses. For details, see "How AND Works with Multiple OR Clauses" earlier in this topic.


 Specifying Multiple Search Conditions for One Column in a Query

Specifying Multiple Search Conditions for One Column in a Query

In some instances, you might want to apply a number of search conditions to the same data column. For example, you might want to:

  • Search for several different names in an employee table or for employees who are in different salary ranges. This type of search requires an OR condition.

  • Search for a book title that both starts with the word "The" and contains the word "Cook." This type of search requires an AND condition.

    Note The information in this topic applies to search conditions in both the WHERE and HAVING clauses of a query. The examples focus on creating WHERE clauses, but the principles apply to both types of search conditions. For details about creating HAVING clauses, see Specifying Conditions for Groups.

To search for alternative values in the same data column, you specify an OR condition. To search for values that meet several conditions, you specify an AND condition.

Specifying an OR Condition

Using an OR condition enables you to specify several alternative values to search for in a column. This option expands the scope of the search and can return more rows than searching for a single value.

Tip You can often use the IN operator instead to search for multiple values in the same data column. For details, see Comparison Operators.

To specify an OR condition

  1. In the Grid pane, add the column to search.

  2. In the Criteria column for the data column you just added, specify the first condition.

  3. In the Or … column for the same data column, specify the second condition.

    Grid pane with alternative criteria for one column

The Query Designer creates a WHERE clause that contains an OR condition such as the following:

SELECT fname, lname
FROM employees
WHERE (salary < 30000) OR (salary > 100000)

Specifying an AND Condition

Using an AND condition enables you to specify that values in a column must meet two (or more) conditions for the row to be included in the result set. This option narrows the scope of the search and usually returns fewer rows than searching for a single value.

Tip If you are searching for a range of values, you can use the BETWEEN operator instead of linking two conditions with AND. For details, see Comparison Operators.

To specify an AND condition

  1. In the Grid pane, add the column to search.

  2. In the Criteria column for the data column you just added, specify the first condition.

  3. Add the same data column to the Grid pane again, placing it in an empty row of the grid.

  4. In the Criteria column for the second instance of the data column, specify the second condition.

    Grid pane with two criteria that must both be met for one column

The Query Designer creates a WHERE clause that contains an AND condition such as the following:

SELECT title_id, title
FROM titles
WHERE (title LIKE '%Cook%') AND
  (title LIKE '%Recipe%')


 Specifying Multiple Search Conditions for Multiple Columns in a Query

Specifying Multiple Search Conditions for Multiple Columns in a Query

You can expand or narrow the scope of your query by including several data columns as part of your search condition. For example, you might want to:

  • Search for employees who either have worked more than five years at the company or who hold certain jobs.

  • Search for a book that is both published by a specific publisher and pertains to cooking.

To create a query that searches for values in either of two (or more) columns, you specify an OR condition. To create a query that must meet all conditions in two (or more) columns, you specify an AND condition.

Note If you are creating queries that include combinations of AND and OR clauses, you must be aware of how the query is interpreted when you execute it. For details, see Combining Search Conditions.

Specifying an OR Condition

To create multiple conditions linked with OR, you put each separate condition in a different column of the Grid pane.

To specify an OR condition for two different columns

  1. In the Grid pane, add the columns you want to search. For details, see Adding Columns.

  2. In the Criteria column for the first column to search, specify the first condition. For details, see Specifying Search Conditions.

  3. In the Or … column for the second data column to search, specify the second condition, leaving the Criteria column blank.

    Grid pane with alternative criteria for two columns

    The Query Designer creates a WHERE clause that contains an OR condition such as the following:

    SELECT job_lvl, hire_date
FROM employee
WHERE (job_lvl >= 200) OR
  (hire_date < '01/01/90')
  4. Repeat Step 3 for each additional condition you want to add. Use a different Or … column for each new condition.

Specifying an AND Condition

To search different data columns using conditions linked with AND, you put all the conditions in the Criteria column of the grid.

To specify an AND condition for two different columns

  1. In the Grid pane, add the columns you want to search.

  2. In the Criteria column for the first data column to search, specify the first condition.

  3. In the Criteria column for the second data column, specify the second condition.

    Grid pane with criteria that must be met for two columns

    The Query Designer creates a WHERE clause that contains an AND condition such as the following:

    SELECT pub_id, title
FROM titles
WHERE (pub_id = '0877') AND (title LIKE '%Cook%')
  4. Repeat Steps 2 and 3 for each additional condition you want to add.


Combining Query Search Conditions When AND Has Precedence

To combine conditions with AND, you put the conditions in the same column of the Grid pane. To combine conditions with OR, you put the first one in the Criteria column and additional conditions into an Or … column.

For example, imagine that you want to find either employees who have been with the company for more than five years in lower-level jobs or employees with middle-level jobs regardless of their hire date. This query requires three conditions, two of them linked with AND:

  • Employees with a hire date earlier than five years ago and with a job level of 100

    -or-

  • Employees with a job level of 200

The following procedure illustrates how to create this type of query in the Grid pane.

To combine conditions when AND has precedence

  1. In the Grid pane, add the data columns you want to search. If you want to search the same column using two or more conditions linked with AND, you must add the data column name to the grid once for each value you want to search.

  2. In the Criteria column, enter all the conditions that you want to link with AND. For example, to link conditions with AND that search the hire_date and job_lvl columns, enter values as shown here:

    Grid pane with criteria that must be met for two columns

    These grid entries produce the following WHERE clause in the statement in the SQL pane:

    WHERE (hire_date < '01/01/91') AND
  (job_lvl = 100)
  3. In the Or … grid column, enter conditions that you want to link with OR. For example, to add a condition that searches for another value in the job_lvl column, enter an additional value as shown here:

    Grid pane showing And and Or criteria for two columns

    Adding a value in the Or … column adds another condition to the WHERE clause in the statement in the SQL pane:

    WHERE (hire_date < '01/01/91' ) AND
  (job_lvl = 100) OR
  (job_lvl = 200)


Combining Query Search Conditions When OR Has Precedence

To link conditions with OR and give them precedence over conditions linked with AND, you must repeat the AND condition for each OR condition.

For example, imagine that you want to find all employees who have been with the company more than five years and those who have lower-level jobs or are retired. This query requires three conditions, a single condition linked to two additional conditions with AND:

  • Employees with a hire date earlier than five years ago, and

  • Employees with a job level of 100 or whose status is "R" (for retired).

The following procedure illustrates how to create this type of query in the Grid pane.

To combine conditions when OR has precedence

  1. In the Grid pane, add the data columns you want to search. If you want to search the same column using two or more conditions linked with AND, you must add the data column name to the grid once for each value you want to search.

  2. Create the conditions to be linked with OR by entering the first one into the Criteria grid column and the second (and subsequent ones) into separate Or … columns. For example, to link conditions with OR that search the job_lvl and status columns, enter values as shown here:

    Grid pane with alternative criteria for two columns

    Entering the values shown in the grid above produces the following WHERE clause in the statement in the SQL pane:

    WHERE (job_lvl = 100) OR (status = 'R')
  3. Create the AND condition by entering it once for each OR condition. Place each entry in the same grid column as the OR condition it corresponds to. For example, to add an AND condition that searches the hire_date column and applies to both OR conditions, enter values as shown here:

    Grid pane showing And and Or criteria for three columns

    Entering the values shown in the grid above produces the following WHERE clause in the statement in the SQL pane:

    WHERE (job_lvl = 100) AND
  (hire_date < '01/01/91' ) OR
  (status = 'R') AND
  (hire_date < '01/01/91' )

    Tip You can repeat an AND condition by adding it once, and then using the Cut and Paste commands from the Edit menu to repeat it for other OR conditions.

The WHERE clause created by the Query Designer is equivalent to the following WHERE clause, which uses parentheses to specify the precedence of OR over AND:

WHERE (job_lvl = 100 OR status = 'R') AND
   (hire_date < '01/01/91')

Note If you enter the search conditions in the format shown immediately above in the SQL pane, but then make a change to the query in the Diagram or Grid panes, the Query Designer recreates the SQL statement to match the form with the AND condition explicitly distributed to both OR conditions.


 About Using Expressions in Queries

About Using Expressions in Queries

You can use an expression anywhere in a query that you can use a column name. Expressions can calculate values to display, be part of search conditions, or combine the contents of data columns. An expression can consist of a mathematical calculation or a string, and can involve any combination of column names, literals, operators, or functions.

Examples of the use of expressions in a query include:

  • In a products table, displaying a discounted price that is calculated by taking 10% off the retail price.

  • Displaying only the first three digits — the area code — of a phone number.

  • Displaying employee names in the format last_name, first_name.

  • Joining two tables, an orders table and a products table, then sorting the query on the total price (order quantity times product price).

  • In an orders table, copying and then deleting all orders that were shipped more than one year ago.

For more information about creating and using expressions, refer to the topics listed in the following table.

For information about | See
How to create expressions | Creating an Expression
How to enter expressions into a query | Using Expressions in a Query
Creating summaries of data | Summarizing and Grouping
Operators you can use in expressions | Operators for Expressions
Functions you can use in expressions | Functions for Expressions
Predefined variables you can use in expressions | Predefined Variables for Expressions


 Creating an Expression in a Query

Creating an Expression in a Query

An expression consists of any combination of column names, literals, operators, or functions. Follow these guidelines in combining elements to form expressions:

  • Reference columns by typing their names. If your query uses more than one table and if you use a column name that is not unique, you must add the table name and a period to the column name. The following example shows the column name job_id qualified with the table name employee:
    employee.job_id
  • Include literal text by enclosing it in single quotation marks; no quotation marks are necessary for numbers.

    Note Though terms in single quotation marks are interpreted as literal values, terms in double quotation marks are interpreted as database objects such as column or table references. For details, see Query Designer Considerations for SQL Server Databases.

  • Use standard arithmetic operators for numbers and a concatenation operator for combining strings. For details, see Operators for Expressions.

  • Include parentheses to establish precedence of operators.

  • If you include a function, use these same guidelines for the arguments passed to the function. That is, reference columns by typing their names, enclose literal text in single quotation marks, and so on. For a list of functions you can use in expressions, see Functions for Expressions.

  • If you pass column names as function arguments, be sure the data type of the column is appropriate for the function argument.

The following table illustrates the use of expressions in a query.

Expression1 Result
SELECT (price * .9)
FROM products 		Displays a discounted price (10% off the value in the price column).
SELECT (lname + ', ' + fname)
FROM employee 		Displays the concatenated values of the last name and first name columns with a comma between them.
SELECT sales.qty, titles.price

FROM sales INNER JOIN titles ON
sales.title_id = titles.title_id
ORDER BY
(sales.qty * titles.price)

 After joining two tables, sorts the result set by the total value of an order (quantity times price). (This example does not apply to views, which don't support ORDER BY in the Query Designer.)
SELECT au_lname, au_fname
FROM authors
WHERE
(SUBSTRING(phone, 1, 3) = '415') 		Displays authors whose area code is in the San Francisco area.
SELECT ord_num, ord_date
FROM sales
WHERE
(ord_date >=
   DATEADD(day, -10, GETDATE())) 		Finds all orders in the sales table that were made in the last 10 days. Today’s date is returned by the GETDATE( ) function.

1For details about what operators and functions you can use, refer to the documentation for your database.


 Using Expressions in a Query

Using Expressions in a Query

To use an expression in a query, you can type it directly into the Grid pane or you can enter it in the SQL pane as part of the statement. Entering expressions is similar to entering column names. For details about how to create an expression, see Creating an Expression.

Tip To make it easier to see long expressions on your screen, you can resize the columns in the Grid pane. For details, see Grid Pane.

In this topic you can read about:

  • Displaying Expressions in the Result Set

  • Sorting Using Expressions

  • Searching Using Expressions

Displaying Expressions in the Result Set

You can display an expression in the result set by specifying the expression in place of a column in the Grid pane.

To display an expression in the result set

  1. In the Grid pane, insert a new grid row.

  2. In the Column column of the new grid row, type the expression you want to display.

    Grid pane with expression in Column column

When you display an expression in the result set, the database assigns a column heading to it using the format "Exprn," where n is the number of the expression in the current query. To assign a more meaningful column heading, you can create an alias for the expression. For details, see Creating Column Aliases.

Sorting Using Expressions

In a SQL statement stored in the RecordSource property of a form or report, you can sort by the results of an expression.

To sort using an expression

  1. In the Grid pane, insert a new grid row.

  2. In the Column column of the new grid row, type the expression you want to sort by.

  3. If you do not want to display the expression in the query, clear the check box in the Output column of the new row.

  4. In the Sort column, choose Ascending or Descending, and then in the Sort Order column, choose the sort priority for the expression.

    5.

Searching Using Expressions

There are two ways to use an expression for searching. The expression can be the condition against which you compare values, or it can function as the value you are comparing.

The following example illustrates how you can use an expression as the condition in a WHERE clause:

SELECT ord_num, ord_date
FROM sales
WHERE (price * .9) > 20

In contrast, the following example illustrates the opposite use of an expression, in which the expression is the value you are comparing:

SELECT ord_num, ord_date
FROM sales
WHERE (ord_date >= DATEADD(day, -10, GETDATE() ) )

The way you specify an expression for searching depends on whether it appears as a condition or as a value to search.

To use an expression as a condition

  1. In the Grid pane, insert a new grid row.

    2.

  2. In the Column column of the new grid row, type the expression you want to use as the condition.

    3.

  3. In the Criteria column for the new row, type the value to compare against the condition.

      Grid pane with expressions in Column and Criteria columns

    4.

To use an expression as a search value

  1. If it is not already in the Grid pane, add the data column or expression you want to search.

    2.

  2. In the Criteria column for that data column or expression, enter the expression to use as a search value.

      Grid pane with expression in Criteria column

    3.


 Operators for Expressions in Queries

Operators for Expressions in Queries

You can use a variety of operators in constructing expressions for your query, including mathematical and text operators.

Mathematical Operators

The following table lists the mathematical operators you can use in constructing an expression.

Operator | Meaning
+, - | Unary positive, negative
+ | Addition
- | Subtraction
* | Multiplication
/ | Division

Note For details about additional operators available in SQL Server, see Query Designer Considerations for SQL Server Databases.

If you use more than one mathematical operator in an expression, the Query Designer processes the expression according to the following operator precedence. To override the default precedence, use parentheses around the portion of the expression that is to be evaluated first. If more than one operator of the same level is included, the operators are evaluated left to right.

  1. Unary + and -

  2. * and /

  3. + and -

Text Operator

You can perform one operation on text: concatenation or the linking together of strings. To concatenate a string, you can use the "+" operator in the Grid pane.


 Functions for Expressions in Queries

Functions for Expressions in Queries

You can call a number of functions when you are building an expression, including:

  • String (character) functions

  • Date functions

  • Mathematical functions

  • System functions

  • Other functions, such as those to convert data from one type to another

The Query Designer can help you work with functions by:

  • Correctly inserting quotation marks in function arguments

  • Validating the data types of arguments

  • Validating the data types of return values

For details about functions supported by the database, refer to the documentation for the database.

Note You can use a special set of functions, the aggregate functions such as SUM( ) and AVG( ), to create queries that summarize data. For details, see Summarizing and Grouping.

String Functions

The following functions for manipulating character strings provide a sampling of those that are available in Microsoft SQL Server.

Function Description Example
LCASE( ),
LOWER( ) 		Converts strings to lowercase
SELECT UPPER(substring(lname, 1, 1)) +
  LOWER(substring (lname, 2, 99))
FROM employee

Displays a last name after the first character is converted to uppercase and the remaining characters to lowercase.
LTRIM( ) Removes leading spaces from a string
SELECT stor_name, LTRIM(stor_address)
FROM stores

Displays an address column after extraneous spaces are removed from the front.

SUBSTRING( )
Extracts one or more characters from a string

SELECT SUBSTRING(phone,1,3)
FROM employee

Displays the first three characters (the area code) of a phone number.

UCASE( ),

UPPER( )
Converts strings to uppercase

SELECT * FROM employee
WHERE UPPER(lname) = 'SMITH'

Converts the contents of the lname column to uppercase before comparing them to a specific value (avoids mismatches if the search is case sensitive). For details about case sensitivity in SQL Server, see Query Designer Considerations.

Date Functions

The following functions (or others similar to them) are available in Microsoft SQL Server.

Function
Description
Example

DATEDIFF( )
Calculates an interval between two dates.

SELECT fname, lname, hire_date
FROM employee
WHERE DATEDIFF(year, hire_date, getdate()) > 5

Locates all employees hired more than five years before the date the query is run

DATEPART( )
Returns the specified portion of a datetime column, including the day, month, or year.

SELECT DATEPART(year, hire_date)
FROM employee

Displays only the year in which an employee was hired (not the full date).

CURDATE( ),

GETDATE( ) or DATE( )
Returns the current date in datetime format. This function is useful as input for many other date functions, such as calculating an interval forward or backward from today.

SELECT order_id
FROM orders
WHERE order_date = GETDATE()

Displays orders placed today.

Mathematical Functions

Most databases provide some mathematical functions that you can use when performing calculations. The following functions are typical of those available in many databases, but you should refer to Microsoft SQL Server documentation for details about what functions are available and what arguments they take.

Note   You can use the aggregate functions AVG( ), COUNT( ), MAX( ), MIN( ), and SUM( ) to create averages and totals in your report. For details, see Summarizing and Grouping.

Function
Description
Example

ROUND( )
Rounds a number off to the specified number of decimal places.

SELECT ROUND(qty * (price * discount), 2)
FROM sales

Displays a total price based on a discount, then rounds the results off to two decimal places.

FLOOR( )
Rounds a number down to the nearest (smallest) whole number.

UPDATE titles
SET price = FLOOR(price)

Rounds all prices in the titles table down to the nearest whole number.

CEILING( )
Rounds a number up to the nearest whole number.

INSERT INTO archivetitle

SELECT title, CEILING(price)
FROM titles

Copies the title and the price (rounded up to the nearest integer) from the titles table to the archivetitle table.

System Functions

Most databases make available special functions that you can use to return information about the current database, current user, or the server. Refer to Microsoft SQL Server documentation for details about what functions are available and what arguments they take.

Function
Description
Example

DATALENGTH( )
Returns the number of bytes used by the specified expression.

SELECT DATALENGTH(au_lname + ', '

  + au_fname)
FROM authors

Lists the number of bytes required for the combination of last and first names.

USER( ),

USER_NAME( )
Returns the current user name.

SELECT company_name, city, phone

FROM customers
WHERE salesperson = USER_NAME()

Creates a list of customers for the salesperson who runs the query.

Other Functions

In addition to the functions listed earlier, most databases provide other functions to help you create queries, such as data type conversion or other utility functions. The following functions illustrate the type of utility functions that are available in many databases.

Function
Description
Example

CONVERT( )
Converts data from one data type into another. Useful to format data or to use the contents of a data column as an argument in a function that requires a different data type.

SELECT 'Hired: ' + CONVERT(char (11),

  hire_date)
FROM employee

Displays a date with a caption in front of it; the CONVERT( ) function creates a string out of the date so that it can be concatenated with a literal string.

SOUNDEX( )
Returns the Soundex code for the specified expression, which you can use to create "sounds like" searches.

SELECT au_lname, au_fname
FROM authors
WHERE SOUNDEX(au_fname) = 'M240'

Searches for names that sound like "Michael".

STR( )
Converts numeric data into a character string so you can manipulate it with text operators.

SELECT str(job_id) + ' ' +
   str(job_lvl)
FROM employee

Displays the job_id and job_lvl columns (both numeric) in a single string.


 Predefined Variables for Expressions

Predefined Variables for Expressions

In addition to using column names, literals, operators, and functions in an expression, you can use predefined variables that have defined meanings or values. For example, you can use a predefined variable to display the user name for the current user or to search for data columns that contain no value (null).

Refer to the documentation for the database for details about what predefined variables are available.

The list below includes examples of predefined variables that are available in Microsoft® SQL Server™.

Note For more details about keywords available in SQL Server, see Query Designer Considerations for SQL Server Databases.

Predefined Variable Description Example
CURRENT_USER The user name of the current user
SELECT OrderID FROM Orders
WHERE salesperson = CURRENT_USER

Selects all orders where the salesperson column contains the name of the current user.
NULL A null value, used in the search expressions
IS NULL and
IS NOT NULL1
SELECT emp_id, lname, fname, minit
FROM employee
WHERE minit IS NULL

Finds authors who have no middle initial.

1The keyword IS is a special operator for use with NULL.


 Summarizing and Grouping in a Query

Summarizing and Grouping in a Query

In addition to creating queries that display individual data rows, you can create aggregate queries—queries that summarize information from multiple rows. For example, you can create a query that averages the contents of a price column. You can create the average for all rows in a table, or for groups of related rows — for example, all the rows that apply to a particular customer.

In this topic you can find information about summarizing and grouping information using queries.

  • Summary Queries

  • Summarizing Data

  • Grouping Rows

Summary Queries

Using summary queries, you can:

  • Create totals or averages of the data in numeric columns. For example, in an orders table, you can find the total of the order_total column to discover the sales total for a day.

  • Count the number of rows that meet specific criteria. For example, in a customers table, you can find out how many customers are in the state of California.

  • Find the minimum or maximum value in a specific column. For example, in an invoices table, you can find the highest sale made this month.

You can create summary queries on a table as a whole, or you can summarize subsets of a table by subdividing the table into groups.

Summarizing Data

To summarize all the data in a table, you create an aggregate query that involves a function such as SUM( ) or AVG( ). When you run the query, the result set contains a single row with the summary information. For example, you can calculate the total price of all books in the titles table by creating a query that sums the contents of the price column. The resulting query output might look like this:

Result of a query using the SUM function

The corresponding SQL statement might look like this:

SELECT SUM(price) total_price
FROM titles

You can use the following aggregate functions:

Aggregate function | Description
AVG(expr) | Average of the values in a column. The column can contain only numeric data.
COUNT(expr), COUNT(*) | A count of the values in a column (if you specify a column name as expr) or of all rows in a table or group (if you specify *). COUNT(expr) ignores null values, but COUNT(*) includes them in the count.
MAX(expr) | Highest value in a column (last value alphabetically for text data types). Ignores null values.
MIN(expr) | Lowest value in a column (first value alphabetically for text data types). Ignores null values.
SUM(expr) | Total of values in a column. The column can contain only numeric data.

When you use an aggregate function, by default the summary information includes all specified rows. In some instances, a result set includes non-unique rows. You can filter out non-unique rows by using the DISTINCT option of an aggregate function.

You can combine aggregate functions with other expressions to calculate other summary values. For details, see Summarizing Values Using Custom Expressions.

Grouping Rows

To create summary values for groups of rows, you create a query containing a GROUP BY clause. All the rows that contain the same group value are summarized into one row of the result set. The result set contains as many rows as there are unique values in the column you choose to group. If you group by multiple columns, the result set contains unique values for each combination of grouping columns you specify.

For example, you can query a titles table to find out the average price of a book for each publisher. To do so, you group the pub_id column so that all the rows for a specific publisher are summarized. The result set might look like this:

Result of a grouped summary query

The corresponding SQL statement might look like this:

SELECT pub_id, AVG(price) AveragePrice
FROM titles
GROUP BY pub_id


 Summary and Grouping Behavior in the Query Designer

Summary and Grouping Behavior in the Query Designer

When you create aggregate queries, certain logical principles apply. For example, you cannot display the contents of individual rows in a summary query. The Query Designer helps you comply with these principles in the way the Diagram and Grid panes behave.

By understanding the principles of aggregate queries and the Query Designer’s behavior, you can create logically correct aggregate queries. The overriding principle is that aggregate queries can result only in summary information. Thus, most of the principles that follow describe the ways that you can reference individual data columns within an aggregate query.

  • Referencing Columns for Output and Sorting

  • Referencing Columns in Search Conditions

  • Working with Columns in Aggregate Queries

Referencing Columns for Output and Sorting

The following principles describe how you can reference columns in an aggregate query for output and for sorting (which is not supported in the Query Designer for views):

  • If you include an aggregate function anywhere in a query, the query is considered an aggregate query. (This principle does not necessarily apply to subqueries, which can include non-aggregate information.)

  • You cannot display the contents of individual rows in an aggregate query; you can display only summary data. As a consequence, all columns marked for output must also be assigned to either an aggregate function or to the GROUP BY clause.

  • Columns used in aggregate functions cannot appear in the GROUP BY clause.

Referencing Columns in Search Conditions

The following principles describe how you can reference columns in an aggregate query in search conditions. In general, you can use a column in a search condition to filter the rows that should be summarized (a WHERE clause) or to determine which grouped results appear in the final output (a HAVING clause).

  • Individual data columns can appear in either the WHERE or HAVING clause, depending on how they are used elsewhere in the query.

  • WHERE clauses are used to select a subset of rows for summarizing and grouping and are thus applied before any grouping is done. Therefore, you can use a data column in a WHERE clause even if it is not part of the GROUP BY clause or contained in an aggregate function. For example, the following statement selects all titles that cost more than $10.00 and averages the price:
    SELECT AVG(price)
FROM titles
WHERE price > 10
  • If you create a search condition that involves a column also used in a GROUP BY clause or aggregate function, the search condition can appear as either a WHERE clause or a HAVING clause — you can decide which when you create the condition. For example, the following statement creates an average price for the titles for each publisher, then displays the average for the publishers in which the average price is greater than $10.00:
    SELECT pub_id, AVG(price)
FROM titles
GROUP BY pub_id
HAVING (AVG(price) > 10)
  • If you use an aggregate function in a search condition, the condition involves a summary and must therefore be part of the HAVING clause.

Working with Columns in Aggregate Queries

When you create aggregate queries using the Diagram and Grid panes, the Query Designer makes certain assumptions so that your query adheres to the principles outlined earlier. For example, if you are creating an aggregate query and mark a data column for output, the Query Designer automatically makes the column part of the GROUP BY clause so that you do not inadvertently attempt to display the contents of an individual row in a summary.

Even though the Query Designer works to help prevent logical errors, it is possible to create aggregate queries that will not execute. Therefore, be sure that you understand the principles listed earlier in order to avoid errors when you create queries.

The Query Designer uses the following guidelines for working with columns:

  • When you choose the Group By option or add an aggregate function to a query, all columns marked for output or used for sorting are automatically added to the GROUP BY clause. Columns are not automatically added to the GROUP BY clause if they are already part of an aggregate function.

    If you don’t want a particular column to be part of the GROUP BY clause, you must manually change it by selecting a different option in the Group By column of the Grid pane. (However, the Query Designer will not prevent you from choosing an option that can result in a query that will not run.)

  • If you manually add a query output column to an aggregate function in either the Grid or SQL pane, the Query Designer does not automatically remove other output columns from the query. Therefore, you must remove the remaining columns from the query output or make them part of the GROUP BY clause or of an aggregate function.

When you enter a search condition into the Criteria column of the Grid pane, the Query Designer follows these rules:

  1. If the Group By column of the grid is not displayed (because you have not yet specified an aggregate query), the search condition is placed into the WHERE clause.

  2. If you are already in an aggregate query and have selected the option Where in the Group By column, the search condition is placed into the WHERE clause.

  3. If the Group By column contains any value other than Where, the search condition is placed in the HAVING clause.


 Summarizing Values for All Rows in a Table by Using a Query

Summarizing Values for All Rows in a Table by Using a Query

Using an aggregate function, you can create a summary for all the values in a table. For example, you can create a query such as the following to display the total price for all books in the titles table:

SELECT SUM(price)
FROM titles

You can create multiple summaries in the same query by using aggregate functions with more than one column. For example, you can create a query that calculates the total of the price column and the average of the discount column.

You can also summarize the same column in different ways (such as totaling, counting, and averaging) in the same query. For example, the following query averages and summarizes the price column from the titles table:

SELECT AVG(price), SUM(price)
FROM titles

If you add a search condition, you can summarize the subset of rows that meet that condition.

Note You can also count all the rows in the table or the ones that meet a specific condition. For details, see Counting Rows in a Table.

When you create a single summary value for all rows in a table, you display only the summaries themselves. For example, if you are totaling the value of the price column of the titles table, you would not also display individual titles, publisher names, and so on.

Note If you are subtotaling — that is, creating groups — you can display column values for each group. For details, see Grouping Rows in Query Results.

To summarize values for all rows

  1. Start the query by adding the table you want to summarize to the Diagram pane.

  2. From the Query menu, choose Group By. The Query Designer adds a Group By column to the grid in the Grid pane.

  3. Add the column you want to summarize to the Grid pane. Be sure that the column is marked for output.

    The Query Designer automatically assigns a column alias to the column you are summarizing to create a useful column heading in query output. For more details, see Creating Column Aliases.

  4. In the Group By grid column, select the aggregate function that you want to use to summarize the data: Sum, Avg, Min, Max, Count. If you want to summarize only unique rows in the result set, choose an aggregate function with the DISTINCT options, such as Min Distinct. Do not choose Group By, Expression, or Where, because those options do not apply when you are summarizing all rows.

    The Query Designer replaces the column name in the statement in the SQL pane with the aggregate function that you specify. For example, the SQL statement might look like this:

    SELECT SUM(price)
FROM titles
  5. If you want to create more than one summary in the query, repeat steps 3 and 4.

    When you add another column to the query output list, the Query Designer automatically fills the term Group By into the Group By column of the grid. Select the appropriate aggregate function.

  6. Add search conditions, if any, to specify the subset of rows you want to summarize.

When you execute the query, the result set displays the summaries that you specified.

Note The Query Designer maintains aggregate functions as part of the SQL statement in the SQL pane until you explicitly turn off Group By mode. Therefore, if you modify your query by changing input sources or changing its type, the resulting query might include invalid aggregate functions.


 Counting Rows in a Table by Using a Query

Counting Rows in a Table by Using a Query

You can count rows in a table to determine:

  • The total number of rows in a table, for example, a count of all the books in a titles table.

  • The number of rows in a table that meet a specific condition, for example, the number of books by one publisher in a titles table.

  • The number of values in a particular column.

When you count values in a column, nulls are not included in the count. For example, you might count the number of books in a titles table that have values in the advance column. By default, the count includes all values, not just unique values.

The procedures for all three types of counts are similar.

To count all the rows in a table

  1. Start the query by adding the table you want to summarize to the Diagram pane.

  2. From the Query menu, choose Group By. The Query Designer adds a Group By column to the grid in the Grid pane.

    Check * (All Columns) in the input source window for the table.

    The Query Designer automatically fills the term Count into the Group By column in the Grid pane and assigns a column alias to the column you are summarizing to create a useful column heading in query output. For more details, see Creating Column Aliases.

    Grid pane with query that counts all the rows in a table

To count all the rows that meet a condition

  1. Start the query by adding the table you want to summarize to the Diagram pane.

  2. From the Query menu, choose Group By. The Query Designer adds a Group By column to the grid in the Grid pane.

  3. Check * (All Columns) in the input source window for the table.

    The Query Designer automatically fills the term Count into the Group By column in the Grid pane and assigns a column alias to the column you are summarizing to create a useful column heading in query output. For more details, see Creating Column Aliases.

  4. Add the data column that you want to search, and then clear the check box in the Output column.

    The Query Designer automatically fills the term Group By into the Group By column of the grid.

  5. Change Group By in the Group By column to Where.

  6. In the Criteria column for the data column to search, enter the search condition.

    Grid pane with query that counts rows that meet a condition

To count the values in a column

  1. Start the query by adding the table you want to summarize to the Diagram pane.

  2. From the Query menu, choose Group By. The Query Designer adds a Group By column to the grid in the Grid pane.

  3. Add the column that you want to count to the Grid pane.

    The Query Designer automatically fills the term Group By into the Group By column of the grid.

  4. Change Group By in the Group By column to Count.

    Grid pane with query that counts the values in a column

    To count only unique values, choose Count Distinct.


 Grouping Rows in Query Results

Grouping Rows in Query Results

If you want to create subtotals or show other summary information for subsets of a table, you create groups using an aggregate query. Each group summarizes the data for all the rows in the table that have the same value.

For example, you might want to see the average price of a book in the titles table, but break the results down by publisher. To do so, you group the query by publisher (for example, pub_id). The resulting query output might look like this:

Result of a grouped summary query

When you group data, you can display only summary or grouped data, such as:

  • The values of the grouped columns (those that appear in the GROUP BY clause). In the example above, pub_id is the grouped column.

  • Values produced by aggregate functions such as SUM( ) and AVG( ). In the example above, the second column is produced by using the AVG( ) function with the price column.

You cannot display the contents of individual columns. For example, if you group only by publisher, you cannot also display individual titles in the query. Therefore, if you add columns to the query output, the Query Designer automatically adds them to the GROUP BY clause of the statement in the SQL pane. If you want a column to be summarized instead, you can specify an aggregate function for that column.

If you group by more than one column, each group in the query shows the summary values for all grouping columns.

For example, the following query against the titles table groups by publisher (pub_id) and also by book type (type). The query results are ordered by publisher and show summary information for each different type of book that the publisher produces:

SELECT pub_id, type, SUM(price) Total_price
FROM titles
GROUP BY pub_id, type

The resulting output might look like this:

Result of summary query grouped by more than one column

To group rows

  1. Start the query by adding the table you want to summarize to the Diagram pane.

  2. From the Query menu, choose Group By. The Query Designer adds a Group By column to the grid in the Grid pane.

  3. Add the column you want to group to the Grid pane. If you want the column to appear in the query output, be sure that the column is marked for output.

    The Query Designer adds a GROUP BY clause to the statement in the SQL pane. For example, the SQL statement might look like this:

    SELECT pub_id
FROM titles
GROUP BY pub_id
  4. Add the column you want to summarize to the Grid pane. Be sure that the column is marked for output.

  5. In the Group By grid column for the summary data column, select the aggregate function that you want to use to summarize the data.

    The Query Designer automatically assigns a column alias to the column you are summarizing to create a useful column heading in query output. For more details, see Creating Column Aliases.

    Grid pane with grouped summary query

    The corresponding statement in the SQL pane might look like this:

    SELECT   pub_id, SUM(price) AS Total price
FROM     titles
GROUP BY pub_id


 Specifying Conditions for Groups in a Query

Specifying Conditions for Groups in a Query

You can limit the groups that appear in a query by specifying a condition that applies to groups as a whole — a HAVING clause. After the data has been grouped and summarized, the conditions in the HAVING clause are applied. Only the groups that meet the conditions appear in the query.

For example, you might want to see the average price of all books for each publisher in a titles table, but only if the average price exceeds $10.00. In that case, you could specify a HAVING clause with a condition such as AVG(price) > 10.

Note In some instances, you might want to exclude individual rows from groups before applying a condition to groups as a whole. For details, see Using HAVING and WHERE Clauses in the Same Query.

You can create complex conditions for a HAVING clause using AND and OR to link conditions. For details about using AND and OR in search conditions, see Specifying Multiple Search Conditions for One Column.

To specify a condition for a group

  1. Specify the groups for your query. For details, see Grouping Rows in Query Results.

  2. If it is not already in the Grid pane, add the column on which you want to base the condition. (Most often the condition involves a column that is already a group or summary column.) You cannot use a column that is not part of an aggregate function or of the GROUP BY clause.

  3. In the Criteria column, specify the condition to apply to the group.

    Grid pane showing a summary query with a condition specified for the group

    The Query Designer automatically creates a HAVING clause in the statement in the SQL pane, such as in the following example:

    SELECT pub_id, AVG(price)
FROM titles
GROUP BY pub_id
HAVING (AVG(price) > 10)
  4. Repeat steps 2 and 3 for each additional condition you want to specify.


 Using HAVING and WHERE Clauses in the Same Query

Using HAVING and WHERE Clauses in the Same Query

In some instances, you might want to exclude individual rows from groups (using a WHERE clause) before applying a condition to groups as a whole (using a HAVING clause).

A HAVING clause is like a WHERE clause, but applies only to groups as a whole (that is, to the rows in the result set representing groups), whereas the WHERE clause applies to individual rows. A query can contain both a WHERE clause and a HAVING clause. In that case:

  • The WHERE clause is applied first to the individual rows in the input sources. Only the rows that meet the conditions in the WHERE clause are grouped.

  • The HAVING clause is then applied to the rows in the result set that are produced by grouping. Only the groups that meet the HAVING conditions appear in the query output. You can apply a HAVING clause only to columns that also appear in the GROUP BY clause or in an aggregate function.

For example, imagine that you are joining the titles and publishers tables to create a query showing the average book price for a set of publishers. You want to see the average price for only a specific set of publishers — perhaps only the publishers in the state of California. And even then, you want to see the average price only if it is over $10.00.

You can establish the first condition by including a WHERE clause, which discards any publishers that are not in California, before calculating average prices. The second condition requires a HAVING clause, because the condition is based on the results of grouping and summarizing the data. The resulting SQL statement might look like this:

SELECT titles.pub_id, AVG(titles.price)
FROM titles INNER JOIN publishers
   ON titles.pub_id = publishers.pub_id
WHERE publishers.state = 'CA'
GROUP BY titles.pub_id
HAVING AVG(price) > 10

You can create both HAVING and WHERE clauses in the Grid pane of the Query Designer. By default, if you specify a search condition for a column, the condition becomes part of the HAVING clause. However, you can change the condition to be a WHERE clause.

You can create a WHERE clause and HAVING clause involving the same column. To do so, you must add the column twice to the Grid pane, then specify one instance as part of the HAVING clause and the other instance as part of the WHERE clause.

To specify a WHERE condition in an aggregate query

  1. Specify the groups for your query. For details, see Grouping Rows in Query Results.

  2. If it is not already in the Grid pane, add the column on which you want to base the WHERE condition.

  3. Clear the check box in the Output column unless the data column is part of the GROUP BY clause or included in an aggregate function.

  4. In the Criteria column, specify the WHERE condition. The Query Designer adds the condition to the HAVING clause of the SQL statement.

    Grid pane showing a summary query with a WHERE condition

    Note The query shown in the illustrations for this procedure joins two tables, titles and publishers.

    At this point in the query, the SQL statement contains a HAVING clause:

    SELECT titles.pub_id, AVG(titles.price)
FROM titles INNER JOIN publishers
   ON titles.pub_id = publishers.pub_id
GROUP BY titles.pub_id
HAVING publishers.state = 'CA'
  5. In the Group By column, select Where from the list of group and summary options. The Query Designer removes the condition from the HAVING clause in the SQL statement and adds it to the WHERE clause.

    Grid pane showing a summary query with a WHERE condition

    The SQL statement changes to include a WHERE clause instead:

    SELECT titles.pub_id, AVG(titles.price)
FROM titles INNER JOIN publishers
   ON titles.pub_id = publishers.pub_id
WHERE publishers.state = 'CA'
GROUP BY titles.pub_id


 Summarizing Values by Using Custom Expressions in a Query

Summarizing Values by Using Custom Expressions in a Query

In addition to using aggregate functions to summarize data, you can create custom expressions to produce summary values. You can use custom expressions in place of aggregate functions anywhere in an aggregate query.

For example, in the titles table you might want to create a query that shows not just the average price, but what the average price would be if it were discounted.

You cannot include an expression that is based on calculations involving only individual rows in the table; the expression must be based on an aggregate value, because only the summary values are available at the time the expression is calculated.

To specify a custom expression for a summary value

  1. Specify the groups for your query. For details, see Grouping Rows in Query Results.

  2. Move to a blank row of the Grid Pane, and then type the expression in the Columns column.

    The Query Designer automatically assigns a column alias to the expression to create a useful column heading in query output. For more details, see Creating Column Aliases.

  3. In the Group By column for the expression, select Expression.

    Grid pane showing a summary query that uses a custom expression


 Querying Using Multiple Tables

Querying Using Multiple Tables

You can retrieve data from two or more tables in the same query by joining the tables. Joined tables have a relationship to one another based on data they have in common.

For example, in a publishers application, the publishers and the titles tables might each contain a publisher ID column. If so, you can create a query that joins the two tables and produces results that include the publisher name for each book, as shown in the following illustration:

Result of joining Titles and Publishers tables

Joining tables creates a result set consisting of a virtual table with rows that combine information from all joined tables. You can specify which columns appear in the result set by selecting particular columns from each of the joined tables. You can also include sort specifications (except in views) and search conditions, just as you do for queries involving single tables.

To join tables, you specify a join condition. You can create join conditions based on any comparison operator. The most common join condition is to match values exactly — that is, the query matches a value in a column of the first table against values in a column of the other table exactly. (This is sometimes referred to as an "equijoin.") For example, in the earlier illustration, the join condition is that the pub_id column in both tables are equivalent.

You can join any number of tables. If you join more than two tables, two tables are joined, the resulting virtual joined table is joined with the next tables, and so on, until a single virtual joined table is obtained.

Typically, you join tables that are in the same database. However, depending on what database server you are using, you might be able to join tables from different databases.

To | See
Learn the different ways in which tables can be joined | Types of Joins
Learn how the Query Designer displays join information in the Diagram pane | How the Query Designer Represents Joins
Learn what rules the Query Designer uses to determine if tables should be joined | Joining Tables Automatically
Join tables yourself | Joining Tables Manually
Specify that tables should be joined using an operator other than equal (=) | Modifying Join Operators
Specify that joined tables should include rows even when they don't match rows in the corresponding table | Creating Outer Joins
Use a join to find subsets of data within a single table | Creating Self-Joins
Remove a join between tables | Removing Joins


 Types of Joins

Types of Joins

When you join tables, the type of join that you create determines the rows that appear in the result set. You can create the following types of joins:

  • Inner join A join that displays only the rows that have a match in both joined tables. (This is the default type of join in the Query Designer.) For example, you can join the titles and publishers tables to create a result set that shows the publisher name for each title. In an inner join, titles for which you do not have publisher information are not included in the result set, nor are publishers with no titles.

    Note Columns containing NULL do not match any values when you are creating an inner join and are therefore excluded from the result set. Null values do not match other null values.

  • Outer join A join that includes rows even if they do not have related rows in the joined table. You can create three variations of an outer join to specify the unmatched rows to be included:
    • Left outer join All rows from the first-named table (the "left" table, which appears leftmost in the JOIN clause) are included. Unmatched rows in the right table do not appear. For example, the following SQL statement illustrates a left outer join between the titles and publishers tables to include all titles, even those you don’t have publisher information for:
      SELECT titles.title_id, titles.title,
   publishers.pub_name
FROM titles LEFT OUTER JOIN publishers ON
   titles.pub_id = publishers.pub_id
    • Right outer join All rows in the second-named table (the "right" table, which appears rightmost in the JOIN clause) are included. Unmatched rows in the left table are not included. For example, a right outer join between the titles and publishers tables will include all publishers, even those who have no titles in the titles table.

    • Full outer join All rows in all joined tables are included, whether they are matched or not. For example, a full outer join between titles and publishers shows all titles and all publishers, even those that have no match in the other table.

You can also create a self-join, which compares rows within the same table. For example, you can use a self-join to find all publishers that are in a specific city and have the same postal code. For details, see Creating Self-Joins.


 How the Query Designer Represents Joins

How the Query Designer Represents Joins

If tables are joined, the Query Designer represents the join graphically in the Diagram pane and by using SQL syntax in the SQL pane.

Diagram Pane

In the Diagram pane the Query Designer displays a join line between the data columns involved in the join. The Query Designer displays one join line for each join condition. For example, the following illustration shows a join line between two tables that are joined:

A single join line between two tables

If tables are joined using more than one join condition, the Query Designer displays multiple join lines, as in the following example:

Two join lines between two tables

If the joined data columns are not displayed (for example, the input source window is minimized or the join involves an expression), the Query Designer places the join line at the title bar of the input source window.

The shape of the icon in the middle of the join line indicates how the input sources are joined. If the join clause uses an operator other than equal (=), the operator appears in the join line icon. The following table lists the icons that appear in the join line.

Join line icon | Description
 | Inner join (created using an equal sign)
 | Inner join based on the "greater than" operator
 | Outer join in which all rows from the table represented on the left will be included, even if they do not have matches in the related table
 | Outer join in which all rows from the table represented on the right will be included, even if they do not have matches in the related table
 | Full outer join in which all rows from both tables will be included, even if they do not have matches in the related table.

The symbols on the ends of the join line indicate the type of join. The following table lists the types of joins and the icons displayed on the ends of the join line.

Icon on ends of join line | Type of join
 | One-to-one join
 | One-to-many join
 | Query Designer cannot determine the join type. This situation occurs most often when you have created a join manually.

SQL Pane

A join can be expressed in a number of ways in an SQL statement. The exact syntax depends on how you have defined the join.

Syntax option for joining tables include:

  • JOIN qualifier for the FROM clause. The keywords INNER and OUTER specify the join type. This syntax is standard for ANSI 92 SQL.

    For example, if you join the publishers and pub_info tables based on the pub_id column in each table, the resulting SQL statement might look like this:

    SELECT *
FROM publishers INNER JOIN pub_info ON
   publishers.pub_id = pub_info.pub_id

    If you create an outer join, the words LEFT OUTER or RIGHT OUTER appear in place of the word INNER.

  • WHERE clause compares columns in both tables. If the join is created in the WHERE clause, both table names appear in the FROM clause.

    For example, the following statement joins the publishers and pub_info tables.

    SELECT *
FROM publishers, pub_info
WHERE  publishers.pub_id = pub_info.pub_id

Note SQL Server databases support *= and =* syntax. For details, see Query Designer Considerations for SQL Server.


 Joining Tables Automatically

Joining Tables Automatically

When you add two or more tables to a query, the Query Designer attempts to determine if they are related. If they are, the Query Designer automatically puts join lines between the input source windows for the tables.

The Query Designer will recognize tables as joined if:

  • The database contains information that specifies that the tables are related.

  • If two columns, one in each table, have the same name and data type. The column must be a primary key in at least one of the tables. For example, if you add employee and jobs tables, if the job_id column is the primary key in the jobs table, and if each table has a column called job_id with the same data type, the Query Designer will automatically join the tables.

    Note The Query Designer will create only one join based on columns with the same name and data type. If more than one join is possible, the Query Designer stops after creating a join based on the first set of matching columns that it finds.

  • The Query Designer detects that a search condition (a WHERE clause) is actually a join condition. For example, you might add the tables employee and jobs, then create a search condition that searches for the same value in the job_id column of both tables. When you do, the Query Designer detects that the search condition results in a join, and then creates a join condition based on the search condition.

If the Query Designer has created a join that is not suitable to your query, you can modify the join or remove it. For details, see Modifying Join Operators and Removing Joins.

If the Query Designer does not automatically join the tables in your query, you can create a join yourself. For details, see Joining Tables Manually.


 Joining Tables Manually

Joining Tables Manually

When you add two (or more) tables to a query, the Query Designer attempts to join them based on common data or on information stored in the database about how tables are related. (For details, see Joining Tables Automatically.) However, if the Query Designer has not joined the tables automatically, or if you want to create additional join conditions between tables, you can join tables manually.

You can create joins based on comparisons between any two columns, not just columns that contain the same information. For example, if your database contains two tables, titles and roysched, you can compare values in the ytd_sales column of the titles table against the lorange and hirange columns in the roysched table. Creating this join would allow you to find titles for which the year-to-date sales falls between the low and high ranges for the royalty payments.

Tip Joins work fastest if the columns in the join condition have been indexed. In some cases, joining on unindexed columns can result in an extremely slow query. For information about creating indexes, see Indexes.

To manually join tables

  1. Add to the Diagram pane the tables you want to join.

  2. Drag the name of the join column in the first input source window and drop it onto the related column in the second input source window. You cannot base a join on text, ntext, or image columns.

    Note The join columns must be of the same (or compatible) data types. For example, if the join column in the first table is a date, you must relate it to a date column in the second table. On the other hand, if the first join column is an integer, the related join column must also be of an integer data type, but it can be a different size. The Query Designer will not check the data types of the columns you use to create a join, but when you execute the query, the database will display an error if the data types are not compatible.

  3. If necessary, change the join operator; by default, the operator is an equal sign (=). For details, see Modifying Join Operators.

The Query Designer adds an INNER JOIN clause to the SQL statement in the SQL pane. You can change the type to an outer join. For details see Creating Outer Joins.


 Modifying Join Operators

Modifying Join Operators

By default, the Query Designer joins tables using an equal sign (an equijoin), which matches values in the two join columns. If you want, you can change the operator used to compare values in the join columns.

To modify join operators

  1. In the Diagram pane, right-click the join line you want to modify, and then choose Properties from the shortcut menu.

  2. In the Join Line tab of the Property Pages dialog box, select a new operator from the list.

–or–

Change the operator in the SQL statement in the SQL pane.


 Creating Outer Joins

Creating Outer Joins

By default, the Query Designer creates an inner join between tables. If you want to include data rows in the result set that do not have a match in the joined table, you can create an outer join.

When you create an outer join, the order in which tables appear in the SQL statement is significant. The first table you add becomes the "left" table and the second table becomes the "right" table. (The actual order in which the tables appear in the Diagram pane is not significant.) When you specify a left or right outer join, you are referring to the order in which the tables were added to the query and to the order in which they appear in the SQL statement in the SQL pane.

To create an outer join

  1. Create the join, either automatically or manually. For details, see Joining Tables Automatically or Joining Tables Manually.

  2. Select the join line in the Diagram pane, and then from the right-click menu, choose Select All Rows from table, selecting the command that includes the table whose extra rows you want to include.

–or–

In the Diagram pane, right-click the join line you want to change to an outer join, and then choose Properties from the shortcut menu. Under Include rows in the Join Line tab of the Property Pages dialog box, choose the option specifying the table from which you want to include all rows.

  • Choose the first table to create a left outer join.

  • Choose the second table to create a right outer join.

  • Choose both tables to create a full outer join.

    For example, the following illustration shows the options you would choose for a left outer join:

    Join line tab with left outer join settings

When you specify an outer join, the Query Designer modifies the join line to indicate an outer join. For example, the following figure shows a join line that represents an outer join in which rows are included from the employee table:

Join line with icon for outer join

In addition, the Query Designer modifies the SQL statement in the SQL pane to reflect the change in join type, as shown in the following statement:

SELECT employee.job_id, employee.emp_id,
   employee.fname, employee.minit, jobs.job_desc
FROM employee LEFT OUTER JOIN jobs ON
    employee.job_id = jobs.job_id

Because an outer join includes unmatched rows, you can use it to find rows that violate foreign key constraints. To do so, you create an outer join and then add a search condition to find rows in which the primary key column of the rightmost table is null. For example, the following outer join finds rows in the employee table that do not have corresponding rows in the jobs table:

SELECT employee.emp_id, employee.job_id
FROM employee LEFT OUTER JOIN jobs
   ON employee.job_id = jobs.job_id
WHERE (jobs.job_id IS NULL)


 Creating Self-Joins

Creating Self-Joins

You can join a table to itself — that is, create a self-join — if you want to find rows in a table that have values in common with other rows in the same table. For example, you can use a self-join to find pairs of authors who live in the same postal code.

As with any join, a self-join requires at least two tables. The difference is that, instead of adding a second table to the query, you add a second instance of the same table. That way, you can compare a column in the first instance of the table to the same column in the second instance, which allows you to compare the values in a column to each other. Each instance of the table must be unique, so the Query Designer assigns an alias to the second instance of the table.

For example, if you are creating a self-join to find all authors with the same postal code, you compare the zip column in the first instance of the table against the zip column in the second instance. The resulting join condition might look like the following:

FROM authors INNER JOIN authors authors1 ON
   authors.zip = authors1.zip

Creating a self-join often requires multiple join conditions. The primary join condition is the one on which the join is based. In the example of the authors’ postal code, the primary join condition is based on finding an exact match in the zip column.

However, if you join based on only this condition, each row in the table appears in the result set at least twice. Each row matches itself, resulting in a duplicate. In addition, the join results are reversed for rows that are identical except for the order of the join values.

To eliminate these duplicates, you can include a second join condition to filter out duplicated rows. The second join condition might, for example, compare the primary key (in this example, the au_id column) with a less than (<) operator. The resulting join condition might look like this:

FROM authors INNER JOIN authors authors1 ON
   authors.zip = authors1.zip AND
   authors.au_id < authors1.au_id

When you create a self-join, the Query Designer usually creates the second join condition automatically, because it is based on a primary key. You can then manually add the primary join condition.

To create a self-join

  1. Add to the Diagram pane the table you want to work with.

  2. Add the same table again, so that the Diagram pane shows the same table in two input source windows.

    The Query Designer assigns an alias to the second instance by adding a sequential number to the table name. In addition, the Query Designer creates a join line between the input source windows based on the primary key. In most cases, this join can function as the second join condition.

  3. Right-click the join line between the tables, choose Properties from the shortcut menu, and then change the comparison operator between the primary keys as required. For example, you might change the operator to less than (<).

  4. Create the primary join condition by dragging the name of the primary join column in the first input source window and dropping it on the corresponding column in the second input source window.

    Input source windows with two join lines

  5. Specify other options for the query such as output columns, search conditions, and sort order (except in views).


 Removing Joins

Removing Joins

If you don’t want tables to be joined, you can remove the join between them. For example, you might remove a join that the Query Designer has created automatically between two tables.

Note Removing a join between tables does not make a permanent change to their relationship. If join information for the tables is stored as part of a database, removing the join removes it only for the current query.

If two joined tables are part of your query and you remove all join conditions between them, the resulting query becomes the product of both tables — that is, the query displays all rows from the first table, each one joined to every row in the second table. Therefore, if you remove a join condition, be sure that you add a different join condition or another search condition or the result set can grow very large.

To remove a join

  • In the Diagram pane, select the join line for the join to remove, and then press the DELETE key. You can select and delete multiple join lines at one time.

The Query Designer removes the join line and the join condition in the statement in the SQL pane.


 Determining When Query Results Can Be Updated

Determining When Query Results Can Be Updated

In many cases, you can update the result set. However, in some cases you cannot.

In general, in order to update results, the Query Designer must have sufficient information to uniquely identify the row in the table. An example is if the query includes a primary key in the output list. In addition, you must have sufficient permission to update the database.

If your query is based on a view, you might be able to update the data. The same guidelines apply, except that they apply to the underlying tables in the view, not just to the view itself.

Note The Query Designer cannot determine in advance whether you can update a result set based on a view. Therefore, it displays all views, even though you might not be able to update them.

The following table summarizes specific instances in which you might and might not be able to update data in the result set.

Query | Can be updated?
Query based on one table with primary key in the output list | Yes (except as listed below)
Query based on a table with no unique index and without a primary key | Depends on query.
Query based on multiple tables which are not joined | No
Query based on data marked as read-only in the database | No
Query based on a view that involves one table with no constraints | Yes (except as listed below)
Query based on tables joined with a one-to-one relationship | Yes (except as listed below)
Query based on tables joined with a one-to-many relationship | Usually
Query based on three or more tables in which there is a many-to-many relationship | No
Query based on table for which update permission isn't granted | Can delete but not update
Query based on table for which delete permission isn't granted | Can update but not delete
Aggregate query | No
Query based on a subquery that contains totals or aggregate functions | No
Query that includes the DISTINCT keyword to exclude duplicate rows | No

In addition, you might not be able to update specific columns in the query results. The following list summarizes specific types of columns that you cannot update in the result set.

  • Columns based on expressions

  • Rows or columns deleted by another user

  • Rows or columns locked by another user (locked rows can usually be updated as soon as they are unlocked)

  • Timestamp or Image (OLE Object) columns


 Stored Procedures

Stored Procedures

Stored procedures can make managing your database and displaying information about that database and its users much easier. Stored procedures are a precompiled collection of SQL statements and optional control-of-flow statements stored under a name and processed as a unit. Stored procedures are stored within a database; can be executed with one call from an application; and allow user-declared variables, conditional execution, and other powerful programming features.

Stored procedures can contain program flow, logic, and queries against the database. They can accept parameters, output parameters, return single or multiple result sets, and return values.

You can use stored procedures for any purpose for which you would use SQL statements, with these advantages:

  • You can execute a series of SQL statements in a single stored procedure.

  • You can reference other stored procedures from within your stored procedure, which can simplify a series of complex statements.

  • The stored procedure is compiled on the server when it is created, so it executes faster than individual SQL statements.

The functionality of a stored procedure is dependent on the features offered by your database. For more details about what a stored procedure can accomplish for you, see your database documentation.

When you create a stored procedure in a Microsoft Access project, the stored procedure appears in the Database window. Click Stored Procedures [image] under Objects to see it in the list.

For details about working with stored procedures, see the following topics:

To | See
Create stored procedures to be executed from the database | Creating a Stored Procedure
Use parameters in stored procedures | Using Parameters in Stored Procedures
Open a stored procedure to view or edit its text | Opening a Stored Procedure
Save stored procedures | Saving a Stored Procedure
Delete stored procedures | Deleting a Stored Procedure
Copy stored procedures | Copying a Stored Procedure
Run stored procedures against your database | Running a Stored Procedure
Change the name of a stored procedure | Renaming a Stored Procedure


Creating a Stored Procedure

You can use any stored procedures that appear when you click Stored Procedures [image] under Objects in the Database window. Or you can create your own stored procedures that can be executed from the database you’re connected to.

To create a new stored procedure

  1. In the Database window, click Stored Procedures [image] under Objects, and then click New on the Database window toolbar.

    A new stored procedure is created using skeleton SQL statements.

    Stored procedure window with skeleton SQL statements

  2. If desired, replace StoredProcedure1 in the first line with the name of the procedure. For example, you might use "MyProcedure" as the name:
    Create Procedure MyProcedure

    Note Stored procedures must have unique names. If you choose a name that is already assigned to another stored procedure in your project, an error message warns you that a stored procedure with that name already exists.

  3. Write the remaining procedure text in SQL.

    Note If you're creating a stored procedure that returns rows from the database, the first statement after the Create Procedure statement must be a SELECT statement, or you must use SET NOCOUNT ON at the top of the procedure. This ensures that the result set from the first SELECT statement is displayed; otherwise, no rows will display. For more information and examples of stored procedures, see the documentation for your database server.


 Opening a Stored Procedure

Opening a Stored Procedure

You can open a stored procedure in your database to view or edit its text.

To open a stored procedure

  1. In the Database window, click Stored Procedures [image] under Objects.

  2. Double-click the name of the stored procedure you want to open.

    -or-

    Right-click the name of the stored procedure that you want to open, choose Design View from the shortcut menu.

The stored procedure is opened in a text editor that you can use to edit the SQL statements. For details about editing stored procedures, see your database documentation.


 Saving a Stored Procedure

Saving a Stored Procedure

A stored procedure must be saved before you can run it. If you attempt to run an unsaved stored procedure, a message prompts you to save it first. When you save the stored procedure, it is added to the Stored Procedures list in the Database window.

To save a stored procedure

  • From the File menu, choose Save.

Stored procedures must have unique names. If the name beside CREATE PROCEDURE in the procedure text is already assigned to another database object, a message prompts you to choose another name for the stored procedure.


 Renaming a Stored Procedure

Renaming a Stored Procedure

When you change the name of a stored procedure, that name is updated in your database and in the Stored Procedures list in the Database window as soon as you save the stored procedure.

To rename a stored procedure

  1. In the Database window, click Stored Procedures [image] under Objects.

  2. Right-click the name of the stored procedure that you want to rename.

  3. Choose Rename from the shortcut menu.

  4. Enter the new name for the stored procedure.

Stored procedures must have unique names. If you choose a name that is already assigned to another stored procedure in your project, an error message warns you that a stored procedure with that name already exists.

Note If you change the name of a stored procedure in the editor, the save command will create a new version of the stored procedure with the new name. If you change the stored procedure name, you'll need to update any references to it in other database objects, such as forms or reports.


 Copying a Stored Procedure

Copying a Stored Procedure

You can copy a stored procedure as the first step in creating a new stored procedure for your database. Because stored procedures must have names that are unique, the new stored procedure is automatically assigned a new unique name based on the original name.

To copy a stored procedure

  1. Open the stored procedure you want to copy in the text editor.

  2. Rename the stored procedure.

  3. Save the stored procedure under a new name to the database.

The new stored procedure is added to the Stored Procedures list in the Database window with the name you specified. The original stored procedure is not removed.

Note This process does not copy any privileges that may have been associated with the original stored procedure.

You can edit the SQL statements in the new stored procedure. For more information about editing stored procedures, see your database documentation.


 Running a Stored Procedure

Running a Stored Procedure

You can run a stored procedure against your database to execute the SQL statements it contains and display the results in Datasheet view.

To run a stored procedure

  1. In the Database window, click Stored Procedures [image] under Objects.

  2. Right-click the name of the stored procedure that you want to run.

  3. Choose Run from the shortcut menu. The datasheet shows the status of the stored procedure or displays the records returned from the stored procedure.

  4. If the stored procedure contains parameters, the Enter Parameter Value dialog box prompts you for their values. In the parameter box, type a value for the parameter, and then choose OK. For details about parameters, see Using Parameters in Stored Procedures.

The datasheet is updated with status information as the stored procedure is run. If any errors occurred during this process, the Server Errors dialog box displays a list of errors.


Using Parameters in Stored Procedures

Parameters enable you to use the same stored procedure to search the database many times, rather than requiring you to create one stored procedure for each value that you want to match. For example, in a SQL Server database, you can add a @HireDate parameter to a stored procedure that searches the employee table for employees whose hire date matches the date you specify. You can then run the stored procedure each time you want to specify a different hire date. Or you can use a combination of parameters to specify a range of dates. For example, you can create two parameters — @BeginningDate and @EndingDate — in the where clause of your stored procedure, and then specify a range of hire dates when you run the procedure.

When you use parameters in stored procedures, you can:

  • Return a status value to another stored procedure to indicate success or failure and the reason for the failure.

  • Return parameter values to another stored procedure.

A parameter takes the place of a constant; it cannot take the place of a table name, column name, or other database object.

Note You specify or determine the input parameters that are passed to a stored procedure used as the record source for a form or report by setting the form or report's InputParameters property. This property maps the input parameters in the stored procedure to expressions that reference those parameters in the form or report. The stored procedure, in this case, should be executed using a command string containing the {call } syntax with one ? marker for each non-default parameter in the InputParameter list.

For more details about how your database works with parameters in stored procedures, see your database documentation.

When you run a stored procedure that contains a parameter, you specify a parameter value.

To enter parameter values

  1. Run the stored procedure. For details, see Running a Stored Procedure.

    If the stored procedure contains one or more parameters, the Enter Parameter Value dialog box is displayed.

  2. For each parameter, enter the value to use, and then choose OK. Be sure that you provide a value that matches the data type of the parameter.


Deleting a Stored Procedure

When you no longer need to retrieve the information specified by a stored procedure, or the tables or columns it references have been deleted from your database, you can delete the stored procedure.

To delete a stored procedure

  1. In the Database window, click Stored Procedures [image] under Objects

  2. Right-click the stored procedure that you want to delete.

  3. Choose Delete from the shortcut menu.

  4. A message prompts you to confirm the deletion. Choose Yes.

The stored procedure is deleted from the database and Database window.


 Create a column to store hyperlinks

Create a column to store hyperlinks

  1. In your database diagram, select the table in which you want to insert the hyperlink column.

  2. If the table is not already in Column Properties view, right-click the table and choose Column Properties from the shortcut menu.

  3. In the first blank cell in the Column Name column, type a name for the column that you'll use to store hyperlinks.

  4. In the Datatype column, select char, nchar, nvarchar, or varchar.

  5. In the Length column, set an appropriate value for the hyperlink addresses that you'll store.

Note In Datasheet view of a table, view, or stored procedure, Microsoft Access displays the entire hyperlink address that you entered (display text, hyperlink address, hyperlink subaddress, and ScreenTip), but it doesn't format the address as a hyperlink. To be able to enter hyperlinks by using the Insert Hyperlink dialog box and follow a hyperlink on a form in Form view or Datasheet view, make a text box or combo box that formats the hyperlink address as a hyperlink.


 Format hyperlink addresses as hyperlinks in a text box or combo box

Format hyperlink addresses as hyperlinks in a text box or combo box

  1. Open the form in Design view.

  2. Add a text box or combo box that is bound to the column that stores hyperlinks to the form.

  3. Make sure the text box or combo box is selected, and then click Properties [image] on the toolbar to display the property sheet for the control.

  4. Set the IsHyperlink property to Yes.

Note After the IsHyperlink property is set to Yes, you can follow a hyperlink on a form in Form view or Datasheet view and use the Insert Hyperlink dialog box to add hyperlinks to the text box or combo box.


 About ADE files

About ADE files

If your Microsoft Access project contains Visual Basic for Applications (VBA) code, saving your Access project as an ADE file compiles all modules, removes all editable source code, and compacts the destination Access project. Your VBA code will continue to run, but it cannot be viewed or edited, and the size of your Access project will be reduced due to the removal of the code. Additionally, memory usage is optimized, which will improve performance.

Saving your Access project as an ADE file prevents the following actions:

  • Viewing, modifying, or creating forms, reports, or modules in Design view.

  • Adding, deleting, or changing references to object libraries or databases.

  • Changing code using the properties or methods of the Microsoft Access or VBA Object models -- an ADE file contains no source code.

  • Importing or exporting forms, reports, or modules. However, tables, data access pages, views, stored procedures, database diagrams, and macros can be imported from or exported to non-ADE Access projects. Any tables, data access pages, views, stored procedures, database diagrams, or macros in an ADE file can be imported into another Access project, but no forms, reports, or modules can be imported into another Access project.

Caution Be sure to save a copy of your original Access project. If you need to modify the design of forms, reports, or modules in an Access project saved as an ADE file, you must open the original Access project, modify it, and then save it as an ADE file again.

Caution You won't be able to open, convert, or run code in a Microsoft Access 2000 ADE file in future versions of Microsoft Access. The only way to convert a Microsoft Access 2000 ADE file to a future version will be to open the original Access project the ADE file was created from, convert it, and then save the converted Access project as an ADE file.

Important Some restrictions may prevent you from saving your Access project as an ADE file:

  • You must have password access to the VBA code if a password is defined. Learn about protecting VBA code.

  • If your Access project references another Access project, or add-in, you must save all Access projects or add-ins in the chain of references as ADE files. Learn about references and ADE files.


 About references and ADE files

About references and ADE files

If you try to save as an ADE file a Microsoft Access project (.adp) or an add-in (.mda) that references another Access project or add-in, Microsoft Access displays an error message and doesn't let you complete the operation. To save an Access project that references another Access project as an ADE file, you must save all projects in the chain of references as ADE files, starting from the first project referenced. After saving the first project as an ADE file, you must then update the reference in the next project to point to the new ADE file before saving it as an ADE file, and so on.

For example, if Project1.adp references Project2.adp, which references Project3.mda, you would proceed as follows:

  1. Save Project3.mda as Project3.mde.

  2. Open Project 2.adp and change its reference to point to the new Project3.mde.

  3. Save Project2.adp as Project2.ade.

  4. Open Project1.adp and change its reference to point to the new Project2.ade.

  5. Save Project1.adp as Project1.ade.


 Make an ADE file

Make an ADE file

  1. On the Tools menu, click Database Utilities, and then click Make ADE File.

  2. In the Database To Save As ADE dialog box, specify the Microsoft Access project you want to save as an ADE file, and then click Make ADE.

  3. In the Save ADE As dialog box, specify a name, drive, and folder for the Access project.

Caution Be sure to save a copy of your original Access project. You can't modify the design of forms, reports, or modules in a Microsoft Access project saved as an ADE file. If you need to change the design of these objects, you must do so in the original Access project and then re-save the Access project as an ADE file. You also won't be able to run or convert an Access project saved as an ADE file in future versions of Microsoft Access. You will only be able to open or convert the original Access project.


Getting Started with Transact-SQL

Transact-SQL is central to the use of Microsoft® SQL Server™. All applications that communicate with SQL Server do so by sending Transact-SQL statements to the server, regardless of an application’s user interface.

Transact-SQL is generated from many kinds of applications, including:

  • General office productivity applications.
  • Applications that use a graphical user interface to allow users to select the tables and columns from which they want to see data.
  • Applications that use general language sentences to determine what data a user wants to see.
  • Line of business applications that store their data in SQL Server databases. These can include both applications from other vendors and applications written in-house.
  • Transact-SQL scripts that are run using utilities such as osql.
  • Applications created with development systems such as Microsoft Visual C++®, Microsoft Visual Basic®, or Microsoft Visual J++™ that use database application programming interfaces (APIs) such as ADO, OLE DB, and ODBC.
  • Web pages that extract data from SQL Server databases.
  • Distributed database systems from which data from SQL Server is replicated to various databases or distributed queries are executed.
  • Data Warehouses in which data is extracted from online transaction processing (OLTP) systems and summarized for decision-support analysis.


Transact-SQL Syntax Conventions

The syntax diagrams in the Transact-SQL Reference use these conventions.

Convention | Used for
UPPERCASE | Transact-SQL keywords.
italic | User-supplied parameters of Transact-SQL syntax.
| (vertical bar) | Separating syntax items within brackets or braces. You can choose only one of the items.
[ ] (brackets) | Optional syntax items. Do not type the brackets.
{} (braces) | Required syntax items. Do not type the braces.
[,…n] | Indicating that the preceding item can be repeated n number of times. The occurrences are separated by commas.
[ …n] | Indicating that the preceding item can be repeated n number of times. The occurrences are separated by blanks.
bold | Database names, table names, column names, index names, stored procedures, utilities, data type names, and text that must be typed exactly as shown.
<label> ::= | The name for a block of syntax. This convention is used to group and label portions of lengthy syntax or a unit of syntax that can be used in more than one place within a statement. Each location in which the block of syntax can be used is indicated with the label enclosed in chevrons: <label>

Unless specified otherwise, all Transact-SQL references to the name of a database object can be a four-part name in the form:

[
server_name.[database_name].[owner_name].
| database_name.[owner_name].
 | owner_name.
]
]
object_name

  • server_name specifies a linked server name or remote server name.
  • database_name specifies the name of a Microsoft® SQL Server™ database when the object resides in a SQL Server database. It specifies an OLE DB catalog when the object is in a linked server.
  • owner_name specifies the user that owns the object if the object is in a SQL Server database. It specifies an OLE DB schema name when the object is in a linked server.
  • object_name refers to the name of the object.

When referencing a specific object, you do not always have to specify the server, database, and owner for SQL Server to identify the object. Intermediate nodes can be omitted; use periods to indicate these positions. The valid formats of object names are:

server.database.owner.object

server.database..object

server..owner.object

server...object

database.owner.object

database..object

owner.object

object

Code Example Conventions

Unless stated otherwise, the examples were tested using Query Analyzer and its default settings for these options:

  • QUOTED_IDENTIFIER
  • ANSI_NULLS
  • ANSI_WARNINGS
  • ANSI_PADDING
  • ANSI_NULL_DFLT_ON
  • CONCAT_NULL_YIELDS_NULL

Most code examples in the Transact-SQL Reference have been tested on servers running a case-sensitive sort order. The test servers were usually running the ANSI/ISO 1252 code page.

Transact-SQL Data Type Categories

Data types with similar characteristics are classified into categories. Categories that contain two or three data types generally have a category name derived from the data types in that category. For example, the money and smallmoney category contains the money data type and the smallmoney data type. Data type names always appear in bold, even when used as part of a category name.

Transact-SQL Data Type Hierarchy

The following data type hierarchy shows the SQL Server data type categories, subcategories, and data types used in the SQL Server documentation. For example, the exact numeric category contains three subcategories: integers, decimal, and money and smallmoney.

The exact numeric category also contains all of the data types in these three subcategories: int, smallint, tinyint, bit, decimal, money, and smallmoney. Any reference to exact numeric in the Transact-SQL Reference refers to these seven data types.

In this hierarchy the category names built from two or more data types use the conjunction “and.” The conjunction “or” may be used in the Transact-SQL Reference if it is more appropriate for the context in which the name is used.

The data types specified in this hierarchy also pertain to synonyms. For example, int refers to both int and its synonym integer. For more information, see Data Types.

numeric
exact numeric
integer
int
smallint
tinyint
bit
decimal
money and smallmoney
money
smallmoney
float and real, or approximate numeric
float
real
datetime and smalldatetime
datetime
smalldatetime

character and binary string
character string
char, varchar, and text
char and varchar
char
varchar
text
Unicode
nchar and nvarchar
nchar
nvarchar
ntext
binary, varbinary, and image
binary and varbinary
binary
varbinary
image

cursor

timestamp

uniqueidentifier

Additional data type categories used in the Transact-SQL Reference are described in these two hierarchies:

text, ntext, and image
text and ntext
text
ntext
image

short string
short character
char and varchar
char
varchar
nchar and nvarchar
nchar
nvarchar
binary and varbinary
binary
varbinary


New Features in Microsoft Transact-SQL

Microsoft® Transact-SQL provides new and extended functionality that allows greater control and flexibility for the Transact-SQL programmer.

The additions and enhancements are organized by feature. For items listed by component type, see these topics:

  • New Configuration and Database Options
  • New Data Types
  • New Transact-SQL Functions
  • New Transact-SQL Statements
  • New System Stored Procedures
  • New System Tables
Attaching and Detaching Databases

Microsoft SQL Server™ provides extended SQL statements and new system stored procedures for attaching and detaching databases.

ALTER DATABASE FOR ATTACH | sp_attach_single_file_db
CREATE DATABASE FOR ATTACH | sp_detach_db
sp_attach_db |

Cursor Support

SQL Server enhances cursor support.

cursor | sp_describe_cursor_columns
sp_cursor_list | sp_describe_cursor_tables
sp_describe_cursor |

Deferred Name Resolution

Deferred name resolution allows SQL Server stored procedures and triggers to reference the names of objects that do not yet exist.

Files and Filegroups

SQL Server creates a database by using a set of operating-system files. These new or extended SQL statements support the use of files and filegroups:

ALTER DATABASE | CREATE INDEX
ALTER TABLE | CREATE TABLE
BACKUP | RESTORE
CREATE DATABASE |

Distributed Queries

Microsoft SQL Server supports distributed queries, which use a four-part database object naming scheme. These new functions and new or enhanced stored procedures are used with distributed queries:

OPENQUERY | sp_foreignkeys
OPENROWSET | sp_indexes
sp_addlinkedserver | sp_linkedservers
sp_addlinkedsrvlogin | sp_primarykeys
sp_catalogs | sp_serveroption
sp_columns_ex | sp_tables_ex
sp_droplinkedsrvlogin | sysoledbusers

Full-text Querying

SQL Server provides these new functions and stored procedures for full-text querying:

CONTAINS | sp_fulltext_service
CONTAINSTABLE | sp_fulltext_table
FREETEXT | sp_help_fulltext_catalogs
FREETEXTTABLE | sp_help_fulltext_catalogs_cursor
FULLTEXTCATALOGPROPERTY | sp_help_fulltext_tables
FULLTEXTSERVICEPROPERTY | sp_help_fulltext_tables_cursor
OBJECTPROPERTY | sp_help_fulltext_columns
sp_fulltext_catalog | sp_help_fulltext_columns_cursor
sp_fulltext_column | sysfulltextcatalogs
sp_fulltext_database |

Information Schema Views

Information schema views provide table-independent access to the SQL Server metadata and allow applications to work properly even if significant changes have been made to the system tables. For more information, see Information Schema Views.

Job Processing

SQL Server job processing has changed from earlier versions of SQL Server. These stored procedures support the enhanced job processing functionality:

sp_add_alert | sp_help_targetserver
sp_add_category | sp_help_targetservergroup
sp_add_job | sp_manage_jobs_by_login
sp_add_jobschedule | sp_msx_defect
sp_add_jobserver | sp_msx_enlist
sp_add_jobstep | sp_post_msx_operation
sp_add_notification | sp_purge_jobhistory
sp_add_operator | sp_remove_job_from_targets
sp_add_targetservergroup | sp_resync_targetserver
sp_add_targetsvrgrp_member | sp_start_job
sp_apply_job_to_targets | sp_stop_job
sp_delete_category | sp_update_alert
sp_delete_job | sp_update_category
sp_delete_jobschedule | sp_update_job
sp_delete_jobserver | sp_update_jobschedule
sp_delete_jobstep | sp_update_jobstep
sp_delete_notification | sp_update_notification
sp_delete_operator | sp_update_operator
sp_delete_targetserver | sp_update_targetservergroup
sp_delete_targetservergroup | syscategories
sp_delete_targetsvrgrp_member | sysdownloadlist
sp_help_category | sysjobhistory
sp_help_downloadlist | sysjobs
sp_help_job | sysjobschedules
sp_help_jobhistory | sysjobservers
sp_help_jobschedule | sysjobsteps
sp_help_jobserver | systargetservergroupmembers
sp_help_jobstep | systargetservergroups
sp_help_notification | systargetservers
sp_help_operator | systaskids

Optimizer Hints

Optimizer hints have been added to the DELETE, INSERT, SELECT, and UPDATE statements.

Parallel Queries

SQL Server supports parallel execution of individual queries. Queries that must examine a large number of rows to produce a small result set such as joins, aggregations, or unions, can benefit from having portions of their execution plans run in parallel on multiple processors.

Property Functions

SQL Server supports these new or extended property-related functions:

COLUMNPROPERTY | INDEXPROPERTY
DATABASEPROPERTY | OBJECTPROPERTY
FILEGROUPPROPERTY | TYPEPROPERTY
FILEPROPERTY |

Replication

SQL Server replication has changed from earlier versions of SQL Server. These stored procedures and system tables support the enhanced replication functionality:

sp_add_agent_parameter | sp_helpsubscription
sp_add_agent_profile | sp_helpsubscription_properties
sp_adddistpublisher | sp_link_publication
sp_adddistributiondb | sp_mergedummyupdate
sp_addmergearticle | sp_mergesubscription_cleanup
sp_addmergefilter | sp_refreshsubscriptions
sp_addmergepublication | sp_reinitmergepullsubscription
sp_addmergepullsubscription | sp_reinitmergesubscription
sp_addmergepullsubscription_agent | sp_reinitpullsubscription
sp_addmergesubscription | sp_reinitsubscription
sp_addpublication_snapshot | sp_replicationdboption
sp_addpublisher70 | sp_replication_agent_checkup
sp_addpullsubscription | sp_replshowcmds
sp_addpullsubscription_agent | sp_removedbreplication
sp_addsubscriber_schedule | sp_revoke_publication_access
sp_addsynctriggers | sp_script_synctran_commands
sp_articlesynctranprocs | sp_scriptdelproc
sp_browsereplcmds | sp_scriptinsproc
sp_change_agent_parameter | sp_scriptmappedupdproc
sp_change_agent_profile | sp_scriptupdproc
sp_change_subscription_properties | sp_subscription_cleanup
sp_changedistpublisher | MSagent_parameters
sp_changedistributiondb | MSagent_profiles
sp_changedistributor_property | MSarticles
sp_changedistributor_password | MSdistpublishers
sp_changemergearticle | MSdistributiondbs
sp_changemergefilter | MSdistribution_agents
sp_changemergepublication | MSdistribution_history
sp_changemergepullsubscription | MSdistributor
sp_changemergesubscription | MSlogreader_agents
sp_changesubscriber_schedule | MSlogreader_history
sp_deletemergeconflictrow | MSmerge_agents
sp_drop_agent_parameter | MSmerge_contents
sp_drop_agent_profile | MSmerge_delete_conflicts
sp_dropdistpublisher | MSmerge_genhistory
sp_dropdistributiondb | MSmerge_history
sp_dropmergearticle | MSmerge_replinfo
sp_dropmergefilter | MSmerge_subscriptions
sp_dropmergepublication | MSmerge_tombstone
sp_dropmergepullsubscription | MSpublication_access
sp_dropmergesubscription | MSpublications
sp_droppullsubscription | MSpublisher_databases
sp_dumpparamcmd | MSreplication_objects
sp_enumcustomresolvers | MSreplication_subscriptions
sp_get_distributor | MSrepl_commands
sp_grant_publication_access | MSrepl_errors
sp_help_agent_default | MSrepl_originators
sp_help_agent_parameter | MSrepl_transactions
sp_help_agent_profile | MSrepl_version
sp_helpdistpublisher | MSsnapshot_agents
sp_helpdistributiondb | MSsnapshot_history
sp_helpmergearticle | MSsubscriber_info
sp_helpmergearticleconflicts | MSsubscriber_schedule
sp_helpmergeconflictrows | MSsubscriptions
sp_helpmergedeleteconflictrows | MSsubscription_properties
sp_helpmergefilter | sysarticleupdates
sp_helpmergepublication | sysmergearticles
sp_helpmergepullsubscription | sysmergepublications
sp_helpmergesubscription | sysmergeschemachange
sp_help_publication_access | sysmergesubscriptions
sp_helppullsubscription | sysmergesubsetfilters
sp_helpreplicationdboption | sysreplicationalerts

Showplan

Showplan output options have changed considerably. SET SHOWPLAN_TEXT provides showplan information in text format. SET SHOWPLAN_ALL sends showplan information to another program for further display enhancement.

Security

SQL Server provides enhanced security through these new or extended functions, statements, and stored procedures:

DENY | sp_droprole
IS_MEMBER | sp_droprolemember
IS_SRVROLEMEMBER | sp_dropsrvrolemember
REVOKE | sp_grantdbaccess
SUSER_SID | sp_grantlogin
SUSER_SNAME | sp_helpdbfixedrole
sp_addapprole | sp_helpntgroup
sp_addlinkedsrvlogin | sp_helprole
sp_addrole | sp_helprolemember
sp_addrolemember | sp_helpsrvrole
sp_addsrvrolemember | sp_helpsrvrolemember
sp_approlepassword | sp_revokedbaccess
sp_changeobjectowner | sp_revokelogin
sp_dbfixedrolepermission | sp_setapprole
sp_denylogin | sp_srvrolepermission
sp_dropapprole | sp_validatelogins
sp_droplinkedsrvlogin |

SQL Server Profiler Extended Stored Procedures

SQL Server includes SQL Server Profiler for monitoring SQL Server events. These are the SQL Server Profiler related stored procedures:

xp_trace_addnewqueue | xp_trace_getwritefilter
xp_trace_deletequeuedefinition | xp_trace_loadqueuedefinition
xp_trace_destroyqueue | xp_trace_pausequeue
xp_trace_enumqueuedefname | xp_trace_restartqueue
xp_trace_enumqueuehandles | xp_trace_savequeuedefinition
xp_trace_eventclassrequired | xp_trace_setappfilter
xp_trace_flushqueryhistory | xp_trace_setconnectionidfilter
xp_trace_generate_event | xp_trace_setcpufilter
xp_trace_getappfilter | xp_trace_setdbidfilter
xp_trace_getconnectionidfilter | xp_trace_setdurationfilter
xp_trace_getcpufilter | xp_trace_seteventclassrequired
xp_trace_getdbidfilter | xp_trace_seteventfilter
xp_trace_getdurationfilter | xp_trace_sethostfilter
xp_trace_geteventfilter | xp_trace_sethpidfilter
xp_trace_geteventnames | xp_trace_setindidfilter
xp_trace_getevents | xp_trace_setntdmfilter
xp_trace_gethostfilter | xp_trace_setntnmfilter
xp_trace_gethpidfilter | xp_trace_setobjidfilter
xp_trace_getindidfilter | xp_trace_setqueryhistory
xp_trace_getntdmfilter | xp_trace_setqueueautostart
xp_trace_getntnmfilter | xp_trace_setqueuecreateinfo
xp_trace_getobjidfilter | xp_trace_setqueuedestination
xp_trace_getqueueautostart | xp_trace_setreadfilter
xp_trace_getqueuedestination | xp_trace_setserverfilter
xp_trace_getqueueproperties | xp_trace_setseverityfilter
xp_trace_getreadfilter | xp_trace_setspidfilter
xp_trace_getserverfilter | xp_trace_setsysobjectsfilter
xp_trace_getseverityfilter | xp_trace_settextfilter
xp_trace_getspidfilter | xp_trace_setuserfilter
xp_trace_getsysobjectsfilter | xp_trace_setwritefilter
xp_trace_gettextfilter | xp_trace_startconsumer
xp_trace_getuserfilter |

Transactions

SQL Server includes changes to COMMIT WORK and ROLLBACK WORK.


New Configuration and Database Options

Microsoft® SQL Server™ includes these new server configuration options:

cost threshold for parallelism | query wait(s)
index create memory | remote proc trans
lightweight pooling | scan for startup procs
max degree of parallelism | time slice
min query memory per query | Unicode comparison style
max server memory | Unicode locale id
min server memory | extended memory size
query governor cost limit |

Microsoft SQL Server includes these new database options:

autoclose | cursor close on commit
autoshrink | merge publish
ANSI nulls | quoted identifier
ANSI warnings | recursive triggers
concat null yields null | torn page detection

sp_dbcmptlevel sets certain database behaviors to be compatible with a specified earlier version of SQL Server. For more information about compatibility levels and the effect of setting different compatibility levels, see sp_dbcmptlevel.


New Data Types

Microsoft® SQL Server™ includes these new data type-related items:

  • The maximum length of character data and binary strings in SQL Server has been expanded to 8,000 bytes. For more information, see binary and varbinary or char and varchar.
  • The cursor data type for cursor variables.
  • Unicode data types named nchar, nvarchar, and ntext. For more information, see nchar and nvarchar and ntext.
  • The uniqueidentifier data type for storing globally unique identification numbers (GUID).


New Transact-SQL Functions

  • + (Add) and - (Subtract) enable addition and subtraction of date and time.
  • @@LOCK_TIMEOUT function contains the current locking time-out setting, in milliseconds, for the current session.
  • COLUMNPROPERTY returns information about a column or procedure parameter.
  • CONTAINSTABLE allows users to issue full-text queries (similar to those using the CONTAINS predicate) that return relevance ranking for each row.
  • CURSOR_STATUS returns the status of a cursor or a cursor held in a cursor variable.
  • DATABASEPROPERTY returns information about a database.
  • DAY returns an integer representing the day date part of the specified date.
  • FILE_ID returns a file identification number for a named file.
  • FILE_NAME returns a file name for a given file identification number
  • FILEGROUP_ID returns a filegroup identification number for a named filegroup.
  • FILEGROUP_NAME returns a filegroup name for a given filegroup identification number.
  • FILEGROUPPROPERTY returns the specified filegroup property value when given a filegroup and property name.
  • FILEPROPERTY returns the specified file name property value when given a file name and property name.
  • FREETEXTTABLE allows users to issue full-text queries (similar to those using the FREETEXT predicate) that return relevance ranking for each row.
  • FULLTEXTCATALOGPROPERTY returns information on full-text catalog status.
  • FULLTEXTSERVICEPROPERTY returns information on the Full-Text Search (MSSearch) Service and sets some service level properties.
  • INDEXPROPERTY returns information about a particular index.
  • IS_MEMBER indicates whether the current user is a member of the specified Microsoft® Windows NT® group or Microsoft SQL Server™ role.
  • IS_SRVROLEMEMBER indicates whether the current user’s login is a member of the specified server role.
  • LEN allows SQL Server to map to ODBC scalar functions.
  • MONTH returns an integer representing the month date part of the specified date.
  • NCHAR returns a Unicode character for a given character code value.
  • NEWID creates a globally unique identification number (GUID).
  • OBJECTPROPERTY returns information about objects in the database.
  • OPENROWSET and OPENQUERY use OLE DB functionality to create a distributed query. For more information, see FROM.
  • PARSENAME returns the specified piece of an object name.
  • QUOTENAME returns the specified character string as a valid SQL Server quoted identifier.
  • REPLACE replaces all occurrences of the second given string expression in the first string expression with a third expression.
  • STDEV returns the standard deviation.
  • STDEVP returns the standard deviation for the population.
  • SUBSTRING now allows SUBSTRING functionality on text data.
  • SUSER_SID returns the user’s security identification number (SID) from the login name.
  • SUSER_SNAME returns the user’s login identification name from a user’s security identification number (SID).
  • SYSTEM_USER returns the Windows NT domain and username for the currently logged in user connected through Windows NT Authentication.
  • TRIGGER_NESTLEVEL returns the depth or nesting level of triggers in an INSERT, DELETE, or UPDATE statement.
  • TYPEPROPERTY returns information about a data type.
  • UNICODE returns a Unicode character code for a given Unicode character.
  • VAR returns the variance.
  • VARP returns the variance for the population.
  • YEAR returns an integer representing the year date part of the specified date.


New Transact-SQL Statements

Microsoft® SQL Server™ includes these new statements, or options to existing statements:

  • These options have been added to ALTER DATABASE: ADD FILEGROUP, MODIFY FILE, MODIFY FILEGROUP, REMOVE FILE, and REMOVE FILEGROUP.
  • ALTER DATABASE and CREATE DATABASE allow databases to be attached using the FOR ATTACH option.
  • ALTER PROCEDURE and ALTER TRIGGER statements have been added.
  • The DROP COLUMN clause in the ALTER TABLE statement provides the ability to specify a non (nonnull) default for a column. In addition, ALTER TABLE includes the ability to add a nonnull column with a default by using ALTER COLUMN. For more information, see ALTER TABLE.
  • ROWGUIDCOL allows one uniqueidentifier column per table to be a rowguid. For more information, see ALTER TABLE and CREATE TABLE.
  • SQL Server allows computed columns to be stored and retrieved. For more information, see ALTER TABLE, CREATE TABLE, and SELECT.
  • The NOT FOR REPLICATION clause has been added to both ALTER TRIGGER and CREATE TRIGGER. This clause indicates that the trigger being created should not be executed when a replication login modifies the table involved in the given trigger.
  • ALTER VIEW statement allows views to be altered without changing permissions.
  • BACKUP statement has been added to allow full or partial database backup operations, and log backups.
  • BULK INSERT copies a database table to or from a data file in a user-specified format.
  • CAST conversion function is an ANSI/ISO synonym for the CONVERT conversion function.
  • Specifying the WORK keyword is optional in the COMMIT WORK statement marking the end of a transaction.
  • CONTAINS and FREETEXT predicates added to the WHERE clause for full-text querying.
  • In earlier versions of SQL Server, a database had to be created before it could be restored. Because SQL Server version 7.0 now fully creates the destination database from a restore operation, it is recommended that you perform only the restore operation and not create the destination database to be restored. For more information, see FOR LOAD in CREATE DATABASE and RESTORE.
  • CREATE STATISTICS creates a histogram and associated statistics groups for the specified column or set of columns.
  • Bit columns created using CREATE TABLE can now allow NULLs. In addition, when a column with the IDENTITY property is defined with the NOT FOR REPLICATION clause, then:
    • A replication task can perform an INSERT with an explicit value specified for this column without having to execute SET IDENTITY_INSERT ON.
    • An INSERT statement by a replication connection does not change the current IDENTITY values.
  • Multiple triggers for any trigger action (DELETE, INSERT, or UPDATE) can exist if either the WITH APPEND option is specified, or if the compatibility level setting equals 70. In addition, SQL Server adds direct trigger recursion. For more information, see CREATE TRIGGER.
  • CREATE VIEW now allows the use of the system functions that have names that begin with two at signs (@@).
  • DBCC CHECKFILEGROUP checks the allocation and structural integrity of all tables in the filegroup.
  • DBCC SHRINKDATABASE shrinks the size of a database’s data files.
  • DBCC SHRINKFILE shrinks the size of a data file in a database.
  • Cursor variables created by using DECLARE @local_variable.
  • Optimizer hints have been added to the DELETE, INSERT, UPDATE, and SELECT statements.
  • DENY statement enhances security by creating an entry in the security system that denies a permission from a security account in the current database and prevents the security account from inheriting the permission through its group or role memberships.
  • LOOP, HASH, MERGE, ROBUST PLAN, and FASTFIRSTROW optimizer hints (a READPAST optimizer hint exists only for SELECT) for DELETE, INSERT, SELECT, and UPDATE. For more information, see FROM.
  • Specifying the WORK keyword is an option in the ROLLBACK WORK statement, which rolls back a user-specified transaction to the last savepoint inside a transaction or to the beginning of a transaction.
  • RESTORE statement has been added to allow full or partial database backups or log backups to be restored. In addition, using either LOAD DATABASE or RESTORE DATABASE automatically creates the master database, if it does not already exist.
  • REVOKE statement. In SQL Server 6.5, REVOKE either removed a grant or created a negative permission entry in sysprotects depending on the initial state of the user and group level permissions. In SQL Server 7.0, REVOKE always removes a grant or deny from sysprotects for the user, group, or role specified in the REVOKE statement. It does not create a negative entry. In SQL Server 7.0, negative entries are created using the DENY statement.
  • READUNCOMMITTED, READCOMMITTED, REPEATABLEREAD, and table hints are added. For more information, see Table Hints in SELECT.
  • TOP, PERCENT, and WITH TIES options have been added to the SELECT statement.
  • SET @local_variable assigns a value to the specified local variable. In addition, SET can be used with cursor variables.
  • When set in a batch, SET ANSI_NULLS now takes effect only from subsequent batches. If SET ANSI_NULLS is used inside a stored procedure, it does not take effect inside the stored procedure and a warning is issued.
  • SET CONCAT_NULL_YIELDS_NULL, which, when ON, yields NULL if either of the operands in a concatenation operation is NULL.
  • SET LOCK_TIMEOUT option specifies the number of seconds a statement waits for a lock to be released.
  • SET QUERY_GOVERNOR_COST_LIMIT overrides the configured value of the query_governor_cost_limit option of sp_configure.
  • SET SHOWPLAN_ALL and SET SHOWPLAN_TEXT statements display showplan output. The SET SHOWPLAN_ALL statement shows all information including the parent identification number of the node being displayed. The SET SHOWPLAN_TEXT statement displays a small subset of the information that SET SHOWPLAN_ALL displays.
  • Optimizer hints have been added to the UPDATE statement.


New System Stored Procedures

Microsoft® SQL Server™ includes these stored procedure:

  • sp_add_agent_parameter adds a new parameter and its value to an agent’s profile.
  • sp_add_agent_profile creates a new profile for a replication agent.
  • sp_add_alert creates an alert.
  • sp_addapprole adds a special type of role in the current database used for application security.
  • sp_adddistpublisher creates a remote Publisher that uses the local Distributor.
  • sp_adddistributiondb creates a new Distributor database and installs the Distributor schema.
  • sp_add_category adds the specified job, alert, or operator category to the named server.
  • sp_add_data_file_recover_suspect_db adds a data file to a file group when recovery cannot complete.
  • sp_add_log_file_recover_suspect_db adds a log file to a file group when recovery cannot complete.
  • sp_add_job adds a new job that can be executed by SQL Server Enterprise Manager.
  • sp_add_jobschedule adds a job to the schedule of activities performed by SQL Server Enterprise Manager.
  • sp_add_jobserver adds the specified server to the list of those servers available to process SQL Server jobs.
  • sp_add_jobstep adds a step (operation) to a job.
  • sp_addlinkedserver creates a linked server for use with distributed queries and OLE DB data sources.
  • sp_addlinkedsrvlogin creates a new SQL Server login mapping for a linked server.
  • sp_addmergearticle adds an article to an existing merge publication.
  • sp_addmergefilter adds a new merge filter for the purpose of creating a partition based on a join with another table.
  • sp_addmergepublication, creates a new merge publication.
  • sp_addmergepullsubscription adds a merge subscription of type pull.
  • sp_addmergepullsubscription_agent adds an agent for merge pull subscription at the Subscriber.
  • sp_addmergesubscription creates a push or pull merge subscription.
  • sp_add_notification sets up a notification for an alert.
  • sp_add_operator sets up an operator (notification recipient) for use with alerts.
  • sp_addpublication_snapshot creates a Snapshot Agent.
  • sp_addpublisher70 adds a SQL Server version 7.0 Publisher at a SQL Server 6.5 Subscriber.
  • sp_addpullsubscription adds a pull or an anonymous subscription at the current database of the Subscriber.
  • sp_addpullsubscription_agent adds a new agent to the Subscriber’s database.
  • sp_addrole creates a new Microsoft SQL Server role in the current database.
  • sp_addrolemember adds a security account as a member of an existing SQL Server database role in the current database.
  • sp_addsrvrolemember adds a login as a member of a fixed server role.
  • sp_addsubscriber_schedule adds a schedule for the Distribution Agent and Merge Agent.
  • sp_addsynctriggers creates synchronous transaction triggers at the Subscriber.
  • sp_add_targetservergroup adds the specified server group name.
  • sp_add_targetsvrgrp_member adds the specified group name. Adds the optionally specified server to the specified group.
  • sp_apply_job_to_targets removes the specified job either from those servers on which the job has already been applied or from those servers on which the job is not currently applied.
  • sp_approlepassword changes the password of an application role in the current database.
  • sp_articlesynctranprocs generates synchronous transaction procedures at the Publisher.
  • sp_attach_db attaches a database to the specified server.
  • sp_attach_single_file_db works with a database having only one data file.
  • sp_autostats immediately displays or changes the automatic statistics for one or many indexes.
  • sp_browsereplcmds returns a result set containing the replicated commands stored in the distribution database.
  • sp_catalogs returns the list of catalogs in the named linked server.
  • sp_change_agent_parameter changes a parameter of a replication agent profile stored in Msagent_parameters.
  • sp_change_agent_profile changes a parameter of a replication agent profile stored in Msagent_profiles
  • sp_change_subscription_properties updates the security information in the MSsubscription_properties table.
  • sp_changedistpublisher updates the properties of the distribution Publisher.
  • sp_changedistributiondb updates the properties of the distribution database.
  • sp_changedistributor_property updates the properties of the Distributor.
  • sp_changedistributor_password changes the password for a Distributor.
  • sp_changemergearticle changes the properties of a merge article.
  • sp_changemergefilter changes some filter properties.
  • sp_changemergepublication changes the properties of a merge publication.
  • sp_changemergepullsubscription changes the properties of the merge pull subscription.
  • sp_changemergesubscription changes a merge push or pull subscription.
  • sp_changeobjectowner changes the owner of an object in the current database.
  • sp_changesubscriber_schedule changes a Subscriber’s schedule for the Distribution Agent and Merge Agent.
  • sp_column_privileges_ex returns column privileges for the specified table on the specified linked server.
  • sp_columns_ex returns the column information for the given table.
  • sp_createstats creates statistics for all eligible columns for all user-defined tables in the specified database.
  • sp_cursor_list reports the attributes of server cursors currently open for the connection and visible to Transact-SQL statements.
  • sp_cycle_errorlog closes the current error log file and cycles the error log extension numbers.
  • sp_dbcmptlevel sets certain database behaviors to be compatible with a specified earlier version of SQL Server.
  • sp_dbfixedrolepermission displays the permissions for each fixed database role.
  • sp_delete_alert removes an alert used by SQL Server Enterprise Manager to respond to special conditions or events in SQL Server.
  • sp_delete_backuphistory deletes the entries in the backup and restore history tables for old backup sets.
  • sp_delete_category removes the specified category from the named server.
  • sp_delete_job deletes a job.
  • sp_delete_jobschedule removes a job from the scheduled list of jobs to be executed by SQL Server Enterprise Manager.
  • sp_delete_jobserver removes the specified server from processing SQL Server jobs.
  • sp_delete_jobstep removes a job step from a job used by SQL Server Enterprise Manager to perform automated activities.
  • sp_delete_notification removes a notification used by SQL Server Enterprise Manager to send an alert to an operator in the event of an error returned by SQL Server.
  • sp_delete_operator removes an operator used by SQL Server Enterprise Manager to identify the person notified when an alert occurs.
  • sp_delete_targetserver removes the specified server from the list of available job servers.
  • sp_delete_targetservergroup removes the specified server from the target server group.
  • sp_delete_targetsvrgrp_member removes the specified group name.
  • sp_deletemergeconflictrow deletes rows from the msmerge_delete_conflicts table.
  • sp_denylogin prevents a Microsoft Windows NT® user or group from connecting to SQL Server.
  • sp_describe_cursor reports the attributes of a server cursor.
  • sp_describe_cursor_columns reports the attributes of the columns in the result set of a server cursor.
  • sp_describe_cursor_tables reports the base tables referenced by a server cursor.
  • sp_detach_db detaches a database from the specified server.
  • sp_drop_agent_parameter drops one or all profiles from the MSagent_parameters table.
  • sp_drop_agent_profile drops or all parameters of one or all profiles in the MSagent_parameters table.
  • sp_dropapprole removes an application role from the current database.
  • sp_dropdistpublisher drops a Publisher that serves as its own Distributor.
  • sp_dropdistributiondb drops a Distributor database.
  • sp_droplinkedsrvlogin removes an existing SQL Server login mapping to a linked server.
  • sp_dropmergearticle removes an article from a merge publication.
  • sp_dropmergefilter drops a merge filter.
  • sp_dropmergepublication drops a merge publication and its associated Snapshot Agent.
  • sp_dropmergepullsubscription drops a merge pull subscription.
  • sp_dropmergesubscription drops a subscription to a merge publication and its associated Merge Agent.
  • sp_droppullsubscription drops a subscription at the current database of the Subscriber.
  • sp_droprole which removes a SQL Server role from the current database.
  • sp_droprolemember removes a security account from a Microsoft SQL Server role in the current database.
  • sp_dropsrvrolemember removes a SQL Server login, or a Windows NT user or group, from a fixed server role.
  • sp_dumpparamcmd returns detailed information for a parameterized command stored in the distribution database.
  • sp_enumcodepages returns a three-column list: code page, character set, and code page description.
  • sp_enumcustomresolvers returns a listing of all available custom resolvers.
  • sp_foreignkeys returns the foreign keys defined on the specified remote table.
  • sp_fulltext_catalog administers a full-text catalog.
  • sp_fulltext_column administers a full-text indexed column.
  • sp_fulltext_database initializes or disables full-text indexing.
  • sp_fulltext_service changes full-text service settings.
  • sp_fulltext_table administers a full-text indexed table.
  • sp_generatefilters creates filters on foreign key tables when a specified table is replicated.
  • sp_getmergedeletetype returns the type of merge delete.
  • sp_get_distributor determines whether a Distributor is installed on a server.
  • sp_grant_publication_access adds a login to the publication's access list.
  • sp_grantdbaccess adds a security account in the current database for a login, or Windows NT user or group, and enables it to be granted permissions to perform activities in the database.
  • sp_grantlogin allows a Windows NT user or group account to connect to SQL Server.
  • sp_help_agent_default retrieves the ID of the default configuration for the agent type passed as parameter.
  • sp_help_agent_parameter returns all the parameters of a profile from the MSagent_parameters table.
  • sp_help_agent_profile displays the profile of a specified agent.
  • sp_help_alert reports information about the alerts defined for the server.
  • sp_help_category provides information about the specified classes of jobs, alerts, or operators.
  • sp_helpdbfixedrole returns a list of the fixed database roles.
  • sp_helpdistpublisher returns properties of a Publisher that serves as its own Distributor.
  • sp_helpdistributiondb returns properties of the specified Distributor database(s).
  • sp_help_downloadlist lists all rows in the sysdownloadlist system table for the supplied job, or all rows if no job is specified.
  • sp_helpfile returns the physical names and attributes of files associated with the current database.
  • sp_helpfilegroup returns the names and attributes of filegroups associated with the current database.
  • sp_help_fulltext_catalogs gets a list of full-text catalogs.
  • sp_help_fulltext_catalogs_cursor gets a list of full-text catalogs.
  • sp_help_fulltext_tables gets a list of full-text indexed tables.
  • sp_help_fulltext_tables_cursor gets a list of full-text indexed tables.
  • sp_help_fulltext_columns gets a list of full-text indexed columns.
  • sp_help_fulltext_columns_cursor gets a list of full-text indexed columns.
  • sp_help_job returns information about jobs that are used by SQL Server Enterprise Manager to perform automated activities in SQL Server.
  • sp_help_jobhistory provides information about the jobs for servers in the multiserver administration domain.
  • sp_help_jobschedule returns information about the scheduling of jobs used by SQL Server Enterprise Manager to perform automated activities.
  • sp_help_jobserver returns information about the specified job.
  • sp_help_jobstep returns information for the steps in a job used by SQL Server Enterprise Manager to perform automated activities.
  • sp_helpmergearticle returns information about an article.
  • sp_helpmergearticleconflicts returns the articles in the publication that have conflicts.
  • sp_helpmergeconflictrows returns the rows in the specified conflict table.
  • sp_helpmergedeleteconflictrows returns the rows in the specified msmerge_delete_conflicts table.
  • sp_helpmergefilter returns information about merge filter(s).
  • sp_helpmergepublication returns information about a merge publication.
  • sp_helpmergepullsubscription returns information about the pull subscription.
  • sp_helpmergesubscription returns information about a push subscription.
  • sp_help_notification reports a list of notifications.
  • sp_helpntgroup reports information about Windows NT groups with accounts in the current database.
  • sp_help_operator reports information about the operators defined for the server.
  • sp_helppullsubscription displays information about one or more subscriptions at the Subscriber.
  • sp_helpreplicationdboption shows the databases that have the replication option enabled.
  • sp_helprole returns information about the roles in the current database.
  • sp_helprolemember returns information about the members of a role in the current database.
  • sp_helpsrvrole returns a list of the SQL Server fixed server roles.
  • sp_helpsrvrolemember returns information about the members of a SQL Server fixed server role.
  • sp_helpsubscription lists subscription information associated with a particular publication, article, Subscriber, or set of subscriptions.
  • sp_helpsubscription_properties retrieves security information from the Mssubscription_properties table.
  • sp_help_targetserver lists all target servers.
  • sp_help_targetservergroup lists all target servers in the specified group. If no group is specified, SQL Server returns information on all target server groups.
  • sp_helptrigger returns the type or types of triggers defined on the specified table for the current database.
  • sp_indexes returns index information for the specified remote table.
  • sp_indexoption sets option values for user-defined indexes.
  • sp_link_publication sets the configuration and security information used by synchronization triggers when connecting to the Publisher.
  • sp_linkedservers returns the list of linked servers defined in the local server.
  • sp_makewebtask has additional parameters.
  • sp_manage_jobs_by_login deletes or reassigns jobs belonging to the specified login.
  • sp_mergedummyupdate does a dummy update on the given row so that changes to text columns made using UPDATETEXT are sent during the next merge.
  • sp_mergesubscription_cleanup removes metadata such as triggers and entries in sysmergesubscription and sysmergeaarticles when a merge subscription is dropped at a Subscriber.
  • sp_msx_defect removes the current server from multiserver operations.
  • sp_msx_enlist adds the current server to the list of servers available for multiserver operations.
  • sp_primarykeys returns the primary key columns for the specified remote table.
  • sp_post_msx_operation inserts rows into the sysdownloadlist system table for target servers to download posted job operations.
  • sp_procoption sets procedure options.
  • sp_purge_jobhistory removes the history records for jobs that have been performed by SQL Server Enterprise Manager.
  • sp_refreshsubscriptions adds subscriptions to new articles in a pull publication for all the existing Subscribers to the publication.
  • sp_refreshview refreshes the metadata for the specified view.
  • sp_reinitmergepullsubscription marks a merge subscription for reinitialization the next time the Merge Agent runs.
  • sp_reinitmergesubscription marks a merge subscription for reinitialization the next time the Merge Agent runs.
  • sp_reinitpullsubscription marks a merge subscription for reinitialization the next time the Merge Agent runs.
  • sp_reinitsubscription resynchronizes the subscription.
  • sp_remove_job_from_targets removes the specified job from the given target servers or target server groups.
  • sp_replicationdboption sets a replication database option for the current database.
  • sp_replication_agent_checkup checks each distribution database for replication agents that are running but have not logged history within the specified heartbeat interval.
  • sp_replshowcmds returns the commands for transactions marked for replication in a readable format.
  • sp_removedbreplication removes all replication objects from a database without updating data at the Distributor.
  • sp_resync_targetserver resynchronizes the specified server in the multiserver domain.
  • sp_revoke_publication_access removes the login from a publications access list.
  • sp_revokedbaccess removes a security account from the current database.
  • sp_revokelogin removes the login entries for a Windows NT user or group created with sp_grantlogin or sp_denylogin from SQL Server.
  • sp_script_synctran_commands generates a script containing the sp_addsynctrigger calls to be applied at Subscribers for nonsynchronous Subscriptions.
  • sp_scriptdelproc enerates the CREATE PROCEDURE statement to create a custom stored procedure.
  • sp_scriptinsproc generates the CREATE PROCEDURE statement to create a custom stored procedure.
  • sp_scriptupdproc generates the CREATE PROCEDURE statement to create a custom stored procedure.
  • sp_serveroption provides these new server options:
collation compatible | rpc out
data access | system
local login mapping |

  • sp_setapprole activates the permissions associated with an application role in the current database.
  • sp_srvrolepermission returns the permissions applied to a fixed server role.
  • sp_start_job informs SQL Server Agent to begin the execution of a job.
  • sp_stop_job informs SQL Server Agent to cancel the execution of a job.
  • sp_subscription_cleanup cleans up metadata when a subscription is dropped at a Subscriber.
  • sp_table_privileges_ex returns privilege information about the specified table from the specified linked server.
  • sp_tables_ex returns table information on the matching remote tables and type of table.
  • sp_update_agent_profile updates the profile for a type of replication agent.
  • sp_update_alert updates information for an existing alert.
  • sp_update_category changes the name of a category.
  • sp_update_job changes the attributes of a job.
  • sp_update_jobschedule changes the settings for a scheduled job.
  • sp_update_jobstep changes the setting for a step in a job that is used by SQL Server Enterprise Manager to perform automated activities.
  • sp_update_notification updates the notification method of an alert notification.
  • sp_update_operator updates information about an operator.
  • sp_updatestats runs UPDATE STATISTICS against all user-defined tables in the current database.
  • sp_update_targetservergroup changes the name of the specified server group name.
  • sp_validname checks for valid SQL Server identifier names.
  • sp_validatelogins reports information about orphaned Windows NT users and groups that no longer exist in the Windows NT environment but still have entries in the SQL Server system tables.
  • xp_sqlmaint calls the sqlmaint utility with a string containing sqlmaint switches.
  • xp_trace_addnewqueue adds a new trace queue and sets trace queue configuration values.
  • xp_trace_deletequeuedefinition deletes the named trace queue from the registry.
  • xp_trace_destroyqueue destroys the given trace queue, but does not delete the queue definition.
  • xp_trace_enumqueuedefname lists all currently defined trace queue names in alphabetic order.
  • xp_trace_enumqueuehandles lists all currently active trace queue handles in numeric order.
  • xp_trace_eventclassrequired returns the class name for the event classes being captured for the given queue handle when event class information is provided.
  • xp_trace_flushqueryhistory flushes the last 100 SQL Server events.
  • xp_trace_generate_event adds a user-defined event to all queues.
  • xp_trace_getappfilter retrieves the current application filter value.
  • xp_trace_getconnectionidfilter retrieves the current connection ID filter value.
  • xp_trace_getcpufilter retrieves the current CPU filter value.
  • xp_trace_getdbidfilter retrieves the current database identification number (DBID) filter value.
  • xp_trace_getdurationfilter retrieves the current definition of the duration filter value (the event duration).
  • xp_trace_geteventfilter retrieves the current event text filter definition.
  • xp_trace_geteventnames lists the names of all event classes.
  • xp_trace_getevents removes events from the trace queue created with xp_trace_seteventclassrequired and returns the events as a result set.
  • xp_trace_gethostfilter retrieves the current host filter value is configured by executing xp_trace_sethostfilter and associated with the specified trace queue.
  • xp_trace_gethpidfilter retrieves the host process identification number (HPID) filter.
  • xp_trace_getindidfilter retrieves the current index identification number (INDID) filter.
  • xp_trace_getntdmfilter retrieves the current Windows NT domain name filter.
  • xp_trace_getntnmfilter retrieves the current Windows NT computer name filter.
  • xp_trace_getobjidfilter retrieves the current object identification number (OBJID) filter.
  • xp_trace_getqueueautostart retrieves the current trace queue’s startup configuration information.
  • xp_trace_getqueuedestination retrieves the current trace queue destination filter value.
  • xp_trace_getqueueproperties retrieves all current filters associated with the specified trace queue.
  • xp_trace_getreadfilter retrieves the current read filter.
  • xp_trace_getserverfilter retrieves the current server filter.
  • xp_trace_getseverityfilter retrieves the current severity filter.
  • xp_trace_getspidfilter retrieves the current system (internal) process identification number (SPID) filter.
  • xp_trace_getsysobjectsfilter retrieves the current system objects filter.
  • xp_trace_gettextfilter retrieves the current text filter.
  • xp_trace_getuserfilter retrieves the current user filter.
  • xp_trace_getwritefilter retrieves the current write filter.
  • xp_trace_loadqueuedefinition loads a saved trace queue definition.
  • xp_trace_pausequeue suspends new events from being added to the trace queue.
  • xp_trace_restartqueue restarts a previously paused trace queue.
  • xp_trace_savequeuedefinition specifies the trace queue definition to save.
  • xp_trace_setappfilter specifies the application filter.
  • xp_trace_setconnectionidfilter specifies the connection ID filter.
  • xp_trace_setcpufilter specifies the CPU filter.
  • xp_trace_setdbidfilter specifies the database identification number (ID) filter.
  • xp_trace_setdurationfilter specifies the duration filter.
  • xp_trace_seteventclassrequired specifies the event classes to trace or not trace for the specified trace queue.
  • xp_trace_seteventfilter specifies the event description filter (entered as a text string).
  • xp_trace_sethostfilter specifies the host name filter.
  • xp_trace_sethpidfilter specifies the host process identification number (HPID) filter.
  • xp_trace_setindidfilter specifies the index identification number (INDID) filter.
  • xp_trace_setntdmfilter specifies the existing Windows NT domain name filter.
  • xp_trace_setntnmfilter specifies the Windows NT username filter.
  • xp_trace_setobjidfilter specifies the object identification number (OBJID) filter.
  • xp_trace_setqueryhistory captures the last 100 SQL Server events.
  • xp_trace_setqueueautostart configures the specified trace queue for automatic startup on the server’s next restart.
  • xp_trace_setqueuecreateinfo specifies the trace queue properties to modify.
  • xp_trace_setqueuedestination specifies the trace queue destination filter.
  • xp_trace_setreadfilter specifies the read filter.
  • xp_trace_setserverfilter specifies the SQL Server name filter.
  • xp_trace_setseverityfilter specifies the severity filter.
  • xp_trace_setspidfilter specifies the system process identification number (SPID) filter.
  • xp_trace_setsysobjectsfilter specifies the system objects filter.
  • xp_trace_settextfilter specifies the text filter.
  • xp_trace_setuserfilter specifies the SQL Server username filter.
  • xp_trace_setwritefilter specifies the write filter.
  • xp_trace_startconsumer starts the specified consumer for processing trace queue information.


New System Tables

Microsoft® SQL Server™ includes these new system tables:

  • backupfile contains one row per data or log file that was backed up.
  • backupmediafamily describes each medium involved in the backup family backup set.
  • backupmediaset describes the backup media set.
  • backupset describes the backup set.
  • MSagent_parameters contains parameters associated with an agent profile.
  • MSagent_profiles contains one row for each defined replication agent profile.
  • MSarticles contains one row for each article being replicated by a Publisher.
  • MSdistpublishers contains one row for each remote Publisher supported by the local Distributor.
  • MSdistributiondbs contains one row for each distribution database defined on the local Distributor.
  • MSdistribution_agents contains one row for each Distribution Agent running at the local Distributor.
  • MSdistribution_history contains history rows for the Distribution Agents associated with the local Distributor.
  • MSdistributor contains the Distributor properties.
  • MSlogreader_agents contains one row for each Log Reader Agent running at the local Distributor.
  • MSlogreader_history contains history rows for the Log Reader Agents associated with the local Distributor.
  • MSmerge_agents contains one row for each Merge Agent running at the Subscriber.
  • MSmerge_contents contains one row for each row modified in the current database since it was published.
  • MSmerge_delete_conflicts contains tombstone information for rows that were deleted and subsequently had the delete undone because it conflicted with an update performed at another replica.
  • MSmerge_genhistory contains one row for each generation that a Subscriber knows about (within the retention period).
  • MSmerge_history contains history rows for previous updates to Subscriber.
  • MSmerge_replinfo contains one row for each replica made from the local server.
  • MSmerge_subscriptions contains one row for each subscription serviced by the Merge Agent at the Subscriber.
  • MSmerge_tombstone contains information on deleted rows and allows deletes to be propagated to other Subscribers.
  • MSpublication_access contains a row for each Microsoft SQL Server login that has access to the specific publication or Publisher.
  • MSpublications contains one row for each publication that is replicated by a Publisher.
  • MSpublisher_databases contains one row for each Publisher/Publisher database pair serviced by the local Distributor.
  • MSreplication_objects contains one row for each object that is associated with replication in the Subscriber database.
  • MSreplication_subscriptions contains one row or replication information for each Distribution Agent servicing the local Subscriber database.
  • MSrepl_commands contains rows of replicated commands.
  • MSrepl_errors contains rows with extended replication agent failure information.
  • MSrepl_originators contains one row for each updatable Subscriber from which the transaction originated.
  • MSrepl_transactions contains one row for each replicated transaction.
  • MSrepl_version contains one row with the current version of replication installed.
  • MSsnapshot_agents contains one row for each Snapshot Agent associated with the local Distributor.
  • MSsnapshot_history contains history rows for the Snapshot Agents associated with the local Distributor.
  • MSsubscriber_info contains one row for each Publisher/Subscriber pair that is being pushed subscriptions from the local Distributor.
  • MSsubscriber_schedule contains default merge and transactional synchronization schedules for each Publisher/Subscriber pair.
  • MSsubscriptions contains one row for each subscription serviced by the local Distributor.
  • MSsubscription_properties contains rows for the parameter information for pull Distribution Agents.
  • restorefile contains one row per file restore.
  • restorefilegroup contains one row per restored filegroup.
  • restorehistory contains one row per restore operation.
  • sysallocations contains one row for each allocation unit.
  • sysaltfiles contains one row for each file in a database.
  • sysarticleupdates contains information on the articles that are updated.
  • syscategories contains the categories used by SQL Server Enterprise Manager to organize jobs, alerts, and operators.
  • sysdownloadlist holds the queue of download instructions for all target servers.
  • sysfiles describes each database file.
  • sysfilegroups describes each database filegroup.
  • sysfulltextcatalogs lists the set of full-text catalogs.
  • sysjobhistory contains information about the execution of scheduled jobs by SQL Server Enterprise Manager.
  • sysjobschedules contains schedule information for jobs to be executed by SQL Server Enterprise Manager.
  • sysjobs stores the information for each scheduled job to be executed by SQL Server Enterprise Manager.
  • sysjobservers stores the association or relationship of a particular job with one or more target servers.
  • sysjobsteps contains the information for each step in a job to be executed by SQL Server Enterprise Manager.
  • syslockinfo contains information on all granted, converting, and waiting lock requests.
  • sysmembers contains a row for each member of a database role.
  • sysmergearticles contains one row for each merge article defined in the local database.
  • sysmergepublications contains one row for each merge publication defined in the database.
  • sysmergeschemachange contains information about the last schema change.
  • sysmergesubscriptions contains one row for each known Subscriber and is a local table at the Publisher.
  • sysmergesubsetfilters contains join filter information for partitioned articles.
  • sysperfinfo contains a SQL Server representation of the internal performance counters that can be displayed through the Windows NT Performance Monitor.
  • syspermissions contains information about permissions that have been granted and denied to users, groups, and roles in the database.
  • sysoledbusers contains one row for each user and password mapping for the specified linked server.
  • sysprocesses includes the addition of the open_tran column, which indicates how many transactions a process has.
  • sysreplicationalerts contains information about the conditions that cause a replication alert to fire.
  • systargetservergroupmembers records the target servers that are currently enlisted into this multiserver group.
  • systargetservergroups records the target server groups that are currently enlisted into this multiserver environment.
  • systargetservers records the target servers that are currently enlisted into this multiserver operation domain.
  • systaskids contains a mapping of tasks created in earlier versions of SQL Server to SQL Server Enterprise Manager jobs in the current version.


+ (Add)

Adds two numbers. This addition arithmetic operator can also add a number, in days, to a date.

Syntax

expression + expression

Arguments
expression
Is any valid Microsoft® SQL Server™ expression of any of the data types in the numeric category except the bit data type.
Result Types

Returns the data type of the argument with the higher precedence. For more information, see Data Type Precedence.

Examples
A. Use the addition operator to calculate the total units available for customers to order

This example adds the current number of product in stock and the number of units currently on order for all products in the Products table.

USE Northwind

GO

SELECT ProductName, UnitsInStock + UnitsOnOrder

FROM Products

ORDER BY ProductName ASC

GO

B. Use the addition operator to add days to date and time values

This example adds a number of days to a datetime date.

USE master

GO

SET NOCOUNT ON

DECLARE @startdate datetime, @adddays int

SET @startdate = '1/10/1900 12:00 AM'

SET @adddays = 5

SET NOCOUNT OFF

SELECT @startdate + 1.25 AS 'Start Date',

    @startdate + @adddays AS 'Add Date'

Here is the result set:

Start Date                  Add Date

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

Jan 11 1900  6:00AM         Jan 15 1900 12:00AM

(1 row(s) affected)

C. Add character and integer data types

This example adds an int data type value and a character value by converting the int value to a character data type. If an invalid character exists in the int string, SQL Server returns an error.

DECLARE @addvalue int

SET @addvalue = 15

SELECT '125127' + @addvalue

Here is the result set:

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

125142

(1 row(s) affected)

See Also
CAST and CONVERT | Functions
Data Types | SELECT
Expressions | Operators


+ (Positive)

A unary operator that returns the positive value of a numeric expression (a unary operator).

Syntax

+numeric_expression

Arguments
numeric_expression
Is any valid Microsoft® SQL Server™ expression of any of the data types in the numeric data type category except the datetime or smalldatetime data types.
Result Types

Returns the data type of numeric_expression, except that an unsigned tinyint expression is promoted to a smallint result.

Examples

This example sets a variable to a positive value.

DECLARE @MyNumber decimal(10,2)

SET @MyNumber = +123.45

See Also
Data Types | Operators
Expressions |


+ (String Concatenation)

An operator in a string expression that concatenates two or more character or binary strings, columns, or a combination of strings and column names into one expression (a string operator).

Syntax

expression + expression

Arguments
expression
Is any valid Microsoft® SQL Server™ expression of any of the data types in the character and binary data type category, except the image, ntext, or text data types. Both expressions must be of the same data type, or one expression must be able to be implicitly converted to the data type of the other expression.

Note An explicit conversion to character data must be used when concatenating binary strings and any characters between the binary strings. The following example shows when CONVERT (or CAST) must be used with binary concatenation and when CONVERT (or CAST) does not need to be used.

DECLARE @mybin1 binary(5), @mybin2 binary(5)

SET @mybin1 = 0xFF

SET @mybin2 = 0xA5

-- No CONVERT or CAST function is necessary because this example

-- concatenates two binary strings.

SELECT @mybin1 + @mybin2

-- A CONVERT or CAST function is necessary because this example

-- concatenates two binary strings plus a space.

SELECT CONVERT(varchar(5), @mybin1) + ' '
    + CONVERT(varchar(5), @mybin2)

-- Here is the same conversion using CAST

SELECT CAST(@mybin1 AS varchar(5)) + ' '
    + CAST(@mybin2 AS varchar(5))

Result Types

Returns the data type of the argument with the highest precedence. For more information, see Data Type Precedence.

Remarks

When you concatenate null values, either the concat null yields null setting of sp_dboption or SET CONCAT_NULL_YIELDS_NULL determines the behavior when one expression is NULL. With either concat null yields null or SET CONCAT_NULL_YIELDS_NULL enabled ON, ‘string’ + NULL returns NULL. If either concat null yields null or SET CONCAT_NULL_YIELDS_NULL is disabled, the result is ‘string’.

Examples
A. Use string concatenation

This example creates a single column (under the column heading Name) from multiple character columns, with the author’s last name followed by a comma, a single space, and then the author’s first name. The result set is in ascending, alphabetic order by the author’s last name, and then by the author’s first name.

USE pubs

SELECT (au_lname + ', ' + au_fname) AS Name

FROM authors

ORDER BY au_lname ASC, au_fname ASC

Here is the result set:

Name

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

Bennet, Abraham

Blotchet-Halls, Reginald

Carson, Cheryl

DeFrance, Michel

del Castillo, Innes

Dull, Ann

Green, Marjorie

Greene, Morningstar

Gringlesby, Burt

Hunter, Sheryl

Karsen, Livia

Locksley, Charlene

MacFeather, Stearns

McBadden, Heather

O'Leary, Michael

Panteley, Sylvia

Ringer, Albert

Ringer, Anne

Smith, Meander

Straight, Dean

Stringer, Dirk

White, Johnson

Yokomoto, Akiko

(23 row(s) affected)

B. Combine numeric and date data types

This example uses the CAST function to concatenate numeric and date data types.

USE pubs

SELECT 'The order date is ' + CAST(ord_date AS varchar(30))

FROM sales

WHERE ord_num = 'A2976'

ORDER BY ord_num

Here is the result set:

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

The order date is May 24 1993 12:00AM

(1 row(s) affected)

C. Use multiple string concatenation

This example concatenates multiple strings to form one long string. To display the last name and the first initial of each author living in the state of California, a comma is placed after the last name and a period after the first initial.

USE pubs

SELECT (au_lname + ',' + SPACE(1) + SUBSTRING(au_fname, 1, 1) + '.') AS Name

FROM authors

WHERE state = 'CA'

ORDER BY au_lname ASC, au_fname ASC

Here is the result set:

Name

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

Bennet, A.

Carson, C.

Dull, A.

Green, M.

Gringlesby, B.

Hunter, S.

Karsen, L.

Locksley, C.

MacFeather, S.

McBadden, H.

O'Leary, M.

Straight, D.

Stringer, D.

White, J.

Yokomoto, A.

(15 row(s) affected)

See Also
CAST and CONVERT | SELECT
Data Types | SET
Expressions | sp_dboption
Functions | Operators


- (Negative)

Is a unary operator that returns the negative value of a numeric expression (a unary operator).

Syntax

-numeric_expression

Arguments
numeric_expression
Is any valid Microsoft® SQL Server™ expression of any of the data types of the numeric data type category except the datetime or smalldatetime data types.
Result Types

Returns the data type of numeric_expression, except that an unsigned tinyint expression is promoted to a signed smallint result.

Examples
A. Set a variable to a negative value

This example sets a variable to a negative value.

DECLARE @MyNumber decimal(10,2)

@MyNumber = -123.45

B. Negate a value

This example negates a variable.

DECLARE @Num1 int

SET @Num1 = 5

SELECT -@Num1

See Also
Data Types | Operators
Expressions |


- (Subtract)

Subtracts two numbers. This substraction arithmetic operator can also subtract a number, in days, from a date.

Syntax

expression - expression

Arguments
expression
Is any valid Microsoft® SQL Server™ expression of any of the data types of the numeric data type category except the bit data type.
Result Types

Returns the data type of the argument with the higher precedence. For more information, see Data Type Precedence.

Examples
A. Use subtraction in a SELECT statement

This example returns the amount of the year-to-date revenues retained by the company for each book title.

USE pubs

GO

SELECT title,

    (

        (price * ytd_sales) * CAST( ( (100 - royalty) / 100.0 )

            AS MONEY)

        ) AS IncomeAfterRoyalty

FROM titles

WHERE royalty <> 0

ORDER BY title_id ASC

GO

Parentheses can be used to change the order of execution. Calculations inside parentheses are evaluated first. If parentheses are nested, the most deeply nested calculation has precedence. For example, the result and meaning of the preceding query can be changed if you use parentheses to force the evaluation of subtraction before multiplication, which in this case would yield a meaningless number.

B. Use date subtraction

This example subtracts a number of days from a datetime date.

USE pubs

GO

DECLARE @altstartdate datetime

SET @altstartdate = '1/10/1900 3:00 AM'

SELECT @altstartdate - 1.5 AS 'Subtract Date'

Here is the result set:

Subtract Date

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

Jan 8 1900  3:00PM

(1 row(s) affected)

See Also
Data Types | SELECT
Expressions | Operators
Functions |


* (Multiply)

Multiplies two expressions (an arithmetic multiplication operator).

Syntax

expression * expression

Arguments
expression
Is any valid Microsoft® SQL Server™ expression of any of the data types of the numeric data type category except the datetime or smalldatetime data types.
Result Types

Returns the data type of the argument with the higher precedence. For more information, see Data Type Precedence.

Examples

This example retrieves the title identification number and the price of modern cookbooks, and uses the * arithmetic operator to multiply the price by 1.15.

USE pubs

SELECT title_id, price * 1.15 AS NewPrice

FROM titles

WHERE type = 'mod_cook'

ORDER BY title_id ASC

See Also
Data Types | SELECT
Expressions | WHERE
Functions | Operators


/ (Divide)

Divides one number by another (an arithmetic division operator).

Syntax

dividend / divisor

Arguments
dividend
Is the numeric expression to divide. dividend can be any valid Microsoft® SQL Server™ expression of any of the data types of the numeric data type category except the datetime and smalldatetime data types.
divisor
Is the numeric expression to divide the dividend by. divisor can be any valid SQL Server expression of any of the data types of the numeric data type category except the datetime and smalldatetime data types.
Result Types

Returns the data type of the argument with the higher precedence. For more information about data type precedence, see Data Type Precedence.

If an integer dividend is divided by an integer divisor, the result is an integer that has any fractional part of the result truncated.

Remarks

The actual value returned by the / operator is the quotient of the first expression divided by the second expression.

Examples

This example uses the division arithmetic operator to calculate the royalty amounts due for authors who have written business books.

USE pubs

GO

SELECT ((ytd_sales * price) * royalty)/100 AS 'Royalty Amount'

FROM titles

WHERE type = 'business'

ORDER BY title_id

See Also
Data Types | SELECT
Expressions | WHERE
Functions | Operators


% (Modulo)

Provides the remainder of one number divided by another.

Syntax

dividend % divisor

Arguments
dividend
Is the numeric expression to divide. dividend must be any valid Microsoft® SQL Server™ expression of the integer data type category. (A modulo is the integer that remains after two integers are divided.)
divisor
Is the numeric expression to divide the dividend by. divisor must be any valid SQL Server expression of any of the data types of the integer data type category.
Result Types

int

Remarks

The modulo arithmetic operator can be used in the select list of the SELECT statement with any combination of column names, numeric constants, or any valid expression of the integer data type category.

Examples

This example returns the book title number and any modulo (remainder) of dividing the price (converted to an integer value) of each book into the total yearly sales (ytd_sales * price).

USE pubs

GO

SELECT title_id,

    CAST((ytd_sales * price) AS int) % CAST(price AS int) AS Modulo

FROM titles

WHERE price IS NOT NULL and type = 'trad_cook'

ORDER BY title_id

GO

See Also
Expressions | SELECT
Functions | Operators
LIKE |


% (Wildcard - Character(s) to Match)

Matches any string of zero or more characters. This wildcard character can be used as either a prefix or a suffix.

See Also
LIKE


& (Bitwise AND)

Performs a bitwise logical AND operation between two integer values.

Syntax

expression & expression

Arguments
expression
Is any valid Microsoft® SQL Server™ expression of any of the data types of the integer data type category, or of the binary or varbinary data type. expression is an integer parameter that is treated and transformed into a binary number for the bitwise operation.

Note Only one expression can be of either binary or varbinary data type in a bitwise operation.

Result Types

Returns an int if the input values are int, a smallint if the input values are smallint, or a tinyint if the input values are tinyint.

Remarks

The bitwise & operator performs a bitwise logical AND between the two expressions, taking each corresponding bit for both expressions. The bits in the result are set to 1 if and only if both bits (for the current bit being resolved) in the input expressions have a value of 1; otherwise, the bit in the result is set to 0.

The & bitwise operator can be used only on columns of the integer data type category.

If the left and right expressions have different integer data types (for example, the left expression is smallint and the right expression is int), the argument of the smaller data type is converted to the larger data type. In this example, the smallint expression is converted to an int.

Examples

This example creates a table with int data types to show the values, and puts the table into one row.

USE master

GO

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES

        WHERE TABLE_NAME = 'bitwise')

    DROP TABLE bitwise

GO

CREATE TABLE bitwise

(

 a_int_value int NOT NULL,

 b_int_value int NOT NULL

)

GO

INSERT bitwise VALUES (170, 75)

GO

This query performs the bitwise AND between the a_int_value and b_int_value columns.

USE MASTER

GO

SELECT a_int_value & b_int_value

FROM bitwise

GO

Here is the result set:

-----------

10

(1 row(s) affected)

The binary representation of 170 (a_int_value or A, below) is 0000 0000 1010 1010. The binary representation of 75 (b_int_value or B, below) is 0000 0000 0100 1011. Performing the bitwise AND operation on these two values produces the binary result 0000 0000 0000 1010, which is decimal 10.

(A & B)

0000     0000 1010 1010

0000 0000 0100 1011

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

0000 0000 0000 1010

See Also
Expressions Operators (Bitwise Operators)


| (Bitwise OR)

Performs a bitwise logical OR operation between two given integer values as translated to binary expressions within Transact-SQL statements.

Syntax

expression | expression

Arguments
expression
Is any valid Microsoft® SQL Server™ expression of any of the data types of the integer data type category, or of the binary or varbinary data type. expression is an integer that is treated and transformed into a binary number for the bitwise operation.

Note Only one expression can be of either binary or varbinary data type in a bitwise operation.

Result Types

Returns an int if the input values are int, a smallint if the input values are smallint, or a tinyint if the input values are tinyint.

Remarks

The bitwise | operator performs a bitwise logical OR between the two expressions, taking each corresponding bit for both expressions. The bits in the result are set to 1 if either or both bits (for the current bit being resolved) in the input expressions have a value of 1; if neither bit in the input expressions is 1, the bit in the result is set to 0.

The | bitwise operator requires two expressions, and it can be used on columns of only the integer data type category.

If the left and right expressions have different integer data types (for example, the left expression is smallint and the right expression is int), the argument of the smaller data type is converted to the larger data type. In this example, the smallint expression is converted to an int.

Examples

This example creates a table with int data types to show the original values and puts the table into one row.

USE master

GO

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES

        WHERE TABLE_NAME = 'bitwise')

    DROP TABLE bitwise

GO

CREATE TABLE bitwise

(

 a_int_value int NOT NULL,

b_int_value int NOT NULL

)

GO

INSERT bitwise VALUES (170, 75)

GO

This query performs the bitwise OR on the a_int_value and b_int_value columns.

USE MASTER

GO

SELECT a_int_value | b_int_value

FROM bitwise

GO

Here is the result set:

-----------

235

(1 row(s) affected)

The binary representation of 170 (a_int_value or A, below) is 0000 0000 1010 1010. The binary representation of 75 (b_int_value or B, below) is 0000 0000 0100 1011. Performing the bitwise OR operation on these two values produces the binary result 0000 0000 1110 1011, which is decimal 235.

(A | B)

0000 0000 1010 1010

0000 0000 0100 1011

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

0000 0000 1110 1011

See Also
Expressions Operators (Bitwise Operators)


^ (Bitwise Exclusive OR)

Performs a bitwise exclusive OR operation between two given integer values as translated to binary expressions within Transact-SQL statements.

Syntax

expression ^ expression

Arguments
expression
Is any valid Microsoft® SQL Server™ expression of any of the data types of the integer data type category, or of the binary or varbinary data type. expression is an integer that is treated and transformed into a binary number for the bitwise operation.

Note Only one expression can be of either binary or varbinary data type in a bitwise operation.

Result Types

Returns an int if the input values are int, a smallint if the input values are smallint, or a tinyint if the input values are tinyint.

Remarks

The bitwise ^ operator performs a bitwise logical ^ between the two expressions, taking each corresponding bit for both expressions. The bits in the result are set to 1 if either (but not both) bits (for the current bit being resolved) in the input expressions have a value of 1; if both bits are either a value of 0 or 1, the bit in the result is cleared to a value of 0.

The ^ bitwise operator can be used only on columns of the integer data type category.

If the left and right expressions have different integer data types (for example, the left expression is smallint and the right expression is int), then the argument of the smaller data type is converted to the larger data type. In this example, the smallint expression is converted to an int.

Examples

This example creates a table with int data types to show the original values, and puts the table into one row.

USE master

GO

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES

        WHERE TABLE_NAME = 'bitwise')

    DROP TABLE bitwise

GO

CREATE TABLE bitwise

(

 a_int_value int NOT NULL,

b_int_value int NOT NULL

)

GO

INSERT bitwise VALUES (170, 75)

GO

This query performs the bitwise exclusive OR on the a_int_value and b_int_value columns.

USE MASTER

GO

SELECT a_int_value ^ b_int_value

FROM bitwise

GO

Here is the result set:

-----------

225

(1 row(s) affected)

The binary representation of 170 (a_int_value or A, below) is 0000 0000 1010 1010. The binary representation of 75 (b_int_value or B, below) is 0000 0000 0100 1011. Performing the bitwise exclusive OR operation on these two values produces the binary result 0000 0000 1110 0001, which is decimal 225.

(A ^ B)

0000 0000 1010 1010

0000 0000 0100 1011

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

0000 0000 1110 0001

See Also
Expressions Operators (Bitwise Operators)


~ (Bitwise NOT)

Performs a bitwise logical NOT operation for one given integer value as translated to binary expressions within Transact-SQL statements.

Syntax

~ expression

Arguments
expression
Is any valid Microsoft® SQL Server™ expression of any of the data types of the integer data type category, or of the binary or varbinary data type. expression is an integer that is treated and transformed into a binary number for the bitwise operation.
Result Types

Returns an int if the input values are int, a smallint if the input values are smallint, a tinyint if the input values are tinyint, or a bit if the input values are bit.

Remarks

The bitwise ~ operator performs a bitwise logical NOT for the expression, taking each corresponding bit. The bits in the result are set to 1 if one bit (for the current bit being resolved) in expression has a value of 0; otherwise, the bit in the result is cleared to a value of 1.

The ~ bitwise operator can be used only on columns of the integer data type category.

Important When performing any kind of bitwise operation, the storage length of the expression used in the bitwise operation is important. It is recommended that you use the same number of bytes when storing values. For example, storing the decimal value of 5 as a tinyint, smallint, or int produces a value stored with different numbers of bytes. tinyint stores data using 1 byte, smallint stores data using 2 bytes, and int stores data using 4 bytes. Therefore, performing a bitwise operation on an int decimal value can produce different results as compared to a direct binary or hexidecimal translation, especially when the ~ (bitwise NOT) operator is used. The bitwise NOT operation may occur on a variable of a shorter length that, when converted to a longer data type variable, may not have the bits in the upper 8 bits set to the expected value. It is recommended that you convert the smaller data type variable to the larger data type, and then perform the NOT operation on the result.

Examples

This example creates a table with int data types to show the values, and puts the table into one row.

USE master

GO

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES

        WHERE TABLE_NAME = 'bitwise')

    DROP TABLE bitwise

GO

CREATE TABLE bitwise

(

 a_int_value tinyint NOT NULL,

b_int_value tinyint NOT NULL

)

GO

INSERT bitwise VALUES (170, 75)

GO

This query performs the bitwise NOT on the a_int_value and b_int_value columns.

USE MASTER

GO

SELECT ~ a_int_value, ~ b_int_value

FROM bitwise

Here is the result set:

--- ---

85  180

(1 row(s) affected)

The binary representation of 170 (a_int_value or A, below) is 0000 0000 1010 1010. Performing the bitwise NOT operation on this value produces the binary result 0000 0000 0101 0101, which is decimal 85.

 (~A)

0000 0000 1010 1010

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

0000 0000 0101 0101

See Also
Expressions Operators (Bitwise Operators)


= (Equals)

Compares two expressions (a comparison operator). When you compare nonnull expressions, the result is TRUE if both operands are equal; otherwise, the result is FALSE. If either or both operands are NULL and SET ANSI_NULLS is set to ON, the result is NULL. If SET ANSI_NULLS is set to OFF, the result is FALSE if one of the operands is NULL, and TRUE if both operands are NULL.

Syntax

expression = expression

Arguments
expression
Is any valid Microsoft® SQL Server™ expression. Both expressions must have implicitly convertible data types. The conversion depends on the rules of data type precedence. For more information, see Data Type Precedence.
Result Types

Boolean

See Also
Data Types | Operators (Comparison Operators)
Expressions |


> (Greater Than)

Compares two expressions (a comparison operator). When you compare nonnull expressions, the result is TRUE if the left operand has a higher value than the right operand; otherwise, the result is FALSE. If either or both operands are NULL and SET ANSI_NULLS is set to ON, the result is NULL. If SET ANSI_NULLS is set to OFF, the result is FALSE if one of the operands is NULL, and TRUE if both operands are NULL.

Syntax

expression > expression

Arguments
expression
Is any valid Microsoft® SQL Server™ expression. Both expressions must have implicitly convertible data types. The conversion depends on the rules of data type precedence. For more information, see Data Type Precedence.
Result Types

Boolean

See Also
Data Types | Operators (Comparison Operators)
Expressions |


< (Less Than)

Compares two expressions (a comparison operator). When you compare nonnull expressions, the result is TRUE if the left operand has a lower value than the right operand; otherwise, the result is FALSE. If either or both operands are NULL and SET ANSI_NULLS is set to ON, the result is NULL. If SET ANSI_NULLS is set to OFF, the result is FALSE if one of the operands is NULL, and TRUE if both operands are NULL.

Syntax

expression < expression

Arguments
expression
Is any valid Microsoft® SQL Server™ expression. Both expressions must have implicitly convertible data types. The conversion depends on the rules of data type precedence. For more information, see Data Type Precedence.
Result Types

Boolean

See Also
Data Types | Operators (Comparison Operators)
Expressions |


>= (Greater Than or Equal To)

Compares two expressions (a comparison operator). When you compare nonnull expressions, the result is TRUE if the left operand has a higher or equal value than the right operand; otherwise, the result is FALSE. If either or both operands are NULL and SET ANSI_NULLS is set to ON, the result is NULL. If SET ANSI_NULLS is set to OFF, the result is FALSE if one of the operands is NULL, and TRUE if both operands are NULL.

Syntax

expression >= expression

Arguments
expression
Is any valid Microsoft® SQL Server™ expression. Both expressions must have implicitly convertible data types. The conversion depends on the rules of data type precedence. For more information about data type precedence, see Data Type Precedence.
Result Types

Boolean

See Also
Data Types | Operators (Comparison Operators)
Expressions |


<= (Less Than or Equal To)

Compares two expressions (a comparison operator). When you compare nonnull expressions, the result is TRUE if the left operand has a lower or equal value than the right operand; otherwise, the result is FALSE. If either or both operands are NULL and SET ANSI_NULLS is set to ON, the result is NULL. If SET ANSI_NULLS is set to OFF, the result is FALSE if one of the operands is NULL, and TRUE if both operands are NULL.

Syntax

expression =< expression

Arguments
expression
Is any valid Microsoft® SQL Server™ expression. Both expressions must have implicitly convertible data types. The conversion depends on the rules of data type precedence. For more information, see Data Type Precedence.
Result Types

Boolean

See Also
Data Types | Operators (Comparison Operators)
Expressions |


<> (Not Equal To)

Compares two expressions (a comparison operator). When you compare nonnull expressions, the result is TRUE if the left operand is not equal to the right operand; otherwise, the result is FALSE. If either or both operands are NULL and SET ANSI_NULLS is set to ON, the result is NULL. If SET ANSI_NULLS is set to OFF, the result is FALSE if one of the operands is NULL, and TRUE if both operands are NULL.

Syntax

expression <> expression

Arguments
expression
Is any valid Microsoft® SQL Server™ expression. Both expressions must have implicitly convertible data types. The conversion depends on the rules of data type precedence. For more information, see Data Type Precedence.
Result Types

Boolean

See Also
Data Types | Operators (Comparison Operators)
Expressions |


!< (Not Less Than)

Compares two expressions (a comparison operator). When you compare nonnull expressions, the result is TRUE if the left operand does not have a lower value than the right operand; otherwise, the result is FALSE. If either or both operands are NULL and SET ANSI_NULLS is set to ON, the result is NULL. If SET ANSI_NULLS is set to OFF, the result is FALSE if one of the operands is NULL, and TRUE if both operands are NULL.

Syntax

expression !< expression

Arguments
expression
Is any valid Microsoft® SQL Server™ expression. Both expressions must have implicitly convertible data types. The conversion depends on the rules of data type precedence. For more information, see Data Type Precedence.
Result Types

Boolean

See Also
Data Types | Operators (Comparison Operators)
Expressions |


!= (Not Equal To)

Tests whether or not one expression is not equal to another expression (a comparison operator). Functions the same as the Not Equal To (<>) comparison operator.

See Also
Expressions | Operators (Comparison Operators)
<> (Not Equal To) |


!> (Not Greater Than)

Compares two expressions (a comparison operator). When you compare nonnull expressions, the result is TRUE if the left operand does not have a higher value than the right operand; otherwise, the result is FALSE. If either or both operands are NULL and SET ANSI_NULLS is set to ON, the result is NULL. If SET ANSI_NULLS is set to OFF, the result is FALSE if one of the operands is NULL, and TRUE if both operands are NULL.

Syntax

expression !> expression

Arguments
expression
Is any valid Microsoft® SQL Server™ expression. Both expressions must have implicitly convertible data types. The conversion depends on the rules of data type precedence. For more information, see Data Type Precedence.
Result Types

Boolean

See Also
Data Types | Operators (Comparison Operators)
Expressions |


--(Comment)

Indicates user-provided text. Comments can be inserted on a separate line, nested (-- only) at the end of a Transact-SQL command line, or within a Transact-SQL statement. The comment is not evaluated by the server. Two hyphens (--) is the SQL-92 standard indicator for comments.

Syntax

-- text_of_comment

Arguments
text_of_comment
Is the character string containing the text of the comment.
Remarks

Use -- for single-line or nested comments. Comments inserted with -- are delimited by the newline character.

There is no maximum length for comments.

Note Including a GO command within a comment generates an error message.

Examples

This example uses the -- commenting characters.

-- Choose the pubs database.

USE pubs

-- Choose all columns and all rows from the titles table.

SELECT *

FROM titles

ORDER BY title_id ASC -- We don't have to specify ASC because that

-- is the default.

See Also
/*…*/ (Comment) Control-of-Flow Language


/*...*/ (Comment)

/*…*/ (Comment)

Indicates user-provided text. The text between the /* and */ commenting characters is not evaluated by the server.

Syntax

/* text_of_comment */

Arguments
text_of_comment
Is the character string(s) containing the text of the comment.
Remarks

Comments can be inserted on a separate line or within a Transact-SQL statement. Multiple-line comments must be indicated by /* and */. A stylistic convention often used for multiple-line comments is to begin the first line with /*, subsequent lines with **, and end with */.

There is no maximum length for comments.

Note Including a GO command within a comment generates an error message.

Examples

This example uses comments to document and test the behavior during different phases of development for a trigger. In this example, parts of the trigger are commented out to narrow down problems and test only one of the conditions. Both styles of comments are used; SQL-92 style (--) comments are shown both alone and nested.

Note The following CREATE TRIGGER statement fails because a trigger named employee_insupd already exists in the pubs database.

CREATE TRIGGER employee_insupd
/*

Because CHECK constraints can only reference the column(s)

on which the column- or table-level constraint has

been defined, any cross-table constraints (in this case,

business rules) need to be defined as triggers.

Employee job_lvls (on which salaries are based) should be within

the range defined for their job. To get the appropriate range,

the jobs table needs to be referenced. This trigger will be

invoked for INSERT and UPDATES only.

*/
ON employee
FOR INSERT, UPDATE
AS
/* Get the range of level for this job type from the jobs table. */
DECLARE @min_lvl tinyint, -- Minimum level var. declaration
@max_lvl tinyint, -- Maximum level var. declaration
@emp_lvl tinyint, -- Employee level var. declaration
@job_id smallint -- Job ID var. declaration
SELECT @min_lvl = min_lvl, -- Set the minimum level
@max_lvl = max_lvl, -- Set the maximum level
@emp_lvl = i.job_lvl, -- Set the proposed employee level
@job_id = i.job_id -- Set the Job ID for comparison
FROM employee e, jobs j, inserted i
WHERE e.emp_id = i.emp_id AND i.job_id = j.job_id
IF (@job_id = 1) and (@emp_lvl <> 10)
BEGIN
RAISERROR ('Job id 1 expects the default level of 10.', 16, 1)
ROLLBACK TRANSACTION
END
/* Only want to test first condition. Remaining ELSE is commented out.
-- Comments within this section are unaffected by this commenting style.
ELSE
IF NOT (@emp_lvl BETWEEN @min_lvl AND @max_lvl) -- Check valid range
BEGIN
RAISERROR ('The level for job_id:%d should be between %d and %d.',
16, 1, @job_id, @min_lvl, @max_lvl)
ROLLBACK TRANSACTION
END
*/
GO

See Also
-- (Comment) Control-of-Flow Language


[ ] (Wildcard - Character(s) to Match)

Matches any single character within the specified range or set that is specified inside the square brackets.

See Also

LIKE


[^] (Wildcard - Character(s) Not to Match)

Matches any single character not within the specified range or set that is specified inside the square brackets.

See Also
LIKE


_ (Wildcard - Match One Character)

Matches any single character, and can be used as either a prefix or a suffix.

See Also
LIKE


@@CONNECTIONS

Returns the number of connections or attempted connections since Microsoft® SQL Server™ was last started.

Syntax

@@CONNECTIONS

Return Types

integer

Remarks

Connections are not the same as users. Applications, for example, can open multiple connections to SQL Server without the user being aware of these connections.

To display a report containing several SQL Server statistics, including connection attempts, run sp_monitor.

Examples

This example shows the number of login attempts made as of the current date and time.

SELECT GETDATE() AS 'Today''s Date and Time',
    @@CONNECTIONS AS 'Login Attempts'

Here is the result set:

Today's Date and Time              Login Attempts

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

1998-04-09 14:28:46.940            18

See Also
sp_monitor Configuration Functions


@@CPU_BUSY

Returns the time in milliseconds (based on the resolution of the system timer) that the CPU has spent doing work since Microsoft® SQL Server™ was last started.

Syntax

@@CPU_BUSY

Return Types

integer

Remarks

To display a report containing several SQL Server statistics, including CPU activity, run sp_monitor.

Examples

This example shows SQL Server CPU activity as of the current date and time.

SELECT @@CPU_BUSY AS 'CPU ms', GETDATE() AS 'As of'

Here is the result set:

CPU ms               As of

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

20                   1998-04-18  14:43:08.180

See Also
@@IDLE | sp_monitor
@@IO_BUSY | System Statistical Functions


@@CURSOR_ROWS

Returns the number of qualifying rows that are currently in the last cursor opened on the connection. To improve performance, Microsoft® SQL Server™ can populate large keyset and static cursors asynchronously. @@CURSOR_ROWS can be called to determine the number of the rows that qualify for a cursor have been retrieved at the time @@CURSOR_ROWS is called.

Return value | Description
-m | The cursor is being populated asynchronously. The value returned (-m) is the number of rows currently in the keyset.
-1 | The cursor is dynamic. Because dynamic cursors reflect all changes, the number of rows that qualify for the cursor is constantly changing. It can never be definitely stated that all qualified rows have been retrieved.
0 | No cursors have been opened, no rows qualified for the last opened cursor, or the last-opened cursor is closed or deallocated.
n | The cursor is fully populated. The value returned (n) is the total number of rows in the cursor.

Syntax

@@CURSOR_ROWS

Return Types

integer

Remarks

The number returned by @@CURSOR_ROWS is negative if the last cursor was opened asynchronously. Keyset-driver or static cursors are opened asynchronously if the value for sp_configure cursor threshold is greater than 0, and the number of rows in the cursor result set is greater than the cursor threshold.

Examples

This example declares a cursor and uses SELECT to display the value of @@CURSOR_ROWS. The setting has a value of 0 before the cursor is opened, and a value of -1 to indicate that the cursor’s keyset is being populated asynchronously.

SELECT @@CURSOR_ROWS

DECLARE authors_cursor CURSOR FOR

SELECT au_lname FROM authors

OPEN authors_cursor

FETCH NEXT FROM authors_cursor

SELECT @@CURSOR_ROWS

CLOSE authors_cursor

DEALLOCATE authors_cursor

-----------

0

(1 row(s) affected)

au_lname

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

White

(1 row(s) affected)

-----------

-1

(1 row(s) affected)

See Also
OPEN Cursor Functions


@@DATEFIRST

Returns the current value of the SET DATEFIRST parameter, which indicates the specified first day of each week: 1 for Monday, 2 for Wednesday, and so on through 7 for Sunday.

Syntax

@@DATEFIRST

Return Types

tinyint

Remarks

The U.S. English default is 7, Sunday.

Examples

This example sets the first day of the week to 5 (Friday), and assumes the current day to be Saturday. The SELECT statement returns the DATEFIRST value and the number of the current day of the week.

SET DATEFIRST 5

SELECT @@DATEFIRST AS '1st Day', DATEPART(dw, GETDATE()) AS 'Today'

Here is the result set. Counting from Friday, today (Saturday) is day 2.

1st Day           Today

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

5                 2

See Also
DATEPART | Configuration Functions
SET DATEFIRST |


@@DBTS

Returns the value of the current timestamp data type for the current database. This timestamp is guaranteed to be unique in the database.

Syntax

@@DBTS

Return Types

varbinary

Remarks

@@DBTS returns the current database's last used timestamp value. A new timestamp value is generated when a row with a timestamp column is inserted or updated.

Examples

This example returns the current timestamp from the pubs database.

USE pubs

SELECT @@DBTS

See Also
Data Types Configuration Functions


@@ERROR

Returns the error number for the last Transact-SQL statement executed.

Syntax

@@ERROR

Return Types

integer

Remarks

When Microsoft® SQL Server™ completes the execution of a Transact-SQL statement, @@ERROR is set to the value 0 if the statement executed successfully. If an error occurs, an error message is returned. @@ERROR returns the number of the error message until another Transact-SQL statement is executed. You can view the text associated with an @@ERROR error number in the sysmessages system table.

Because @@ERROR is cleared and reset on each statement executed, check it immediately following the statement being validated or save it to a local variable that can be checked later.

Examples
A. Use @@ERROR to detect a specific error

This example uses @@ERROR to check for a check constraint violation (error #547) in an UPDATE statement.

USE pubs

GO

UPDATE authors SET au_id = "172 32 1176"

WHERE au_id = "172-32-1176"

IF @@ERROR = 547

    print "A check constraint violation occurred"

B. Use @@ERROR to conditionally exit a procedure

The IF…ELSE statements in this example test @@ERROR after an INSERT statement in a stored procedure. The value of the @@ERROR variable determines the return code sent to the calling program, indicating the success or failure of the procedure.

USE pubs

GO

-- Create the procedure.

CREATE PROCEDURE add_author

@au_id varchar(11),@au_lname varchar(40),

@au_fname varchar(20),@phone char(12),

@address varchar(40) = NULL,@city varchar(20) = NULL,

@state char(2) = NULL,@zip char(5) = NULL,

@contract bit = NULL

AS

-- Execute the INSERT statement.

INSERT INTO authors

(au_id,  au_lname, au_fname, phone, address,

 city, state, zip, contract) values

(@au_id,@au_lname,@au_fname,@phone,@address,

 @city,@state,@zip,@contract)

-- Test the error value.

IF @@ERROR <> 0

BEGIN

   -- Return 99 to the calling program to indicate failure.

   PRINT "An error occurred loading the new author information"

   RETURN(99)

END

ELSE

BEGIN

   -- Return 0 to the calling program to indicate success.

   PRINT "The new author information has been loaded"

   RETURN(0)

END

GO

C. Use @@ERROR to check the success of several statements

This example depends on the successful operation of the INSERT and DELETE statements. Local variables are set to the value of @@ERROR after both statements and are used in a shared error-handling routine for the operation.

USE pubs

GO

DECLARE @del_error int, @ins_error int

-- Start a transaction.

BEGIN TRAN

-- Execute the DELETE statement.

DELETE authors

WHERE au_id = '409-56-7088'

-- Set a variable to the error value for

-- the DELETE statement.

SELECT @del_error = @@ERROR

-- Execute the INSERT statement.

INSERT authors

   VALUES('409-56-7008', 'Bennet', 'Abraham', '415 658-9932',

   '6223 Bateman St.', 'Berkeley', 'CA', '94705', 1)

-- Set a variable to the error value for

-- the INSERT statement.

SELECT @ins_error = @@ERROR

-- Test the error values.

IF @del_error = 0 AND @ins_error = 0

BEGIN

   -- Success. Commit the transaction.

   PRINT "The author information has been replaced"

   COMMIT TRAN

END

ELSE

BEGIN

   -- An error occurred. Indicate which operation(s) failed

   -- and roll back the transaction.

   IF @del_error <> 0

      PRINT "An error occurred during execution of the DELETE

      statement."

   IF @ins_error <> 0

      PRINT "An error occurred during execution of the INSERT

      statement."

   ROLLBACK TRAN

END

GO

D. Use @@ERROR with @@ROWCOUNT

This example uses @@ERROR with @@ROWCOUNT to validate the operation of an UPDATE statement. The value of @@ERROR is checked for any indication of an error, and @@ROWCOUNT is used to ensure that the update was successfully applied to a row in the table.

USE pubs

GO

CREATE PROCEDURE change_publisher

@title_id tid,

@new_pub_id char(4)

AS

-- Declare the variables used in error checking.

DECLARE @error_var int, @rowcount_var int

-- Execute the UPDATE statement.

UPDATE titles SET pub_id = @new_pub_id

WHERE title_id = @title_id

-- Save the @@ERROR and @@ROWCOUNT values in local

-- variables before they are cleared.

SELECT @error_var = @@ERROR, @rowcount_var = @@ROWCOUNT

-- Check for errors. If an invalid @new_pub_id was specified

-- the UPDATE statement returns a foreign-key violation error #547.

IF @error_var <> 0

BEGIN

   IF @error_var = 547

   BEGIN

      PRINT "ERROR: Invalid ID specified for new publisher"

      RETURN(1)

   END

   ELSE

   BEGIN

      PRINT "ERROR: Unhandled error occurred"

      RETURN(2)

   END

END

-- Check the rowcount. @rowcount_var is set to 0

-- if an invalid @title_id was specified.

IF @rowcount_var = 0

BEGIN

   PRINT "Warning: The title_id specified is not valid"

   RETURN(1)

END

ELSE

BEGIN

   PRINT "The book has been updated with the new publisher"

   RETURN(0)

END

GO

See Also
@@ROWCOUNT | sysmessages
SET @local_variable | System Functions


@@FETCH_STATUS

Returns the status of the last cursor FETCH statement issued against any cursor currently opened by the connection.

Return value | Description
0 | FETCH statement was successful.
-1 | FETCH statement failed or the row was beyond the result set.
-2 | Row fetched is missing.

Syntax

@@FETCH_STATUS

Return Types

integer

Remarks

Because @@FETCH_STATUS is global to all cursors on a connection, use @@FETCH_STATUS carefully. After a FETCH statement is executed, the test for @@FETCH_STATUS must occur before any other FETCH statement is executed against another cursor. The value of @@FETCH_STATUS is undefined before the any fetches have occurred on the connection.

For example, a user executes a FETCH statement from one cursor, and then calls a stored procedure that opens and processes the results from another cursor. When control is returned from the called stored procedure, @@FETCH_STATUS reflects the last FETCH executed in the stored procedure, not the FETCH statement executed before the stored procedure is called.

Examples

This example uses @@FETCH_STATUS to control cursor activities in a WHILE loop.

DECLARE Employee_Cursor CURSOR FOR

SELECT LastName, FirstName FROM Northwind.dbo.Employees

OPEN Employee_Cursor

FETCH NEXT FROM Employee_Cursor

WHILE @@FETCH_STATUS = 0

BEGIN

    FETCH NEXT FROM Employee_Cursor

END

CLOSE Employee_Cursor

DEALLOCATE Employee_Cursor

See Also
FETCH Cursor Functions


@@IDENTITY

Returns the last-inserted identity value.

Syntax

@@IDENTITY

Return Types

numeric

Remarks

After an INSERT, SELECT INTO, or bulk copy statement completes, @@IDENTITY contains the last identity value generated by the statement. If the statement did not affect any tables with identity columns, @@IDENTITY returns NULL. If multiple rows are inserted, generating multiple identity values, @@IDENTITY returns the last identity value generated. If the statement fires one or more triggers that perform inserts that generate identity values, calling @@IDENTITY immediately after the statement returns the last identity value generated by the triggers. The @@IDENTITY value does not revert to a previous setting if the INSERT or SELECT INTO statement or bulk copy fails, or if the transaction is rolled back.

Examples

This example inserts a row into a table with an identity column and uses @@IDENTITY to display the identity value used in the new row.

INSERT INTO jobs (job_desc,min_lvl,max_lvl)

VALUES ('Accountant',12,125)

SELECT @@IDENTITY AS 'Identity'

See Also
CREATE TABLE | SELECT
INSERT | System Functions


@@IDLE

Returns the time in milliseconds (based on the resolution of the system timer) that Microsoft® SQL Server™ has been idle since it was last started.

Syntax

@@IDLE

Return Types

integer

Remarks

To display a report containing several SQL Server statistics, run sp_monitor.

Examples

This example shows the number of milliseconds SQL Server was idle between start time and the current time.

SELECT @@IDLE AS 'Idle ms', GETDATE() AS 'As of'

Here is the result set:

Idle Ms              As of

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

277593               1998-04-18  16:41:07.160

See Also
@@CPU_BUSY | sp_monitor
@@IO_BUSY | System Statistical Functions


@@IO_BUSY

Returns the time in milliseconds (based on the resolution of the system timer) that Microsoft® SQL Server™ has spent doing input and output operations since it was last started.

Syntax

@@IO_BUSY

Return Types

integer

Remarks

To display a report containing several SQL Server statistics, run sp_monitor.

Examples

This example shows the number of milliseconds SQL Server has spent performing input/output operations between start time and the current time.

SELECT @@IO_BUSY AS 'IO ms', GETDATE() AS 'As of'

Here is the result set:

IO ms                As of

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

31                   1998-04-18  16:49:49.650

See Also
@@CPU_BUSY | System Statistical Functions
sp_monitor |


@@LANGID

Returns the local language ID of the language currently in use.

Syntax

@@LANGID

Return Types

smallint

Remarks

To view information about language settings (including language ID numbers), run sp_helplanguage with no parameter specified.

Examples

This example sets the language for the current session to Italiano, and then uses @@LANGID to return the ID for Italiano.

SET LANGUAGE 'Italiano'

SELECT @@LANGID AS 'Language ID'

Here is the result set:

Language ID

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

6

See Also
SET LANGUAGE | Configuration Functions
sp_helplanguage |


@@LANGUAGE

Returns the name of the language currently in use.

Syntax

@@LANGUAGE

Return Types

nvarchar

Remarks

To view information about language settings (including valid official language names), run sp_helplanguage with no parameter specified.

Examples

This example returns the language for the current session.

SELECT @@LANGUAGE AS 'Language Name'

Here is the result set:

Language Name

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

us_english

See Also
SET LANGUAGE | Configuration Functions
sp_helplanguage |


@@LOCK_TIMEOUT

Returns the current lock time-out setting, in milliseconds, for the current session.

Syntax

@@LOCK_TIMEOUT

Return Types

integer

Remarks

SET LOCK_TIMEOUT allows an application to set the maximum time that a statement waits on a blocked resource. When a statement has waited longer than the LOCK_TIMEOUT setting, the blocked statement is automatically canceled, and an error message is returned to the application.

At the beginning of a connection, @@LOCK_TIMEOUT returns a value of -1.

Examples

This example shows the result set when a LOCK_TIMEOUT value has not been set.

SELECT @@LOCK_TIMEOUT

Here is the result set:

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

-1

This example sets LOCK_TIMEOUT to 1800 milliseconds, and then calls @@LOCK_TIMEOUT.

SET LOCK_TIMEOUT 1800

SELECT @@LOCK_TIMEOUT

Here is the result set:

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

1800

See Also
SET LOCK_TIMEOUT Configuration Functions


@@MAX_CONNECTIONS

Returns the maximum number of simultaneous user connections allowed on a Microsoft® SQL Server™. The number returned is not necessarily the number that is currently configured.

Syntax

@@MAX_CONNECTIONS

Return Types

integer

Remarks

The actual number of user connections allowed also depends on the version of SQL Server you are using and the limits of your application(s) and hardware.

To reconfigure SQL Server for fewer connections, use sp_configure.

Examples

This example assumes that SQL Server has not been reconfigured for fewer user connections.

SELECT @@MAX_CONNECTIONS

Here is the result set:

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

32767

See Also
sp_configure Configuration Functions


@@MAX_PRECISION

Returns the level of precision used by decimal and numeric data types as currently set in the server.

Syntax

@@MAX_PRECISION

Return Types

tinyint

Remarks

By default, the maximum precision is 28; however, a larger precision can be set by using the /p switch with sqlservr when starting Microsoft® SQL Server™ from a command prompt.

Examples

SELECT @@MAX_PRECISION

See Also
decimal and numeric | Configuration Functions
Precision, Scale, and Length |


@@NESTLEVEL

Returns the nesting level of the current stored procedure execution (initially 0).

Syntax

@@NESTLEVEL

Return Types

integer

Remarks

Each time a stored procedure calls another stored procedure, the nesting level is incremented. When the maximum of 32 is exceeded, the transaction is terminated.

Examples

This example creates two procedures: one that calls the other and one that displays the @@NESTLEVEL setting of each.

CREATE PROCEDURE innerproc as

select @@NESTLEVEL AS 'Inner Level'

GO

CREATE PROCEDURE outerproc as

select @@NESTLEVEL AS 'Outer Level'

EXEC innerproc

GO

EXECUTE outerproc

GO

This is the result:

Outer Level

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

1

Inner Level

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

2

See Also
@@TRANCOUNT Configuration Functions


@@OPTIONS

Returns information about current SET options.

Syntax

@@OPTIONS

Return Types

integer

Remarks

SET options can be modified as a whole by using the sp_configure user options configuration option. Each user has an @@OPTIONS function that represents the configuration. When first logging in, all users are assigned a default configuration set by the system administrator.

You can change the language and query-processing options by using the SET statement.

Examples

This example sets NOCOUNT ON and then tests the value of @@OPTIONS. The NOCOUNT ON option prevents the message about the number of rows affected from being sent back to the requesting client for every statement in a session. The value of @@OPTIONS is set to 512 (0x0200), which represents the NOCOUNT option. This example tests whether the NOCOUNT option has been enabled on the client. For example, it can help track performance differences on a client.

SET NOCOUNT ON
IF @@OPTIONS & 512 > 0

    RAISERROR ('Current user has SET NOCOUNT turned on.',1,1)

See Also
sp_configure Configuration Functions


@@PACK_RECEIVED

Returns the number of input packets read from the network by Microsoft® SQL Server™ since it was last started.

Syntax

@@PACK_RECEIVED

Return Types

integer

Remarks

To display a report containing several SQL Server statistics, including packets sent and received, run sp_monitor.

Examples

SELECT @@PACK_RECEIVED

See Also
@@PACK_SENT | System Statistical Functions
sp_monitor |


@@PACK_SENT

Returns the number of output packets written to the network by Microsoft® SQL Server™ since it was last started.

Syntax

@@PACK_SENT

Return Types

integer

Remarks

To display a report containing several SQL Server statistics, including packets sent and received, run sp_monitor.

Examples

SELECT @@PACK_SENT

See Also
@@PACK_RECEIVED | System Statistical Functions
sp_monitor |


@@PACKET_ERRORS

Returns the number of network packet errors that have occurred on Microsoft® SQL Server™ connections since the last time SQL Server was started.

Syntax

@@PACKET_ERRORS

Return Types

integer

Remarks

To display a report containing several SQL Server statistics, including packet errors, run sp_monitor.

Examples

SELECT @@PACKET_ERRORS

See Also
@@PACK_RECEIVED | sp_monitor
@@PACK_SENT | System Statistical Functions


@@PROCID

Returns the stored procedure ID of the current procedure.

Syntax

@@PROCID

Return Types

integer

Examples

This example creates a procedure that uses SELECT to display the @@PROCID setting from inside the procedure.

CREATE PROCEDURE testprocedure AS

SELECT @@PROCID AS 'ProcID'

GO

EXEC testprocedure

GO

See Also
CREATE PROCEDURE Metadata Functions


@@REMSERVER

Returns the name of the remote Microsoft® SQL Server™ database server as it appears in the login record.

Syntax

@@REMSERVER

Return Types

nvarchar(128)

Remarks

@@REMSERVER enables a stored procedure to check the name of the database server from which the procedure is run.

Examples

This example creates a procedure, check_server, that returns the name of the remote server.

CREATE PROCEDURE check_server

AS

SELECT @@REMSERVER

The stored procedure is created on SEATTLE1, the local server. The user logs on to a remote server, LONDON2, and runs check_server.

exec SEATTLE…check_server

Here is the result set:

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

LONDON2

See Also
Configuration Functions


@@ROWCOUNT

Returns the number of rows affected by the last statement.

Syntax

@@ROWCOUNT

Return Types

integer

Remarks

This variable is set to 0 by any statement that does not return rows, such as an IF statement.

Examples

This example executes UPDATE and uses @@ROWCOUNT to detect if any rows were changed.

UPDATE authors SET au_lname = 'Jones'

WHERE au_id = '999-888-7777'

IF @@ROWCOUNT = 0

    print 'Warning: No rows were updated'

See Also
@@ERROR System Functions


@@SERVERNAME

Returns the name of the local server running Microsoft® SQL Server™.

Syntax

@@SERVERNAME

Return Types

nvarchar

Remarks

The Setup program sets the server name to the computer name during installation. You can change @@SERVERNAME by using sp_addserver and then restarting SQL Server; although this method is not usually required.

Examples

SELECT @@SERVERNAME

See Also
sp_addserver Configuration Functions


@@SERVICENAME

Returns the name of the registry key under which Microsoft® SQL Server™ is running.

Syntax

@@SERVICENAME

Return Types

nvarchar

Remarks

SQL Server runs as a service named MSSQLServer on Microsoft Windows NT®. It does not run as a service on Windows® 95/98 because the operating system does not support services.

Examples

SELECT @@SERVICENAME

Here is the result set:

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

MSSQLServer

See Also
Configuration Functions


@@SPID

Returns the server process ID of the current user process.

Syntax

@@SPID

Return Types

smallint

Remarks

@@SPID can be used to identify the current user process in the output of sp_who.

Examples

This example returns the process ID, login name, and username for the current user process.

SELECT @@SPID AS 'ID', SYSTEM_USER AS 'Login Name', USER AS 'User Name'

Here is the result set:

ID     Login Name       User Name

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

11     sa               dbo

See Also
sp_lock | Configuration Functions
sp_who |


@@TEXTSIZE

Returns the current value of the TEXTSIZE option of the SET statement, which specifies the maximum length, in bytes, of text or image data that a SELECT statement returns.

Syntax

@@TEXTSIZE

Return Types

integer

Remarks

The default size is 4096 bytes (4 KB).

Examples

This example uses SELECT to display the @@TEXTSIZE value before and after it is changed with the SET TEXTSIZE statement.

SELECT @@TEXTSIZE

SET TEXTSIZE 2048

SELECT @@TEXTSIZE

Here is the result set:

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

64512

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

2048

See Also
SET TEXTSIZE Configuration Functions


@@TIMETICKS

Returns the number of microseconds per tick.

Syntax

@@TIMETICKS

Return Types

integer

Remarks

The amount of time per tick is computer-dependent. Each tick on the operating system is 31.25 milliseconds (one thirty-second of a second).

Examples

SELECT @@TIMETICKS

See Also

System Statistical Functions


@@TOTAL_ERRORS

Returns the number of disk read/write errors encountered by Microsoft® SQL Server™ since it was last started.

Syntax

@@TOTAL_ERRORS

Return Types

integer

Remarks

To display a report containing several SQL Server statistics, including total number of errors, run sp_monitor.

Examples

This example shows the number of errors encountered by SQL Server as of the current date and time.

SELECT @@TOTAL_ERRORS AS 'Errors', GETDATE() AS 'As of'

Here is the result set:

Errors         As of

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

0              1998-04-21  22:07:30.013

See Also
sp_monitor System Statistical Functions


@@TOTAL_READ

Returns the number of disk reads (not cache reads) by Microsoft® SQL Server™ since it was last started.

Syntax

@@TOTAL_READ

Return Types

integer

Remarks

To display a report containing several SQL Server statistics, including read and write activity, run sp_monitor.

Examples

This example shows the total number of disk read and writes as of the current date and time.

SELECT @@TOTAL_READ AS 'Reads', @@TOTAL_WRITE AS 'Writes', GETDATE() AS 'As of'

Here is the result set:

Reads       Writes        As of

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

978         124           1998-04-21 22:14:22.37

See Also
sp_monitor | System Statistical Functions
@@TOTAL_WRITE |


@@TOTAL_WRITE

Returns the number of disk writes by Microsoft® SQL Server™ since it was last started.

Syntax

@@TOTAL_WRITE

Return Types

integer

Remarks

To display a report containing several SQL Server statistics, including read and write activity, run sp_monitor.

Examples

This example shows the total number of disk read and writes as of the current date and time.

SELECT @@TOTAL_READ AS 'Reads', @@TOTAL_WRITE AS 'Writes', GETDATE() AS 'As of'

Here is the result set:

Reads       Writes        As of

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

978         124           1998-04-21 22:14:22.37

See Also
sp_monitor | System Statistical Functions
@@TOTAL_READ |


@@TRANCOUNT

Returns the number of active transactions for the current connection.

Syntax

@@TRANCOUNT

Return Types

integer

Remarks

The BEGIN TRANSACTION statement increments @@TRANCOUNT by 1. ROLLBACK TRANSACTION decrements @@TRANCOUNT to 0, except for ROLLBACK TRANSACTION savepoint_name, which does not affect @@TRANCOUNT. COMMIT TRANSACTION or COMMIT WORK decrement @@TRANCOUNT by 1.

Examples

This example uses @@TRANCOUNT to test for open transactions that should be committed.

BEGIN TRANSACTION

UPDATE authors SET au_lname = upper(au_lname)

WHERE au_lname = 'White'

IF @@ROWCOUNT = 2

    COMMIT TRAN

IF @@TRANCOUNT > 0

BEGIN

    PRINT 'A transaction needs to be rolled back'

    ROLLBACK TRAN

END

See Also
BEGIN TRANSACTION | ROLLBACK TRANSACTION
COMMIT TRANSACTION | System Functions


@@VERSION

Returns the date, version, and processor type for the current installation of Microsoft® SQL Server™.

Syntax

@@VERSION

Return Types

nvarchar

Remarks

The information returned by @@VERSION is similar to the product name, version, platform, and file data returned by the xp_msver stored procedure, which provides more detailed information.

Examples

This example returns the date, version, and processor type for the current installation.

SELECT @@VERSION

See Also
xp_msver Configuration Functions


ABS

Returns the absolute, positive value of the given numeric expression.

Syntax

ABS(numeric_expression)

Arguments
numeric_expression
Is an expression of the exact numeric or approximate numeric data type category, except for the bit data type.
Return Types

Returns the same type as numeric_expression.

Examples

This example shows the effect of the ABS function on three different numbers.

SELECT ABS(-1.0), ABS(0.0), ABS(1.0)

Here is the result set:

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

1.0  .0   1.0

The ABS function can produce an overflow error, for example:

SELECT ABS(convert(int, -2147483648))

Here is the error message:

Server: Msg 8115, Level 16, State 2

Arithmetic overflow error converting expression to type int.

See Also
CAST and CONVERT | Mathematical Functions
Data Types |


ACOS

Returns the angle in radians whose cosine is the given float expression (also called arccosine).

Syntax

ACOS(float_expression)

Arguments
float_expression
Is an expression of the type float or real, with a value between -1 and 1. Values outside this range return NULL and report a domain error.
Return Types

float

Examples

This example returns the ACOS of the given angle.

SET NOCOUNT OFF

DECLARE @angle float

SET @angle = -1

SELECT 'The ACOS of the angle is: ' + CONVERT(varchar, ACOS(@angle))

Here is the result set:

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

The ACOS of the angle is: 3.14159

(1 row(s) affected)

This example sets @angle to a value outside the valid range.

SET NOCOUNT OFF

DECLARE @angle float

SET @angle = 1.01

SELECT 'The ACOS of the angle is: ' + CONVERT(varchar, ACOS(@angle))

Here is the result set:

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

NULL

(1 row(s) affected)

A domain error occurred.

See Also

Mathematical Functions


ALL

Compares a scalar value with a single-column set of values.

Syntax

scalar_expression { = | <> | != | > | >= | !> | < | <= | !< } ALL (subquery)

Arguments
scalar_expression
Is any valid Microsoft® SQL Server™ expression.
{ = | <> | != | > | >= | !> | < | <= | !< }
Is a comparison operator.
subquery
Is a subquery that returns a result set of one column. The data type of the returned column must be the same data type as the data type of scalar_expression.

Is a restricted SELECT statement (the ORDER BY clause, the COMPUTE clause, and the INTO keyword are not allowed).

Return Types

Boolean

Result Value

Returns TRUE when the comparison specified is TRUE for all pairs (scalar_expression, x) where x is a value in the single-column set; otherwise returns FALSE.

See Also
CASE | Operators (Logical Operators)
Expressions | SELECT (Subqueries)
Functions | WHERE
LIKE |


ALTER DATABASE

Adds or removes files and filegroups for a database. Can also be used to modify the attributes of files and filegroups, such as changing the name or size of a file.

Syntax

ALTER DATABASE database
{ ADD FILE <filespec> [,…n] [TO FILEGROUP filegroup_name]
| ADD LOG FILE <filespec> [,…n]
| REMOVE FILE logical_file_name
| ADD FILEGROUP filegroup_name
| REMOVE FILEGROUP filegroup_name
| MODIFY FILE <filespec>
| MODIFY FILEGROUP filegroup_name filegroup_property
}

<filespec> ::=
(NAME = logical_file_name
[, FILENAME = 'os_file_name' ]
[, SIZE = size]
[, MAXSIZE = { max_size | UNLIMITED } ]
[, FILEGROWTH = growth_increment] )

Arguments
database
Is the name of the database being changed.
ADD FILE
Specifies that a file is being added.
TO FILEGROUP
Specifies the filegroup to which to add the specified file.
filegroup_name
Is the name of the filegroup to add the specified file to.
ADD LOG FILE
Specifies that a log file be added to the specified database.
REMOVE FILE
Removes the description of the file from the database system tables and deletes the physical file. The file cannot be removed unless it is empty.
ADD FILEGROUP
Specifies that a filegroup is to be added.
filegroup_name
Is the name of the filegroup to add or drop.
REMOVE FILEGROUP
Removes the filegroup from the database and deletes all the files in the filegroup. The filegroup cannot be removed unless it is empty.
MODIFY FILE
Specifies the given file should be modified, including the FILENAME, SIZE, FILEGROWTH, and MAXSIZE options. Only one of these properties can be changed at a time. NAME must be specified in the <filespec> to identify the file to be modified. If SIZE is specified, the new size must be larger than the current size of the file. FILENAME can be specified only for files in the tempdb database, and the new name does not take effect until MicrosoftSQL Server is restarted.
MODIFY FILEGROUP filegroup_name filegroup_property
Specifies the given filegroup property be applied to the filegroup. The values for filegroup_property are:
READONLY
Specifies the filegroup is read-only. Updates to objects in it are not allowed. The primary filegroup cannot be made read-only. Only users who have exclusive access to the database can mark a filegroup read-only.
READWRITE
Reverses the READONLY property. Updates are enabled for the objects in the filegroup. Only users who have exclusive access to the database can mark a filegroup read-write.
DEFAULT
Specifies the filegroup is the default filegroup for the database. Only one filegroup in a database can be the default filegroup. When you make one filegroup the default filegroup, the default property is removed from the filegroup that had been the default. CREATE DATABASE makes the primary filegroup the initial default filegroup. New tables and indexes are created in the default filegroup if no filegroup is specified in the CREATE TABLE, ALTER TABLE, or CREATE INDEX statements.
NAME
Specifies a logical name for the file.
logical_file_name
Is the name used in Microsoft SQL Server when referencing the file. The name must be unique in the server and conform to the rules for identifiers. The name can be a character or Unicode constant, a regular identifier, or a delimited identifier.
FILENAME
Specifies an operating-system file name. When used with MODIFY FILE, FILENAME can be specified only for files in the tempdb database. The new tempdb file name takes effect only after SQL Server has been stopped and restarted.
'os_file_name'
Is the path and file name used by the operating system for the file. The file must reside in the server in which SQL Server is installed. Data and log files cannot be placed on compressed file systems.

If the file is on a raw partition, os_file_name must specify only the drive letter of an existing raw partition. Only one file can be placed on each raw partition. Files on raw partitions do not autogrow; therefore, the MAXSIZE and FILEGROWTH parameters are not needed when os_file_name specifies a raw partition.

SIZE
Specifies the size of the file.
size
Is the size of the file. The MB and KB suffixes can be used to specify megabytes or kilobytes. The default is MB. Specify a whole number, do not include a decimal. The minimum value for size is 512 KB, and the default if size is not specified is 1 MB. When specified with ADD FILE, size is the initial size for the file. When specified with MODIFY FILE, size is the new size for the file, and must be larger than the current size of the file.
MAXSIZE
Specifies maximum size to which the file is allowed to grow.
max_size
Is the maximum size to which the file can grow. The MB and KB suffixes can be used to specify megabytes or kilobytes. The default is MB. Specify a whole number, do not include a decimal. If max_size is not specified, the file will grow until the disk is full. The Microsoft Windows NT® application log warns an administrator when a disk is about to become full.
UNLIMITED
Specifies that the file grows until the disk is full.
FILEGROWTH
Specifies file growth increment.
growth_increment
Is the amount of space added to the file each time new space is needed. A value of 0 indicates no growth. The value can be specified in MB, KB, or %. Specify a whole number, do not include a decimal. When % is specified, the growth increment size is the specified percentage of the size of the file at the time the increment occurs. If a number is specified without an MB, KB, or % suffix, the default is MB. The default value if FILEGROWTH is not specified is 10%, and the minimum value is 64 KB. The size specified is rounded to the nearest 64 KB.
Remarks

To remove a database, use DROP DATABASE. To rename a database, use sp_renamedb. For information about decreasing the size of a database, see DBCC SHRINKDATABASE.

You cannot add or remove a file while a BACKUP statement is executing.

Adding or dropping a data or log file invalidates an existing log backup chain. If the backup and restore plan for the database includes log backups, perform a BACKUP DATABASE statement to start a new sequence of log backups soon after the ALTER DATABASE statement completes.

To specify a fraction of a megabyte in the size parameters, convert the value to kilobytes by multiplying the number by 1024. For example, specify 1536 KB instead of 1.5MB (1.5 x 1024 = 1536).

Permissions

ALTER DATABASE permissions default to members of the db_owner and db_ddladmin fixed database roles, and to members of the sysadmin and dbcreator fixed server roles. These permissions are not transferrable.

Examples
A. Add a file to a database

This example creates a database and alters it to add a new 5-MB data file.

USE master

GO

CREATE DATABASE Test1 ON

(

 NAME = Test1dat1,

 FILENAME = 'c:\mssql7\data\t1dat1.ndf',

 SIZE = 5MB,

 MAXSIZE = 100MB,

 FILEGROWTH = 5MB

)

GO

ALTER DATABASE Test1

ADD FILE

(

 NAME = Test1dat2,

 FILENAME = 'c:\mssql7\data\t1dat2.ndf',

 SIZE = 5MB,

 MAXSIZE = 100MB,

 FILEGROWTH = 5MB

)

GO

B. Add a filegroup with two files to a database

This example creates a filegroup in the Test 1 database created in Example A and adds two 5-MB files to the filegroup. It then makes Test1FG1 the default filegroup.

USE master

GO

ALTER DATABASE Test1

ADD FILEGROUP Test1FG1

GO

ALTER DATABASE Test1

ADD FILE

( NAME = test1dat3,

  FILENAME = 'c:\mssql7\data\t1dat3.ndf',

  SIZE = 5MB,

  MAXSIZE = 100MB,

  FILEGROWTH = 5MB),

( NAME = test1dat4,

  FILENAME = 'c:\mssql7\data\t1dat4.ndf',

  SIZE = 5MB,

  MAXSIZE = 100MB,

  FILEGROWTH = 5MB)

TO FILEGROUP Test1FG1

ALTER DATABASE Test1

MODIFY FILEGROUP Test1FG1 DEFAULT

GO

C. Add two log files to a database

This example adds two 5-MB log files to a database.

USE master

GO

ALTER DATABASE Test1

ADD LOG FILE

( NAME = test1log2,

  FILENAME = 'c:\mssql7\data\test2log.ldf',

  SIZE = 5MB,

  MAXSIZE = 100MB,

  FILEGROWTH = 5MB),

( NAME = test1log3,

  FILENAME = 'c:\mssql7\data\test3log.ldf',

  SIZE = 5MB,

  MAXSIZE = 100MB,

  FILEGROWTH = 5MB)

GO

D. Remove a file from a database

This example removes one of the files added to the Test1 database in Example B.

USE master

GO

ALTER DATABASE Test1

REMOVE FILE test1dat4

GO

E. Modify a file

This example increases the size of one of the files added to the Test1 database in Example B.

USE master

GO

ALTER DATABASE Test1

MODIFY FILE

    (NAME = test1dat3,

    SIZE = 20MB)

GO

F. Make the primary filegroup the default

This example makes the primary filegroup the default filegroup if another filegroup was made the default earlier.

USE master

GO

ALTER DATABASE MyDatabase

MODIFY FILEGROUP [PRIMARY] DEFAULT

GO

See Also
CREATE DATABASE | sp_helpfilegroup
DROP DATABASE | sp_renamedb
sp_helpdb | sp_spaceused
sp_helpfile |


ALTER PROCEDURE

Alters a previously created procedure (created by executing the CREATE PROCEDURE statement) without changing permissions and without affecting any dependent stored procedures or triggers. For more information about the parameters used in the ALTER PROCEDURE statement, CREATE PROCEDURE.

Syntax

ALTER PROC[EDURE] procedure_name [;number]
[
{@parameter data_type } [VARYING] [= default] [OUTPUT]
]
[,…n]
[WITH
{
RECOMPILE
| ENCRYPTION
| RECOMPILE , ENCRYPTION
}
]
[FOR REPLICATION]
AS
sql_statement […n]

Arguments
procedure_name
Is the name of the procedure to change. Procedure names must conform to the rules for identifiers.
;number
Is an existing optional integer used to group procedures of the same name so that they can be dropped together with a single DROP PROCEDURE statement.
@parameter
Is a parameter in the procedure.
data_type
Is the data type of the parameter.
VARYING
Specifies the result set supported as an output parameter (constructed dynamically by the stored procedure and whose contents can vary). Applies only to cursor parameters.
default
Is a default value for the parameter.
OUTPUT
Indicates that the parameter is a return parameter.
n
Is a placeholder indicating up to 1,024 parameters can be specified.
{RECOMPILE | ENCRYPTION | RECOMPILE, ENCRYPTION}
RECOMPILE indicates that Microsoft® SQL Server™ does not cache a plan for this procedure and the procedure is recompiled each time it is executed.

ENCRYPTION indicates that SQL Server encrypts the syscomments table entry that contains the text of the ALTER PROCEDURE statement.

Note During an upgrade, SQL Server uses the encrypted comments stored in syscomments to re-create encrypted procedures.

FOR REPLICATION
Specifies that stored procedures created for replication cannot be executed on the subscribing server, and is used when creating a filter stored procedure that is executed only by replication. This option cannot be used with the WITH RECOMPILE option.
AS
Are the actions the procedure is to take.
sql_statement
Is any number and type of Transact-SQL statements to be included in the procedure. Some limitations do apply. For more information, see sql_statement Limitations in CREATE PROCEDURE.
n
Is a placeholder indicating that multiple Transact-SQL statements can be included in the procedure. For more information, see sql_statement Limitations in CREATE PROCEDURE.
Remarks

For more information about ALTER PROCEDURE, see Remarks in CREATE PROCEDURE.

Note If a previous procedure definition was created using WITH ENCRYPTION or WITH RECOMPILE, these options are only enabled if they are included in ALTER PROCEDURE.

Permissions

ALTER PROCEDURE permissions default to members of the db_owner and ddl_admin fixed database roles, and are not transferable. Permissions and the startup property remain unchanged for a procedure modified with ALTER PROCEDURE.

Examples

This example creates a procedure called Oakland_authors that by default contains all authors from the city of Oakland, CA. Permissions are granted. Then, when the procedure must be changed to retrieve all authors from California, ALTER PROCEDURE is used to redefine the stored procedure.

USE pubs

GO

IF EXISTS(SELECT name FROM sysobjects WHERE name = 'Oakland_authors' AND type = 'P')

    DROP PROCEDURE Oakland_authors

GO

-- Create a procedure from the authors table that contains author

-- information for those authors who live in Oakland, California.

USE pubs

GO

CREATE PROCEDURE Oakland_authors

AS

SELECT au_fname, au_lname, address, city, zip

FROM pubs..authors

WHERE city = 'Oakland'

and state = 'CA'

ORDER BY au_lname, au_fname

GO

-- Here is the statement to actually see the text of the procedure.

SELECT o.id, c.text

FROM sysobjects o INNER JOIN syscomments c ON o.id = c.id

WHERE o.type = 'P' and o.name = 'Oakland_authors'

-- Here, EXECUTE permissions are granted on the procedure to public.

GRANT EXECUTE ON Oakland_authors TO public

GO

-- The procedure must be changed to include all

-- authors from California, regardless of what city they live in.

-- If ALTER PROCEDURE is not used but the procedure is dropped

-- and then re-created, the above GRANT statement and any

-- other statements dealing with permissions that pertain to this

-- procedure must be redone.

ALTER PROCEDURE Oakland_authors

WITH ENCRYPTION

AS

SELECT au_fname, au_lname, address, city, zip

FROM pubs..authors

WHERE state = 'CA'

ORDER BY au_lname, au_fname

GO

-- Here is the statement to actually see the text of the procedure.

SELECT o.id, c.text

FROM sysobjects o INNER JOIN syscomments c ON o.id = c.id

WHERE o.type = 'P' and o.name = 'Oakland_authors'

GO

See Also
Data Types | EXECUTE
DROP PROCEDURE | System Tables


ALTER TABLE

Modifies a table definition by altering, adding or dropping columns and constraints, or by disabling or enabling constraints and triggers.

Syntax

ALTER TABLE table
{ [ALTER COLUMN column_name
 { new_data_type [ (precision[, scale] ) ]
[ NULL | NOT NULL ]
| {ADD | DROP} ROWGUIDCOL
}
]
| ADD
{ [ <column_definition> ]
| column_name AS computed_column_expression
}[,…n]
| [WITH CHECK | WITH NOCHECK] ADD
{ <table_constraint> }[,...n]
| DROP
{ [CONSTRAINT] constraint_name
| COLUMN column
}[,…n]
| {CHECK | NOCHECK} CONSTRAINT
{ALL | constraint_name[,…n]}
| {ENABLE | DISABLE} TRIGGER
{ALL | trigger_name[,…n]}
}

<column_definition> ::= { column_name data_type }
[ [ DEFAULT constant_expression ]
| [ IDENTITY [(seed, increment ) [NOT FOR REPLICATION] ] ]
]
[ ROWGUIDCOL ]
[ <column_constraint>] [ …n]

<column_constraint> ::= [CONSTRAINT constraint_name]
{
[ NULL | NOT NULL ]
| [ { PRIMARY KEY | UNIQUE }
[CLUSTERED | NONCLUSTERED]
[WITH FILLFACTOR = fillfactor]
[ON {filegroup | DEFAULT} ]]
]
| [ [FOREIGN KEY]
REFERENCES ref_table [(ref_column) ]
[NOT FOR REPLICATION]
]
| CHECK [NOT FOR REPLICATION]
(logical_expression)
}

<table_constraint> ::= [CONSTRAINT constraint_name]
{ [ { PRIMARY KEY | UNIQUE }
[ CLUSTERED | NONCLUSTERED]
{ ( column[,…n] ) }
[ WITH FILLFACTOR = fillfactor]
[ON {filegroup | DEFAULT} ]
]
| FOREIGN KEY
[(column[,…n])]
REFERENCES ref_table [(ref_column[,…n])]
[NOT FOR REPLICATION]
| DEFAULT constant_expression
[FOR column]
| CHECK [NOT FOR REPLICATION]
(logical_expression)
}

Arguments
table
Is the name of the table to be altered. If the table is not in the current database or owned by the current user, the database and owner can be explicitly specified.
WITH CHECK | WITH NOCHECK
Specifies whether the data in the table is or is not validated against a newly added or reenabled FOREIGN KEY or CHECK constraint. If not specified, WITH CHECK is assumed for new constraints, and WITH NOCHECK is assumed for reenabled constraints.

If you do not want to verify new CHECK or FOREIGN KEY constraints against existing data, use WITH NOCHECK. (This is not recommended except in rare cases). The new constraint will be evaluated in all future updates. Any constraint violations that are suppressed by WITH NOCHECK when the constraint is added may cause future updates to fail if they update rows with data that does not comply with the constraint.

Constraints defined WITH NOCHECK are not considered by the query optimizer. These constraints are ignored until all such constraints are reenabled using ALTER TABLE table CHECK CONSTRAINT ALL.

ALTER COLUMN
Specifies that the given column is to be changed or altered. ALTER COLUMN is not allowed if the compatibility level is 65 or earlier. For more information, see sp_dbcmptlevel. The altered column cannot be:
  • A column with a text, image, ntext, or timestamp data type.
  • The ROWGUIDCOL for the table.
  • A computed column or be used in a computed column.
  • A replicated column.
  • Used in an index, unless the column is a varchar or varbinary data type, the data type is not changed, and the new size is equal to or larger than the old size.
  • Used in statistics generated by the CREATE STATISTICS statement. First remove the statistics using the DROP STATISTICS statement. Statistics automatically generated by the query optimizer are automatically dropped by ALTER COLUMN.
  • Used in a PRIMARY KEY or [FOREIGN KEY] REFERENCES constraint.
  • Used in a CHECK or UNIQUE constraint, except that altering the length of a variable-length column used in a CHECK or UNIQUE constraint is allowed.
  • Associated with a default.

Some data type changes may result in a change in the data. For example, changing an nchar or nvarchar column to char or varchar can result in the conversion of extended characters. For more information, see CAST and Convert. Reducing the precision and scale of a column may result in data truncation.

column_name
Is the name of the column to be altered, added or dropped. For new columns, column_name can be omitted for columns created with a timestamp data type. The name timestamp is used if no column_name is specified for a timestamp data type column.
new_data_type
Is the new data type for the altered column. Criteria for the new_data_type of an altered column are:
  • The previous data type must be implicitly convertible to the new data type.
  • new_data_type cannot be timestamp.
  • ANSI null defaults are always on for ALTER COLUMN; if not specified, the column is nullable.
  • ANSI padding is always on for ALTER COLUMN.
  • If the altered column is an identity column, new_data_type must be a data type that supports the identity property.
  • The current setting for SET ARITHABORT is ignored. ALTER TABLE operates as if the ARITHABORT option is ON.
precision
Is the precision for the specified data type. For more information about valid precision values, see Precision, Scale, and Length.
scale
Is the scale for the specified data type. For more information about valid scale values, see Precision, Scale, and Length.
NULL | NOT NULL
Specifies whether the column can accept null values. Columns that do not allow null values can be added with ALTER TABLE only if they have a default specified. A new column added to a table must either allow null values, or the column must be specified with a default value.

If the new column allows null values and no default is specified, the new column contains a null value for each row in the table. If the new column allows null values and a default definition is added with the new column, the WITH VALUES option can be used to store the default value in the new column for each existing row in the table.

If the new column does not allow null values, a DEFAULT definition must be added with the new column, and the new column automatically loads with the default value in the new columns in each existing row.

NULL can be specified in ALTER COLUMN to make a NOT NULL column allow null values, except for columns in PRIMARY KEY constraints. NOT NULL can be specified in ALTER COLUMN only if the column contains no null values. The null values must be updated to some value before the ALTER COLUMN NOT NULL is allowed, such as:

UPDATE MyTable SET NullCol = N'some_value' WHERE NullCol IS NULL

ALTER TABLE MyTable ALTER COLUMN NullCOl NVARCHAR(20) NOT NULL

If NULL or NOT NULL is specified with ALTER COLUMN, new_data_type [(precision [, scale ])] must also be specified. If the data type, precision and scale are not being changed, specify the current values for the column.

[ {ADD | DROP} ROWGUIDCOL ]
Specifies the ROWGUIDCOL property is being added to or dropped from the specified column. ROWGUIDCOL is a keyword indicating that the column is a row global unique identifier column. Only one uniqueidentifier column per table can be designated as the ROWGUIDCOL column. The ROWGUIDCOL property can be assigned only to a uniqueidentifier column.

The ROWGUIDCOL property does not enforce uniqueness of the values stored in the column. It also does not automatically generate values for new rows inserted into the table. To generate unique values for each column, either use the NEWID function on INSERT statements or specify the NEWID function as the default for the column.

ADD
Specifies that one or more column definitions, computed column definitions, or table constraints are being added.
computed_column_expression
Is an expression that defines the value of a computed column. A computed column is a virtual column that is not physically stored in the table, but it is computed from an expression using other columns in the same table. For example, a computed column could have the definition: cost AS price * qty. The expression can be a noncomputed column name, constant, function, variable, and any combination of these connected by one or more operators. The expression cannot be a subquery.

Computed columns can be used in select lists, WHERE clauses, ORDER BY clauses, or any other locations where regular expressions can be used, with these exceptions:

  • A computed column cannot be used as a key column in an index or as part of any PRIMARY KEY, UNIQUE, FOREIGN KEY, or DEFAULT constraint definition.
  • A computed column cannot be the target of an INSERT or UPDATE statement.

Note Because each row in a table may have different values for columns involved in a computed column, the computed column may not have the same result for each row.

n
Is a placeholder indicating that the preceding item can be repeated n number of times.
DROP { [CONSTRAINT] constraint_name | COLUMN column_name }
Specifies that constraint_name or column_name is removed from the table. DROP COLUMN is not allowed if the compatibility level is 65 or earlier. Multiple columns and constraints can be listed. A column cannot be dropped if it is:
  • A replicated column.
  • Used in an index.
  • Used in a CHECK, FOREIGN KEY, UNIQUE, or PRIMARY KEY constraint.
  • Associated with a default defined with the DEFAULT keyword, or bound to a default object.
  • Bound to a rule.
{ CHECK | NOCHECK} CONSTRAINT
Specifies that constraint_name is enabled or disabled. When disabled, future inserts or updates to the column are not validated against the constraint conditions. This option can only be used with FOREIGN KEY and CHECK constraints.
ALL
Specifies that all constraints are disabled with the NOCHECK option, or enabled with the CHECK option.
{ENABLE | DISABLE} TRIGGER
Specifies that trigger_name is enabled or disabled. When a trigger is disabled it is still defined for the table; however, when INSERT, UPDATE or DELETE statements are executed against the table, the actions in the trigger are not performed until the trigger is reenabled.
ALL
Specifies that all triggers in the table are enabled or disabled.
trigger_name
Specifies the name of the trigger to disable or enable.
column_name data_type
Is the data type for the new column. data_type can be any Microsoft® SQL Server™ or user-defined data type.
DEFAULT
Is a keyword that specifies the default value for the column. DEFAULT definitions can be used to provide values for a new column in the existing rows of data. DEFAULT definitions cannot be added to columns that have a timestamp data type, an IDENTITY property, an existing DEFAULT definition, or a bound default. If the column has an existing default, the default must be dropped before the new default can be added. To maintain compatibility with earlier versions of SQL Server, it is possible to assign a constraint name to a DEFAULT.
IDENTITY
Specifies that the new column is an identity column. When a new row is added to the table, SQL Server provides a unique, incremental value for the column. Identity columns are commonly used in conjunction with PRIMARY KEY constraints to serve as the unique row identifier for the table. The IDENTITY property can be assigned to a tinyint, smallint, int, decimal(p,0), or numeric(p,0) column. Only one identity column can be created per table. The DEFAULT keyword and bound defaults cannot be used with an identity column. Either both the seed and increment must be specified, or neither. If neither are specified, the default is (1,1).
seed
Is the value that is used for the first row loaded into the table.
increment
Is the incremental value that is added to the identity value of the previous row that was loaded.
NOT FOR REPLICATION
Specifies that the IDENTITY property should not be enforced when a replication login, such as sqlrepl, inserts data into the table. NOT FOR REPLICATION can also be specified on constraints. The constraint is not checked when a replication login inserts data into the table.
CONSTRAINT
Specifies the beginning of a PRIMARY KEY, UNIQUE, FOREIGN KEY, or CHECK constraint, or a DEFAULT definition.
constraint_name
Is the name of the new constraint. Constraint names must follow the rules for identifiers, except that the name cannot begin with a number sign (#). If constraint_name is not supplied, a system-generated name is assigned to the constraint.
PRIMARY KEY
Is a constraint that enforces entity integrity for a given column or columns through a unique index. Only one PRIMARY KEY constraint can be created per table.
UNIQUE
Is a constraint that provides entity integrity for a given column or columns through a unique index.
CLUSTERED | NONCLUSTERED
Specifies that a clustered or nonclustered index is created for the PRIMARY KEY or UNIQUE constraint. PRIMARY KEY constraints default to CLUSTERED; UNIQUE constraints default to NONCLUSTERED.

If a clustered constraint or index already exists on a table, CLUSTERED cannot be specified in ALTER TABLE. If a clustered constraint or index already exists on a table, PRIMARY KEY constraints default to NONCLUSTERED.

WITH FILLFACTOR = fillfactor
Specifies how full SQL Server should make each index page used to store the index data. User-specified fillfactor values can be from 1 through 100. If a value is not specified, the default is 0. A lower fillfactor creates the index with more space available for new index entries without having to allocate new space. For more information, see CREATE INDEX.
ON {filegroup | DEFAULT}
Specifies the storage location of the index that is created for the constraint. If filegroup is specified, the index is created in the named filegroup. If DEFAULT is specified, the index is created in the default filegroup. If ON is not specified, the index is created in the filegroup that contains the table. If ON is specified when adding a clustered index for a PRIMARY KEY or UNIQUE constraint, the entire table is moved to the specified filegroup when the clustered index is created.
FOREIGN KEY…REFERENCES
Is a constraint that provides referential integrity for the data in the column. FOREIGN KEY constraints require that each value in the column exists in the specified column in the referenced table.
ref_table
Is the name of the table that is referenced by the FOREIGN KEY constraint.
ref_column
Is a column or list of columns in parentheses that is referenced by the new FOREIGN KEY constraint.
WITH VALUES
Specifies that the value given in DEFAULT constant_expression is stored in a new column added to existing rows. WITH VALUES can be specified only when DEFAULT is specified in an ADD column clause. If the added column allows null values and WITH VALUES is specified, the default value is stored in the new column added to existing rows. If WITH VALUES is not specified for columns that allow nulls, the value NULL is stored in the new column in existing rows. If the new column does not allow nulls, the default value is stored in new rows regardless of whether WITH VALUES is specified.
constant_expression
Is a literal value, a NULL, or a system function that is used as the default value for the column.
CHECK
Is a constraint that enforces domain integrity by limiting the possible values that can be entered into a column or columns.
logical_expression
Is a logical expression that is used in a CHECK constraint and returns TRUE or FALSE. Logical_expression used with CHECK constraints cannot reference another table, but can reference other columns in the same table for the same row.
column[,…n]
Is a column or list of columns in parentheses used in a new constraint.
FOR column
Specifies the column associated with a table-level DEFAULT definition.
Remarks

To add new rows of data, use the INSERT statement. To remove rows of data, use the DELETE or TRUNCATE TABLE statements. To change the values in existing rows, use UPDATE.

The changes specified in ALTER TABLE are implemented immediately. If the changes require modifications of the rows in the table, ALTER TABLE updates the rows. ALTER TABLE acquires a schema modify lock on the table to ensure no other connections reference even the metadata for the table during the change. The modifications made to the table are logged and fully recoverable. Changes that affect all the rows in very large tables, such as dropping a column or adding a NOT NULL column with a default, can take a long time to complete and generate many log records. These ALTER TABLE statements should be executed with the same care as any INSERT, UPDATE, or DELETE statement that affects a large number of rows.

If there are any execution plans in the procedure cache referencing the table, ALTER TABLE marks them to be recompiled on their next execution.

Indexes created as part of a constraint are dropped when the constraint is dropped. Indexes that were created with CREATE INDEX must be dropped with the DROP INDEX statement. The DBCC DBREINDEX statement can be used to rebuild an index that is part of a constraint definition; the constraint does not need to be dropped and added again with ALTER TABLE.

All indexes and constraints based on a column must be removed before the column can be removed.

When constraints are added, all existing data is verified for constraint violations. If any violations occur, the ALTER TABLE statement fails and an error is returned.

When a new PRIMARY KEY or UNIQUE constraint is added to an existing column, the data in the column(s) must be unique. If duplicate values are found, the ALTER TABLE statement fails. The WITH NOCHECK option has no effect when adding PRIMARY KEY or UNIQUE constraints.

Each PRIMARY KEY and UNIQUE constraint generates an index. The number of UNIQUE and PRIMARY KEY constraints cannot cause the number of indexes on the table to exceed 249 nonclustered indexes and 1 clustered index.

If a column is added having a uniqueidentifier data type, it can be defined with a default that uses the NEWID() function to supply the unique identifier values in the new column for each existing row in the table.

SQL Server does not enforce an order in which DEFAULT, IDENTITY, ROWGUIDCOL, or column constraints are specified in a column definition.

The ALTER COLUMN clause of ALTER TABLE does not bind or unbind any rules on a column. Rules must be bound or unbound separately using sp_bindrule or sp_unbindrule.

Rules can be bound to a user-defined data type. CREATE TABLE then automatically binds the rule to any column defined having the user-defined data type. ALTER COLUMN does not unbind the rule when changing the data type of the column. The rule from the original user-defined data type remains bound to the column. After ALTER COLUMN has changed the data type of the column, any subsequent sp_unbindrule execution that unbinds the rule from the user-defined data type does not unbind it from the column for which data type was changed. If ALTER COLUMN changes the data type of a column to a user-defined data type that is bound to a rule, the rule bound to the new data type is not bound to the column.

Permissions

ALTER TABLE permissions default to the table owner, members of the sysadmin fixed server role, and to members of the db_owner and db_ddladmin fixed database roles.

Examples
A. Alter a table to add a new column

This example adds a column that allows null values and has no values provided through a DEFAULT definition. Each row will have a NULL in the new column.

CREATE TABLE doc_exa ( column_a INT)

GO

ALTER TABLE doc_exa ADD column_b VARCHAR(20) NULL

GO

EXEC sp_help doc_exa

GO

DROP TABLE doc_exa

GO

B. Alter a table to drop a column

This example modifies a table to remove a column.

CREATE TABLE doc_exb ( column_a INT, column_b VARCHAR(20) NULL)

GO

ALTER TABLE doc_exb DROP COLUMN column_b

GO

EXEC sp_help doc_exb

GO

DROP TABLE doc_exb

GO

C. Alter a table to add a column with a constraint

This example adds a new column with a UNIQUE constraint.

CREATE TABLE doc_exc ( column_a INT)

GO

ALTER TABLE doc_exc ADD column_b VARCHAR(20) NULL

   CONSTRAINT exb_unique UNIQUE

GO

EXEC sp_help doc_exc

GO

DROP TABLE doc_exc

GO

D. Alter a table to add a constraint that is not verified

This example adds a constraint to an existing column in the table. The column has a value that violates the constraint; therefore, WITH NOCHECK is used to prevent the constraint from being validated against existing rows, and to allow the constraint to be added.

CREATE TABLE doc_exd ( column_a INT)

GO

INSERT INTO doc_exd VALUES (-1)

GO

ALTER TABLE doc_exd WITH NOCHECK

ADD CONSTRAINT exd_check CHECK (column_a > 1)

GO

EXEC sp_help doc_exd

GO

DROP TABLE doc_exd

GO

E. Alter a table to add several columns with constraints

This example adds several columns with constraints that are defined with the new column. The first new column has an IDENTITY property; each row in the table has new incremental values in the identity column.

CREATE TABLE doc_exe ( column_a INT CONSTRAINT column_a_un UNIQUE)

GO

ALTER TABLE doc_exe ADD

/* Add a PRIMARY KEY identity column. */

column_b INT IDENTITY

CONSTRAINT column_b_pk PRIMARY KEY,

/* Add a column referencing another column in the same table. */

column_c INT NULL

CONSTRAINT column_c_fk

REFERENCES doc_exe(column_a),

/* Add a column with a constraint to enforce that   */

/* nonnull data is in a valid phone number format.  */

column_d VARCHAR(16) NULL

CONSTRAINT column_d_chk

CHECK

(column_d IS NULL OR

column_d LIKE "[0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]" OR

column_d LIKE

"([0-9][0-9][0-9]) [0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]"),

/* Add a nonnull column with a default.  */

column_e DECIMAL(3,3)

CONSTRAINT column_e_default

DEFAULT .081

GO

EXEC sp_help doc_exe

GO

DROP TABLE doc_exe

GO

F. Add a nullable column with default values

This example adds a nullable column with a DEFAULT definition, and uses WITH VALUES to provide values for each existing row in the table. If WITH VALUES is not used, each row has the value NULL in the new column.

ALTER TABLE MyTable

ADD AddDate smalldatetime NULL

CONSTRAINT AddDateDflt

DEFAULT getdate() WITH VALUES

G. Disable and reenable a constraint

    This example disables a constraint that limits the salaries that are accepted in the data. WITH NOCHECK CONSTRAINT is used with ALTER TABLE to disable the constraint and allow an insert that would normally violate the constraint. WITH CHECK CONSTRAINT is used to reenable the constraint.

    CREATE TABLE cnst_example

    (id INT NOT NULL,

     name VARCHAR(10) NOT NULL,

     salary MONEY NOT NULL

         CONSTRAINT salary_cap CHECK (salary < 100000)

    )

    -- Valid inserts

    INSERT INTO cnst_example VALUES (1,"Joe Brown",65000)

    INSERT INTO cnst_example VALUES (2,"Mary Smith",75000)

    -- This insert violates the constraint.

    INSERT INTO cnst_example VALUES (3,"Pat Jones",105000)

    -- Disable the constraint and try again.

    ALTER TABLE cnst_example NOCHECK CONSTRAINT salary_cap

    INSERT INTO cnst_example VALUES (3,"Pat Jones",105000)

    -- Reenable the constraint and try another insert, will fail.

    ALTER TABLE cnst_example CHECK CONSTRAINT salary_cap

    INSERT INTO cnst_example VALUES (4,"Eric James",110000)

    H. Disable and reenable a trigger

    This example uses the DISABLE TRIGGER option of ALTER TABLE to disable the trigger and allow an insert that would normally violate the trigger. It then uses ENABLE TRIGGER to reenable the trigger.

    CREATE TABLE trig_example

    (id INT,

    name VARCHAR(10),

    salary MONEY)

    go

    -- Create the trigger.

    CREATE TRIGGER trig1 ON trig_example FOR INSERT

    as

    IF (SELECT COUNT(*) FROM INSERTED

    WHERE salary > 100000) > 0

    BEGIN

    print "TRIG1 Error: you attempted to insert a salary > $100,000"

    ROLLBACK TRANSACTION

    END

    GO

    -- Attempt an insert that violates the trigger.

    INSERT INTO trig_example VALUES (1,"Pat Smith",100001)

    GO

    -- Disable the trigger.

    ALTER TABLE trig_example DISABLE TRIGGER trig1

    GO

    -- Attempt an insert that would normally violate the trigger

    INSERT INTO trig_example VALUES (2,"Chuck Jones",100001)

    GO

    -- Reenable the trigger.

    ALTER TABLE trig_example ENABLE TRIGGER trig1

    GO

    -- Attempt an insert that violates the trigger.

    INSERT INTO trig_example VALUES (3,"Mary Booth",100001)

    GO

    See Also
    DROP TABLE sp_help


ALTER TRIGGER

Alters the definition of a trigger created previously by the CREATE TRIGGER statement. For more information about the parameters used in the ALTER TRIGGER statement, see CREATE TRIGGER.

Syntax

ALTER TRIGGER trigger_name
ON table
[WITH ENCRYPTION]
{
{FOR { [DELETE] [,] [UPDATE] [,][INSERT] }
[NOT FOR REPLICATION]
AS
sql_statement […n]
}
|
{FOR { [INSERT] [,] [UPDATE] }
[NOT FOR REPLICATION]
AS
{ IF UPDATE (column)
[{AND | OR} UPDATE (column)]
[…n]
| IF (COLUMNS_UPDATED() {bitwise_operator} updated_bitmask)
{ comparison_operator} column_bitmask […n]
}
sql_statement […n]
}
}

Arguments
trigger_name
Is the name of the existing trigger to alter.
table
Is the table on which the trigger is executed.
WITH ENCRYPTION
Encrypts the syscomments entries that contain the text of the ALTER TRIGGER statement.

Note If a previous trigger definition was created using WITH ENCRYPTION or RECOMPILE, these options are only enabled if they are included in ALTER TRIGGER.

FOR { [DELETE] [,] [UPDATE] [,][INSERT] } | { [INSERT] [,] [UPDATE] }
Specifies which data modification statements, when attempted against this table, activate the trigger. At least one option must be specified. Any combination of these, in any order is allowed in the trigger definition. If more than one option is specified, separate the options with commas.

Note If the ALTER TRIGGER statement specifies {INSERT, UPDATE, DELETE} | {INSERT, DELETE} trigger information different from the original CREATE TRIGGER statement, the ALTER TRIGGER statement overrides the behavior specified in CREATE TRIGGER. For example, if an UPDATE trigger is altered to an INSERT trigger and a different INSERT trigger already exists, then an additional INSERT trigger is created.

NOT FOR REPLICATION
Indicates that the trigger should not be executed when a replication login such as sqlrepl modifies the table involved in the trigger.
AS
Are the actions the trigger is to take.
sql_statement
Is the trigger condition or conditions and action or actions.
n
Is a placeholder indicating that multiple Transact-SQL statements can be included in the trigger.
IF UPDATE (column)
Tests for an INSERT or UPDATE action to a specified column and is not used with DELETE operations.

UPDATE(column) can be used anywhere inside the body of the trigger.

{AND | OR}
Specifies another column to test for either an INSERT or UPDATE action.
column
Is the name of the column to test for either an INSERT or UPDATE action.
IF (COLUMNS_UPDATED())
Tests to see, in an INSERT or UPDATE trigger only, whether the mentioned column or columns were inserted or updated. COLUMNS_UPDATED returns a varbinary bit pattern that indicates which columns of the table were inserted or updated.

COLUMNS_UPDATED can be used anywhere inside the body of the trigger.

bitwise_operator
Is the bitwise operator to use in the comparison.
updated_bitmask
Is the integer bitmask of those columns actually updated or inserted. For example, table t1 contains columns C1, C2, C3, C4, and C5. To check whether columns C2, C3, and C4 are all updated (with table t1 having an UPDATE trigger), specify a value of 14. To check whether only C2 is updated, specify a value of 2.
comparison_operator
Is the comparison operator. Use the equal sign (=) to check whether all columns specified in updated_bitmask are actually updated. Use the greater than symbol (>) to check whether any or not all columns specified in the updated_bitmask are updated.
column_bitmask
Is the integer bitmask of the columns to check.
Remarks

For more information about ALTER TRIGGER, see Remarks in CREATE TRIGGER.

Note Because Microsoft does not support the addition of user-defined triggers on system tables, it is recommended that no user-defined triggers be created on system tables.

Permissions

ALTER TRIGGER permissions default to members of the db_owner and db_ddladmin fixed database roles, and to the table owner. These permissions are not transferable.

Examples

This example creates a trigger that prints a user-defined message to the client when a user tries to add or change data in the roysched table. Then, the trigger is altered using ALTER TRIGGER to apply the trigger only on INSERT activities. This trigger is helpful because it reminds the user who updates or inserts rows into this table to also notify the book authors and publishers.

USE pubs

GO

CREATE TRIGGER royalty_reminder

ON roysched

WITH ENCRYPTION

FOR INSERT, UPDATE

AS RAISERROR (50009, 16, 10)

-- Now, alter the trigger.

USE pubs

GO

ALTER TRIGGER royalty_reminder

ON roysched

FOR INSERT

AS RAISERROR (50009, 16, 10)

Message 50009 is a user-defined message in sysmessages. For information about creating user-defined messages, see sp_addmessage.

See Also
DROP TRIGGER | sp_addmessage
Transactions |


ALTER VIEW

Alters a previously created view (created by executing CREATE VIEW) without affecting dependent stored procedures or triggers and without changing permissions. For more information about the parameters used in the ALTER VIEW statement, see CREATE VIEW.

Syntax

ALTER VIEW view_name [(column [,…n])]
[WITH ENCRYPTION]
AS
select_statement
[WITH CHECK OPTION]

Arguments
view_name
Is the view to change.
column
Is the name of one or more columns, separated by commas, to be part of the given view.

Important Column permissions are maintained only when columns have the same name before and after ALTER VIEW is performed.

Note In the columns for the view, the permissions for a column name apply across a CREATE VIEW or ALTER VIEW statement, regardless of the source of the underlying data. For example, if permissions are granted on the title_id column in a CREATE VIEW statement, an ALTER VIEW statement can rename the title_id column (for example, to qty) and still have the permissions that are associated with the view using title_id.

n
Is a placeholder indicating the column can be repeated n number of times.
ENCRYPTION
Encrypts the syscomments entries that contain the text of the CREATE VIEW statement.
AS
Are the actions the view is to take.
select_statement
Is the SELECT statement that defines the view.
CHECK OPTION
Forces all data modification statements executed against the view to adhere to the criteria set within the select_statement defining the view.
Remarks

For more information about ALTER VIEW, see Remarks in CREATE VIEW.

Note If the previous view definition was created using WITH ENCRYPTION or CHECK OPTION, these options are enabled only if included in ALTER VIEW.

If a view currently in use is modified by using ALTER VIEW, Microsoft® SQL Server™ takes an exclusive schema lock on the view. When the lock is granted (and there are no active users of the view), SQL Server deletes all copies of the view from the procedure cache. Existing plans referencing the view are still in the cache, but will be automatically recompiled the next time they are invoked.

Updatable views can modify more than one table involved in the view. The DELETE, INSERT, and UPDATE statements can reference a view as long as SQL Server can translate the user’s update request unambiguously to updates in the base tables referenced in the view’s definition.

Permissions

ALTER VIEW permissions default to members of the db_owner and db_ddladmin fixed database roles, and to the view owner. These permissions are not transferable.

Examples
A. Alter a view

This example creates a view that contains all authors called All_authors. Permissions are granted to the view, but requirements are changed to select all authors who are from Utah. Then, ALTER VIEW is used to replace the view.

-- Create a view from the authors table that contains all authors.

CREATE VIEW All_authors (au_fname, au_lname, address, city, zip)

AS

SELECT au_fname, au_lname, address, city, zip

FROM pubs..authors

GO

-- Here, grant SELECT permissions on the view to public.

GRANT SELECT ON All_authors TO public

GO

-- The view needs to be changed to include all authors

-- from Utah.

-- If ALTER VIEW is not used but instead the view is dropped and

-- re-created, the above GRANT statement and any other statements

-- dealing with permissions that pertain to this view

-- must be redone.

ALTER VIEW All_authors (au_fname, au_lname, address, city, zip)

AS

SELECT au_fname, au_lname, address, city, zip

FROM pubs..authors

WHERE state = 'UT'

GO

B. Use @@ROWCOUNT function in a view

    This example uses the @@ROWCOUNT function as part of the view definition.

    USE pubs

    GO

    CREATE VIEW yourview

    AS

        SELECT title_id, title, mycount = @@ROWCOUNT, ytd_sales

        FROM titles

    GO

    SELECT *

    FROM yourview

    GO

    -- Here, the view is altered.

    USE pubs

    GO

    ALTER VIEW yourview

    AS

        SELECT title, mycount = @@ ROWCOUNT, ytd_sales

        FROM titles

        WHERE type = 'mod_cook'

    GO

    SELECT *

    FROM yourview

    GO

    See Also
    CREATE TABLE | DROP VIEW
CREATE VIEW | SELECT


AND

Combines two Boolean expressions and returns TRUE when both of the expressions are TRUE. When more than one logical operator is used in a statement, AND operators are evaluated first. You can change the order of evaluation by using parentheses.

Syntax

boolean_expression AND boolean_expression

Arguments
boolean_expression
Is any valid Microsoft® SQL Server™ expression that returns a Boolean value: TRUE, FALSE, or UNKNOWN.
Result Types

Boolean

Result Value

Returns TRUE when both of the expressions are TRUE.

Remarks

This chart outlines the outcomes when you compare TRUE and FALSE values using the AND operator.

 | TRUE | FALSE | UNKNOWN
TRUE | TRUE | FALSE | UNKNOWN
FALSE | FALSE | FALSE | FALSE
UNKNOWN | UNKNOWN | FALSE | UNKNOWN

See Also
Expressions | SELECT
Functions | WHERE
Operators (Logical Operators) |


ANY

Compares a scalar value with a single-column set of values. For more information, see SOME | ANY.


APP_NAME

Returns the application name for the current session if one has been set by the application.

Syntax

APP_NAME()

Return Types

nvarchar(128)

Examples

This example checks whether the client application that initiated this process is a SQL Server Query Analyzer session.

DECLARE @CurrentApp varchar(35)

SET @CurrentApp = APP_NAME()

IF @CurrentApp <> 'MS SQL Server Query Analyzer'

PRINT 'This process was not started by a SQL Server Query Analyzer query session.'

See Also

System Functions


ASCII

Returns the ASCII code value of the leftmost character of a character expression.

Syntax

ASCII(character_expression)

Arguments
character_expression
Is an expression of the type char or varchar.
Return Types

int

Examples

This example, which assumes an ASCII character set, returns the ASCII value and char character for each character in the string Du monde entier.

SET TEXTSIZE 0

SET NOCOUNT ON

-- Create the variables for the current position of the character string

-- and for the character string.

DECLARE @position int, @string char(15)

-- Initialize the variables.

SET @position = 1

SET @string = 'Du monde entier'

WHILE @position <= DATALENGTH(@string)

    BEGIN

    SELECT ASCII(SUBSTRING(@string, @position, 1)),

        CHAR(ASCII(SUBSTRING(@string, @position, 1)))

     SET @position = @position + 1

    END

SET NOCOUNT OFF

GO

Here is the result set:

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

68          D

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

117         u

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

32

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

109         m

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

111         o

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

110         n

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

100         d

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

101         e

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

32

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

101         e

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

110         n

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

116         t

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

105         i

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

101         e

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

114         r

See Also

String Functions


ASIN

Returns the angle in radians whose sine is the given float expression (also called arcsine).

Syntax

ASIN(float_expression)

Arguments
float_expression
Is an expression of the type float, with a value between -1 and 1. Values outside this range return NULL and report a domain error.
Return Types

float

Examples

This example takes a float expression and returns the ASIN of the given angle.

-- First value will be -1.01, which fails.

DECLARE @angle float

SET @angle = -1.01

SELECT 'The ASIN of the angle is: ' + CONVERT(varchar, ASIN(@angle))

GO

-- Next value is -1.00.

DECLARE @angle float

SET @angle = -1.00

SELECT 'The ASIN of the angle is: ' + CONVERT(varchar, ASIN(@angle))

GO

-- Next value is 0.1472738.

DECLARE @angle float

SET @angle = 0.1472738

SELECT 'The ASIN of the angle is: ' + CONVERT(varchar, ASIN(@angle))

GO

Here is the result set:

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

The ASIN of the angle is:

(1 row(s) affected)

Domain error occurred.

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

The ASIN of the angle is: -1.5708

(1 row(s) affected)

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

The ASIN of the angle is: 0.147811

(1 row(s) affected)

See Also
CEILING | SET ARITHIGNORE
SET ARITHABORT | Mathematical Functions


ATAN

Returns the angle in radians whose tangent is the given float expression (also called arctangent).

Syntax

ATAN(float_expression)

Arguments
float_expression
Is an expression of the type float.
Return Types

float

Examples

This example takes a float expression and returns the ATAN of the given angle.

SELECT 'The ATAN of -45.01 is: ' + CONVERT(varchar, ATAN(-45.01))

SELECT 'The ATAN of -181.01 is: ' + CONVERT(varchar, ATAN(-181.01))

SELECT 'The ATAN of 0 is: ' + CONVERT(varchar, ATAN(0))

SELECT 'The ATAN of 0.1472738 is: ' + CONVERT(varchar, ATAN(0.1472738))

SELECT 'The ATAN of 197.1099392 is: ' + CONVERT(varchar, ATAN(197.1099392))

GO

Here is the result set:

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

The ATAN of -45.01 is: -1.54858

(1 row(s) affected)

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

The ATAN of -181.01 is: -1.56527

(1 row(s) affected)

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

The ATAN of 0 is: 0

(1 row(s) affected)

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

The ATAN of 0.1472738 is: 0.146223

(1 row(s) affected)

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

The ATAN of 197.1099392 is: 1.56572

(1 row(s) affected)

See Also
CEILING Mathematical Functions


ATN2

Returns the angle in radians whose tangent is between the two given float expressions (also called arctangent).

Syntax

ATN2(float_expression, float_expression)

Arguments
float_expression
Is an expression of the float data type.
Return Types

float

Examples

This example calculates the ATN2 for the given angles.

DECLARE @angle1 float

DECLARE @angle2 float

SET @angle1 = 35.175643

SET @angle2 = 129.44

SELECT 'The ATN2 of the angle is: ' + CONVERT(varchar,ATN2(@angle1,@angle2 ))

GO

Here is the result set:

The ATN2 of the angle is: 0.265345

(1 row(s) affected)

See Also
CAST and CONVERT | money and smallmoney
CEILING | Mathematical Functions
float and real |


AVG

Returns the average of the values in a group. Null values are ignored.

Syntax

AVG([ALL | DISTINCT] expression)

Arguments
ALL
Applies the aggregate function to all values. ALL is the default.
DISTINCT
Specifies that AVG be performed only on each unique instance of a value, regardless of how many times the value occurs.
expression
Is an expression of the exact numeric or approximate numeric data type category, except for the bit data type. Aggregate functions and subqueries are not permitted.
Return Types

The return type is determined by the type of the evaluated result of expression.

Expression result | Return type
integer category | int
decimal category (p, s) | decimal(38, s) divided by decimal(10, 0)
money and smallmoney category | money
float and real category | float

Important Distinct aggregates, for example, AVG(DISTINCT column_name), COUNT(DISTINCT column_name), MAX(DISTINCT column_name), MIN(DISTINCT column_name), and SUM(DISTINCT column_name), are not supported when using CUBE or ROLLUP. If used, Microsoft® SQL Server™ returns an error message and cancels the query.

Examples
A. Use SUM and AVG functions for calculations

    This example calculates the average advance and the sum of year-to-date sales for all business books. Each of these aggregate functions produces a single summary value for all of the retrieved rows.

    USE pubs

    SELECT AVG(advance), SUM(ytd_sales)

    FROM titles

    WHERE type = 'business'

    Here is the result set:

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

    6,281.25                   30788

    (1 row(s) affected)

    B. Use SUM and AVG functions with a GROUP BY clause

      When used with a GROUP BY clause, each aggregate function produces a single value for each group, rather than for the whole table. This example produces summary values for each type of book that include the average advance for each type of book and the sum of year-to-date sales for each type of book.

      USE pubs

      SELECT type, AVG(advance), SUM(ytd_sales)

      FROM titles

      GROUP BY type

      ORDER BY type

      Here is the result set:

      type

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

      business     6,281.25                   30788

      mod_cook     7,500.00                   24278

      popular_comp 7,500.00                   12875

      psychology   4,255.00                   9939

      trad_cook    6,333.33                   19566

      UNDECIDED    NULL                       NULL

      (6 row(s) affected)

      C. Use AVG with DISTINCT

        This statement returns the average of the distinct prices of business books.

        USE pubs

        SELECT AVG(DISTINCT price)

        FROM titles

        WHERE type = 'business'

        Here is the result set:

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

        11.64

        (1 row(s) affected)

        D. Use AVG without DISTINCT

          Without DISTINCT, the AVG function finds the average price of all business titles in the titles table.

          USE pubs

          SELECT AVG(price)

          FROM titles

          WHERE type = 'business'

          Here is the result set:

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

          13.73

          (1 row(s) affected)

          See Also

          Aggregate Functions


BACKUP

Backs up an entire database, transaction log, or one or more files or filegroups.

Caution Backups created with Microsoft® SQL Server™ version 7.0 cannot be restored in earlier versions of SQL Server.

Syntax

Backing up an entire database:

BACKUP DATABASE {database_name | @database_name_var}
TO <backup_device> [,…n]
[WITH
[BLOCKSIZE = {blocksize | @blocksize_variable}]
[[,] DESCRIPTION = {text | @text_variable}]
[[,] DIFFERENTIAL]
[[,] EXPIREDATE = {date | @date_var}
| RETAINDAYS = {days | @days_var}]
[[,] FORMAT | NOFORMAT]
[[,] {INIT | NOINIT}]
[[,] MEDIADESCRIPTION = {text | @text_variable}]
[[,] MEDIANAME = {media_name | @media_name_variable}]
[[,] [NAME = {backup_set_name | @backup_set_name_var}]
[[,] {NOSKIP | SKIP}]
[[,] {NOUNLOAD | UNLOAD}]
[[,] [RESTART]
[[,] STATS [= percentage]]
]

Backing up specific files or filegroups:

BACKUP DATABASE {database_name | @database_name_var}
<file_or_filegroup> [,…n]
TO <backup_device> [,…n]
[WITH
[BLOCKSIZE = {blocksize | @blocksize_variable}]
[[,] DESCRIPTION = {text | @text_variable}]
[[,] EXPIREDATE = {date | @date_var}
| RETAINDAYS = {days | @days_var}]
[[,] FORMAT | NOFORMAT]
[[,] {INIT | NOINIT}]
[[,] MEDIADESCRIPTION = {text | @text_variable}]
[[,] MEDIANAME = {media_name | @media_name_variable}]
[[,] [NAME = {backup_set_name | @backup_set_name_var}]
[[,] {NOSKIP | SKIP}]
[[,] {NOUNLOAD | UNLOAD}]
[[,] [RESTART]
[[,] STATS [= percentage]]
]

Backing up a transaction log:

BACKUP LOG {database_name | @database_name_var}
{
[WITH
{ NO_LOG | TRUNCATE_ONLY }]
}
|
{
TO <backup_device> [,…n]
[WITH
[BLOCKSIZE = {blocksize | @blocksize_variable}]
[[,] DESCRIPTION = {text | @text_variable}]
[[,] EXPIREDATE = {date | @date_var}
| RETAINDAYS = {days | @days_var}]
[[,] FORMAT | NOFORMAT]
[[,] {INIT | NOINIT}]
[[,] MEDIADESCRIPTION = {text | @text_variable}]
[[,] MEDIANAME = {media_name | @media_name_variable}]
[[,] [NAME = {backup_set_name | @backup_set_name_var}]
[[,] NO_TRUNCATE]
[[,] {NOSKIP | SKIP}]
[[,] {NOUNLOAD | UNLOAD}]
[[,] [RESTART]
[[,] STATS [= percentage]]
]
}

<backup_device> ::=
{
{backup_device_name | @backup_device_name_var}
|
{DISK | TAPE | PIPE} =
{'temp_backup_device' | @temp_backup_device_var}
}

<file_or_filegroup> ::=
{
FILE = {logical_file_name | @logical_file_name_var}
|
FILEGROUP = {logical_filegroup_name | @logical_filegroup_name_var}
 }

Arguments
DATABASE
Specifies the complete backup of the database. If a list of files and filegroups is specified, only those files and filegroups are backed up.

Note During a full database or differential backup, SQL Server backs up enough of the transaction log to produce a consistent database for when the database is restored. Only a full database backup can be performed on the master database.

{database_name | @database_name_var}
Is the database from which the transaction log, partial database, or complete database is being backed up. If supplied as a variable (@database_name_var), this name can be specified either as a string constant (@database_name_var = database name) or as a variable of character string data type, except for the ntext or text data types.
<backup_device>
Specifies the permanent or temporary backup device to use for the backup operation. Can be one or more of the following:
{backup_device_name} | {@backup_device_name_var}
Is the logical name, which must follow the rules for identifiers, of the backup device(s) (created by sp_addumpdevice) to which the database is backed up. If supplied as a variable (@backup_device_name_var), the backup device name can be specified either as a string constant (@backup_device_name_var = backup device name) or as a variable of character string data type, except for the ntext or text data types.
{ DISK | TAPE | PIPE } =
'temp_backup_device' | @temp_backup_device_var

Allows backups to be created on the named disk, tape, or pipe device. When using a temporary disk backup device, the temporary disk backup devices must not exist prior to specifying the BACKUP statement. When using a tape backup device, specify WITH FORMAT to ensure that the backup device is a valid Microsoft Tape Format (MTF) data set.

Important Use FORMAT carefully because it overwrites all contents on the current tape.

With disk and tape, specify the complete path and file name. For example, DISK = ‘C:\Mssql7\Backup\Mybackup.dat’ or TAPE = \\.\TAPE0. With pipe, specify the name of the named pipe that will be used by the client application. If supplied as a variable (@temp_backup_name_var), the temporary backup device name can be specified as a string constant or as a variable of character string data type, except for the ntext or text data types.

Pipe files have been added to allow third-party vendors a flexible and powerful way to connect their own software. For typical Transact-SQL use, pipe files are not used.

Note When performing a backup to a named pipe, you may need to adjust the number of minutes that SQL Server waits for the client to connect before reporting a failure. To adjust this time-out interval from the default of 2 minutes, create the BackupNamedPipeConnectTimeout registry key and add the following registry value:

HKEY_LOCAL_MACHINE
\SOFTWARE
\Microsoft
\MSSQLServer

Data Type: REG_DWORD
Data: Value other than the default of 2
Radix: Decimal

If you are using a network server with a UNC name or using a redirected drive letter, specify a device type of disk.

Important When specifying multiple files, logical file names (or variables) and temporary file names (or variables) can be mixed. However, all devices must be of the same type (disk, tape, or pipe).

n
Is a placeholder indicating that multiple backup devices may be specified. The maximum number of backup devices is 32.
BLOCKSIZE = {blocksize | @blocksize_variable}
Specifies the physical block size, in bytes.

For DISK, BACKUP automatically determines the appropriate block size for disk devices.

Note If you intend to transfer the resulting backup set to a CD-ROM and then restore from that CD-ROM, you must set BLOCKSIZE to 2048.

For tape media, BLOCKSIZE only applies if the tape is being overwritten by using FORMAT. When using tape media, the backup operation selects an appropriate block size. Explicitly stating a block size overrides the backup operation’s selection of a block size.

For PIPE, the backup operation uses 65,536 unless BLOCKSIZE is specified.

DESCRIPTION = {text | @text_variable}
Specifies the free-form text describing the backup set. Can be a maximum of 255 characters.
DIFFERENTIAL
Specifies the database backup should consist only of the portions of the database that have changed since the last full backup. A differential database backup usually takes up less space than a full database. Use this option so that all individual log backups since the last full database backup do not need to be applied.

The DIFFERENTIAL option is specified for full database backups only.

Note During a full database or differential backup, SQL Server backs up enough of the transaction log to produce a consistent database when the database is restored.

EXPIREDATE = {date | @date_var}
Specifies the date when the backup set expires and can be overwritten. If supplied as a variable (@date_var), this date can be specified as either a string constant (@date_var = date), as a variable of character string data type (except for the ntext or text data types), a smalldatetime, or datetime variable, and it must follow the configured datetime format for the system. This option is used for disk and tape devices only and is effective only when specified with all backup sets on the media.
RETAINDAYS = {days | @days_var}
Specifies the number of days that must elapse before this backup media set can be overwritten. If supplied as a variable (@days_var), it must be specified as an integer. This option is used for disk and tape devices only and is effective only when specified with INIT. Specifying SKIP overrides this option.

Important If EXPIREDATE or RETAINDAYS is not specified, expiration is determined by the media retention configuration setting of sp_configure. These options only prevent SQL Server from overwriting a file. Tapes can still be erased using other methods, and disk files can still be deleted through the operating system.

FORMAT

Specifies that the media header should be written on all volumes used for this backup operation and rewrites the backup device. Any existing media header is overwritten. The FORMAT option also invalidates the entire media contents, ignoring any existing password.

Important Use FORMAT carefully. Initializing one backup device or medium renders the entire backup set it contains unusable. For example, if a single tape belonging to an existing striped backup set is initialized, the entire backup set is rendered useless.

By specifying FORMAT, the backup operation implies SKIP and INIT; these do not need to be explicitly stated.

NOFORMAT
Specifies the media header should not be written on all volumes used for this backup operation and does not rewrite the backup device unless INIT is specified.
INIT
Specifies the backup set should be the first file on the disk or tape device and preserves the media header. If INIT is specified, any existing data on that device is overwritten.

The backup media is not overwritten if either of the following conditions is met:

  • All backup sets on the media have not yet expired. For more information, see the EXPIREDATE and RETAINDAYS options.
  • The backup set name given in the BACKUP statement, if provided, does not match the name on the backup media. For more information, see the NAME clause.

Use the SKIP clause to override these checks. For more information about interactions when using SKIP, NOSKIP, INIT, and NOINIT, see the Remarks section.

Note If the backup media is password-protected or encrypted, SQL Server does not write to the media. To overwrite media that is either password-protected or encrypted, specify the WITH FORMAT option.

NOINIT
Specifies the backup set is appended to the current disk or tape device. NOINIT is the default.
MEDIADESCRIPTION = {text | @text_variable}
Specifies the free-form text description, maximum of 255 characters, of the media set.
MEDIANAME = {media_name | @media_name_variable}
Specifies the media name, a maximum of 128 characters, for the entire backup media set. If MEDIANAME is specified, it must match the previously specified media name already existing on the backup volume(s). If not specified or if the SKIP option is specified, there is no verification check of the media name.

Note If FORMAT is specified, MEDIANAME specifies the media name that is written. In addition, tapes shared between SQL Server database backups and Microsoft Windows NT® backups must have a nonnull MEDIANAME.

NAME = {backup_set_name | @backup_set_var}
Specifies the name of the backup set. Names are limited to 128 characters. If NAME is not specified, it is blank.
NOSKIP
Instructs the BACKUP statement to check the expiration date and name of all backup sets on the media before allowing them to be overwritten.
SKIP
Disables the backup set expiration and name checking, which is usually performed by the BACKUP statement to prevent overwrites of backup sets. For more information, see the Remarks section.
NOUNLOAD
Specifies the tape is not unloaded automatically from the tape drive after a backup. NOUNLOAD remains set until UNLOAD is specified. This option is used only for tape devices.
UNLOAD
Specifies that the tape is automatically rewound and unloaded when the backup is finished. UNLOAD is set by default when a new user session is started. It remains set until that user specifies NOUNLOAD. This option is used only for tape devices.
RESTART
Specifies that SQL Server restarts the backup operation that was interrupted. The RESTART option saves time because it restarts the backup operation at the point it was interrupted. To RESTART a specific backup operation that was interrupted, repeat the entire BACKUP statement and add the RESTART option. Using the RESTART option is not required, but can save time.

Important This option can only be used for backups directed to tape media and for backups that span multiple tape volumes. A restart operation never occurs on the first volume of the backup.

STATS [ = percentage]
Displays a message every time another percentage completes, and is used to gauge progress. If percentage is omitted, SQL Server displays a message after every 10 percent completed.
<file_or_filegroup>
Specifies the logical names of the files or filegroups to include in the database backup. Multiple files or filegroups may be specified.
FILE = {logical_file_name | @logical_file_name_var}
Names one or more files to include in the database backup.
FILEGROUP = {logical_filegroup_name | @logical_filegroup_name_var}
Names one or more filegroups to include in the database backup.

Note Back up a file when the database size and performance requirements make a full database backup impractical. To back up the transaction log separately, use BACKUP LOG.

Important To recover a database using file and filegroup backups, a separate backup of the transaction log must be provided by using BACKUP LOG.

File and filegroup backups are disallowed if trunc. log on chkpt. is enabled for the database. If trunc. log on chkpt. is enabled, the log has been truncated and the log backups required to restore individual files and filegroups are not available.

The BACKUP statement requires that entire filegroups affected by a CREATE INDEX statement since the last filegroup backup be backed up as a unit:

  • If an index is created on a filegroup, that entire filegroup must be backed up in a single backup operation. Backups of individual files that are part of the affected filegroup are not allowed.
  • If an index is created on a filegroup different from the one that the table resides in, then both filegroups (the filegroup containing the table and the filegroup containing the newly created index) must be backed up. If more than one index is created on a filegroup different from the filegroup in which the table resides, all filegroups must immediately be backed up to accommodate these differing filegroups.

    The BACKUP statement detects all of these filegroup situations and communicates to the backup user the minimum filegroups that must be backed up.

n
Is a placeholder indicating that multiple files and filegroups may be specified. There is no maximum number of files or filegroups.
LOG
Specifies a backup of the transaction log only. The log is backed up from the last successfully executed LOG backup to the current end of the log. By default, SQL Server truncates the log up to the beginning of the active portion of the log, which contains the oldest open transaction.

Note If backing up the log does not appear to truncate most of the log, you may have a very old open transaction in the log. Log space can be monitored with DBCC SQLPERF (LOGSPACE).

NO_LOG | TRUNCATE_ONLY
Removes the inactive part of the log without making a backup copy of it and truncates the log. This option frees space. Specifying a backup device is unnecessary because the log backup is not saved.

After backing up the log using either NO_LOG or TRUNCATE_ONLY, the changes recorded in the log are not recoverable. For recovery purposes, immediately execute BACKUP DATABASE.

If the log of a published (replicated) database becomes full and absolutely must be truncated, unsubscribe all subscriptions to the publications of that database. This allows you to truncate all distributed transactions.

NO_TRUNCATE
Backs up the log without truncating it. This option also backs up the log if the database becomes damaged or if the database is marked suspect or has not been recovered.
Remarks

Database or log backups can be appended to any disk or tape device, allowing you to keep a database and its transaction logs all within one physical location.

SQL Server uses online backup to allow a database backup while the database is still in use. However, here are some operations that are not allowed during a database or transaction log backup:

  • File management operations such as the ALTER DATABASE statement with either the ADD FILE or REMOVE FILE options; INSERT, UPDATE, or DELETE statements are allowed during a backup operation.
  • Shrink database or shrink file. This includes autoshrink operations.
  • CREATE INDEX. This restriction applies to database backup, not log backup.
  • Nonlogged operations such as bulk load, SELECT INTO, WRITETEXT, and UPDATETEXT. The database option select into/bulkcopy must be enabled for these operations to be nonlogged.

If a backup is started when one of these operations is in progress, the backup ends. If a backup is running and one of these operations is attempted, the operation fails.

Cross-platform backups, even between different processor types, can be performed, providing the following sort order and character set restrictions are met:

  • Usually, the sort order and character set of two servers must match for you to back up on one server and restore on the other. The exception to the sort order and character set matching between two servers is if both servers use a binary sort order. Then, the character sets can differ.
  • It is possible to perform a backup on a server with a binary sort order and restore the back up onto a different server with a binary sort order. If the character sets are the same, all characters are interpreted identically between the two servers. If the character sets are different, however, any extended characters are interpreted differently on the two servers. Even though the stored binary value is the same, extended characters are interpreted differently depending on the installed character set. For example, the character A (ASCII value of 65) is interpreted the same for all character sets. If the character stored is ÷ (ASCII value of 246) on the first server with a character set of code page 437 (U.S. English), the second server with a character set of code page ISO 8859-1 (Latin 1 or ANSI), interprets the ÷ character as the ö character (ASCII value still 246).
Backup File Format

SQL Server backups can coexist on tape media with Windows NT backups because the SQL Server version 7.0 backup format conforms to Microsoft Tape Format (MTF), which is the same format used by Windows NT tape backups.

Backup Types

Here are the types of backups SQL Server supports:

  • Full database backup, which backs up the entire database including the transaction log.
  • Differential database backup, which is performed between full database backups.
  • Transaction log backup.

Use BACKUP LOG when changes made since either the last differential database backup or last full database backup are important to maintain.

  • File(s) and Filegroup(s) backup.

Backup devices used in a stripe set must always be used in a stripe set (unless reinitialized at some point with FORMAT) with the same number of devices. After a backup device is defined as part of a stripe set, it cannot be used for a single file backup unless FORMAT is specified. Similarly, a backup device that contains nonstriped backups cannot be used in a stripe set unless FORMAT is specified. Use FORMAT to split a striped backup set. If neither MEDIANAME nor MEDIADESCRIPTION is specified with FORMAT, the media header field corresponding to the blank item is empty.

Use BACKUP to back up database files and filegroups instead of the full database when time constraints make a full database backup impractical. If you choose to back up a file instead of the full database, put procedures in place to assure that all files in the database are backed up regularly. Also, separate transaction log backups must be performed. After restoring a file backup, apply the transaction log to roll the contents of the file forward to make it consistent with the rest of the database.

SQL Server must be able to read and write the device. Therefore, ownership and permission problems on the backup device’s physical file can interfere with a backup operation. sp_addumpdevice, which adds an entry for a device in the system tables, does not check file access permission. In fact, the physical resource is not accessed until a backup or restore in attempted. Any backup sets with passwords will not be able to be accessed.

You cannot execute the BACKUP LOG statement while the trunc. log on chkpt. database option is enabled, nor can you execute it after enabling select into/bulkcopy and making unlogged changes to the database with SELECT INTO, UPDATETEXT, WRITETEXT, or a bulk-copy operation. Use BACKUP DATABASE instead.

When a RESTORE is performed, the backup history tables are modified.

Caution VOLUME is not an available option in SQL Server version 7.0. If VOLUME is specified, SQL Server returns an error message and halts the operation.

Interaction of SKIP, NOSKIP, INIT, and NOINIT

This table shows how the {INIT | NOINIT} and {NOSKIP | SKIP} clauses interact.

 | INIT | NOINIT
SKIP | If the volume contains a valid** media header, verify the media password* and overwrite any backup sets on the media, preserving only the media header. If the tape media is empty or the disk media is nonexistent, write a media header and proceed. If the media is not empty, however, give feedback that this is not valid MTF media and abort the backup. | If the volume contains a valid media header, verify the media password* and append the backup set, preserving all existing backup sets. If the volume does not contain a valid media header, an error occurs. If the tape media is empty or the disk media is nonexistent, write a media header and proceed. If the media is not empty, however, give feedback that this is not valid MTF media and cancel the backup.
NOSKIP | If the volume contains a valid media header, perform the following checks: Verify the media password***. If MEDIANAME was specified, verify that the given media name matches the media header’s media name. Verify that there are no unexpired backup set(s) already on the media. If there are, abort the backup. If these checks pass, overwrite any backup sets on the media, preserving only the media header. If the tape media is empty or the disk media is nonexistent, write a media header and proceed. If the media is not empty, however, give feedback that this is not valid MTF media and cancel the backup. | If the volume contains a valid media header, verify the media password* and verify that the media name matches the given MEDIANAME, if any. If it matches, append the backup set, preserving all existing backup sets. If the volume does not contain a valid media header, an error occurs.
* This capability is not supported by SQL Server version 7.0. ** Validity includes the MTF version number and other header information. If the version specified is unsupported or an unexpected value, an error occurs.
*** The presence of a media password prevents the backup operation. To override the backup operation, specify FORMAT.

Important To maintain backward compatibility, the DUMP keyword can be used in place of the BACKUP keyword in the BACKUP statement syntax. In addition, the TRANSACTION keyword can be used in place of the LOG keyword.

Backup History Tables

SQL Server includes these backup history tables that track backup activity :

  • backupfile
  • backupmediafamily
  • backupmediaset
  • backupset
Permissions

BACKUP DATABASE and BACKUP LOG permissions default to members of the db_owner fixed database role, who can transfer permissions to other users, and to members of the db_backupoperator fixed database role.

Examples
  1. Back up the entire MyNwind database

Note The MyNwind database is shown for illustration only.

This example creates a backup device called MyNwind_1 that contains the full database backup of the MyNwind database.

-- Create the backup device for the full MyNwind backup.

USE master

EXEC sp_addumpdevice 'disk', 'MyNwind_1',     'c:\mssql7\backup\MyNwind_1.dat'

-- Back up the full MyNwind database.

BACKUP DATABASE MyNwind TO MyNwind_1

B.Back up the entire database and log

This example creates both a full database and log backup. The database is backed up to a backup device called MyNwind_2, and then the log is backed up to a file called MyNwindLog1.

-- Create the backup device for the full MyNwind backup.

USE master

EXEC sp_addumpdevice 'disk', 'MyNwind_2',     'c:\mssql7\backup\MyNwind_2.dat'

-- Back up the full MyNwind database.

BACKUP DATABASE MyNwind TO MyNwind_2

-- Create the log backup device.

USE master

EXEC sp_addumpdevice 'disk', 'MyNwindLog1',

    'c:\mssql7\backup\MyNwindLog1.dat'

-- Update activity has occurred before this point.

-- Back up the log of the MyNwind database.

BACKUP LOG MyNwind

    TO MyNwindLog1

See Also
DBCC SQLPERF | sp_addumpdevice
RESTORE FILELISTONLY | sp_configure
RESTORE HEADERONLY | sp_dboption
RESTORE LABELONLY | sp_helpfile
RESTORE VERIFYONLY | sp_helpfilegroup


BEGIN…END

Encloses a series of Transact-SQL statements so that a group of Transact-SQL statements can be executed. BEGIN and END are control of flow language keywords.

Syntax

BEGIN
{
sql_statement
| statement_block
 }
END

Argument
{sql_statement | statement_block}
Is any valid Transact-SQL statement or statement grouping as defined with a statement block.
Remarks

BEGIN…END blocks can be nested.

Although all Transact-SQL statements are valid within a BEGIN…END block, certain Transact-SQL statements should not be grouped together within the same batch (statement block).

Examples

In this example, BEGIN and END define a series of Transact-SQL statements that are to be executed together. If the BEGIN…END block were not included, the IF condition would cause only the ROLLBACK TRANSACTION to execute, and the print message would not be returned.

USE pubs

GO

CREATE TRIGGER deltitle

ON titles

FOR delete

AS

IF     (SELECT COUNT(*) FROM deleted, sales

        WHERE sales.title_id = deleted.title_id) > 0

    BEGIN

        ROLLBACK TRANSACTION

        PRINT 'You can''t delete a title with sales.'

    END

See Also
ALTER TRIGGER | CREATE TRIGGER
Control-of-Flow Language | END (BEGIN…END)


BEGIN DISTRIBUTED TRANSACTION

Specifies the start of a Transact-SQL distributed transaction managed by Microsoft Distributed Transaction Coordinator (MS DTC).

Syntax

BEGIN DISTRIBUTED TRAN[SACTION]
[transaction_name | @tran_name_variable]

Arguments
transaction_name
Is a user-defined transaction name used to track the distributed transaction within MS DTC utilities. transaction_name must conform to the rules for identifiers, but only the first 32 characters are used.
@tran_name_variable
Is the name of a user-defined variable containing a transaction name used to track the distributed transaction within MS DTC utilities. The variable must be declared with a char, varchar, nchar, or nvarchar data type.
Remarks

The server executing the BEGIN DISTRIBUTED TRANSACTION statement is the transaction originator and controls the completion of the transaction. When a subsequent COMMIT TRANSACTION or ROLLBACK TRANSACTION statement is issued for the connection, the controlling server requests that MS DTC manage the completion of the distributed transaction across the servers involved.

There are two ways remote SQL servers are enlisted in a distributed transaction:

  • A connection already enlisted in the distributed transaction makes a remote stored procedure call referencing a remote server.
  • A connection already enlisted in the distributed transaction executes a distributed query referencing a remote server.

For example, if BEGIN DISTRIBUTED TRANSACTION is issued on ServerA, the connection calls a stored procedure on ServerB and another stored procedure on ServerC, and the stored procedure on ServerC executes a distributed query against ServerD, then all four SQL servers are involved in the distributed transaction. ServerA is the originating, controlling server for the transaction.

The connections involved in Transact-SQL distributed transactions do not get a transaction object they can pass to another connection for it to explicitly enlist in the distributed transaction. The only way for a remote server to enlist in the transaction is to be the target of a remote stored procedure call or a distributed query.

The sp_configure remote proc trans option controls whether calls to remote stored procedures in a local transaction automatically cause the local transaction to be promoted to a distributed transaction managed by MS DTC. The connection-level SET option REMOTE_PROC_TRANSACTIONS can be used to override the server default established by sp_configure remote proc trans. With this option set on, a remote stored procedure call causes a local transaction to be promoted to a distributed transaction. The connection that creates the MS DTC transaction becomes the originator for the transaction. COMMIT TRANSACTION initiates an MS DTC coordinated commit. If the sp_configure remote proc trans option is set on, remote stored procedure calls in local transactions are automatically protected as part of distributed transactions without having to rewrite applications to specifically issue BEGIN DISTRIBUTED TRANSACTION instead of BEGIN TRANSACTION.

When a distributed query is executed in a local transaction, the transaction is automatically promoted to a distributed transaction if the target OLE DB data source supports ITransactionLocal. If the target OLE DB data source does not support ITransactionLocal, only read-only operations are allowed in the distributed query.

For more information about the distributed transaction environment and process, see your Microsoft Distributed Transaction Coordinator documentation.

Permissions

BEGIN DISTRIBUTED TRANSACTION permissions default to any valid user.

Examples

This example updates the author’s last name on the local and remote databases. The local and remote databases will both either commit or roll back the transaction.

Note Unless MS DTC is currently installed on the computer running Microsoft® SQL Server™, this example produces an error message. For more information about installing MS DTC, see your Microsoft Distributed Transaction Coordinator documentation.

USE pubs

GO

BEGIN DISTRIBUTED TRANSACTION
UPDATE authors
    SET au_lname = 'McDonald' WHERE au_id = '409-56-7008'
EXECUTE remote.pubs.dbo.changeauth_lname '409-56-7008','McDonald'
COMMIT TRAN

GO

See Also
BEGIN TRANSACTION | SAVE TRANSACTION
COMMIT TRANSACTION | COMMIT WORK
ROLLBACK TRANSACTION | ROLLBACK WORK


BEGIN TRANSACTION

Marks the starting point of an explicit, local transaction. BEGIN TRANSACTION increments @@TRANCOUNT by 1.

Syntax

BEGIN TRAN[SACTION] [transaction_name | @tran_name_variable]

Arguments
transaction_name
Is the name assigned to the transaction. transaction_name must conform to the rules for identifiers, but only the first 32 characters of the transaction name are used. Use transaction names only on the outermost pair of nested BEGIN…COMMIT or BEGIN…ROLLBACK statements.
@tran_name_variable
Is the name of a user-defined variable containing a valid transaction name. The variable must be declared with a char, varchar, nchar, or nvarchar data type.
Remarks

BEGIN TRANSACTION represents a point at which the data referenced by a connection is known to be logically and physically consistent. If errors are encountered, all data modifications made after the BEGIN TRANSACTION can be rolled back to return the data to this known state of consistency. Each transaction lasts until either it completes without errors and COMMIT TRANSACTION is issued to make the modifications a permanent part of the database, or errors are encountered and all modifications are erased with a ROLLBACK TRANSACTION statement.

BEGIN TRANSACTION starts a local transaction for the connection issuing the statement. Depending on the current transaction isolation level settings, many resources acquired to support the Transact-SQL statements issued by the connection are locked by the transaction until it is completed with either a COMMIT TRANSACTION or ROLLBACK TRANSACTION statement. Transactions left outstanding for long periods of time can prevent other users from accessing these locked resources.

Although BEGIN TRANSACTION starts a local transaction, it is not recorded in the transaction log until the application subsequently performs an action that must be recorded in the log, such as executing an INSERT, UPDATE, or DELETE statement. An application can perform actions such as acquiring locks to protect the transaction isolation level of SELECT statements, but nothing is recorded in the log until the application performs an action that must be recorded in the log.

Naming multiple transactions in a series of nested transactions with a transaction name has little effect on the transaction. Only the first (outermost) transaction name is registered with the system. A rollback to any other name (other than a valid savepoint name) generates an error. None of the statements executed before the rollback are in fact rolled back at the time this error occurs. The statements are rolled back only when the outer transaction is rolled back.

BEGIN TRANSACTION starts a local transaction. The local transaction is escalated to a distributed transaction if the following actions are performed before it is committed or rolled back:

  • An INSERT, DELETE, or UPDATE statement is executed that references a remote table on a linked server. The INSERT, UPDATE or DELETE statement fails if the OLE DB provider used to access the linked server does not support the ITransactionJoin interface.
  • A call is made to a remote stored procedure when the REMOTE_PROC_TRANSACTIONS option is set to ON.

The local copy of SQL Server becomes the transaction controller and uses MS DTC to manage the distributed transaction.

Permissions

BEGIN TRANSACTION permissions default to any valid user.

Example

This example increases the royalties paid for all popular computer books by 10 percent.

DECLARE @TranName VARCHAR(20)

SELECT @TranName = 'MyTransaction'

BEGIN TRANSACTION @TranName

GO

USE pubs

GO

UPDATE roysched

SET royalty = royalty * 1.10

WHERE title_id LIKE 'Pc%'

GO

COMMIT TRANSACTION MyTransaction

GO

See Also
BEGIN DISTRIBUTED TRANSACTION | SAVE TRANSACTION
COMMIT TRANSACTION | COMMIT WORK
ROLLBACK TRANSACTION | ROLLBACK WORK


BETWEEN

Specifies an inclusive range to test.

Syntax

test_expression [NOT] BETWEEN begin_expression AND end_expression

Arguments
test_expression
Is the expression to test for in the range as defined by begin_expression and end_expression. test_expression must be the same data type as both begin_expression and end_expression.
NOT
Specifies that the result of the predicate be negated.
begin_expression
Is any valid Microsoft® SQL Server™ expression. begin_expression must be the same data type as both test_expression and end_expression.
end_expression
Is any valid SQL Server expression. end_expression must be the same data type as both test_expression and begin_expression.
AND
Acts as a placeholder indicating that test_expression should be within the range indicated by begin_expression and end_expression.
Result Types

Boolean

Result Value

BETWEEN returns TRUE if the value of test_expression is greater than or equal to the value of begin_expression and less than or equal to the value of end_expression.

NOT BETWEEN returns TRUE if the value of test_expression is less than the value of begin_expression or greater than the value of end_expression.

Remarks

To specify an exclusive range, use the greater-than and less-than operators (> and <). If any input to the BETWEEN or NOT BETWEEN predicate is NULL, the result is UNKNOWN.

Examples
A. Use BETWEEN

This example returns all books with year-to-date sales between and including 4,095 through 12,000. Notice that books with sales of 4,095 are included in the results. If there were any books with sales of 12,000, they would also be included.

USE pubs

GO

SELECT title_id, ytd_sales

FROM titles

WHERE ytd_sales BETWEEN 4095 AND 12000

GO

Here is the result set:

title_id ytd_sales

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

BU1032   4095

BU7832   4095

PC1035   8780

PC8888   4095

TC7777   4095

(5 row(s) affected)

B. Use > and < instead of BETWEEN

This example, which uses > and < operators, returns different results because these operators are not inclusive.

USE pubs

GO

SELECT title_id, ytd_sales

FROM titles

WHERE ytd_sales > 4095 AND ytd_sales < 12000

GO

Here is the result set:

title_id ytd_sales

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

PC1035   8780

(1 row(s) affected)

C. Use NOT BETWEEN

This example finds all rows outside a specified range (4,095 through 12,000).

USE pubs

GO

SELECT title_id, ytd_sales

FROM titles

WHERE ytd_sales NOT BETWEEN 4095 AND 12000

GO

Here is the result set:

title_id ytd_sales

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

BU1111   3876

BU2075   18722

MC2222   2032

MC3021   22246

PS1372   375

PS2091   2045

PS2106   111

PS3333   4072

PS7777   3336

TC3218   375

TC4203   15096

(11 row(s) affected)

See Also
< (Less Than) | Operators (Logical Operators)
> (Greater Than) | SELECT (Subqueries)
Expressions | WHERE
Functions |


binary and varbinary

Binary data types that are either fixed-length (binary) or variable-length (varbinary).

binary[(n)]
Fixed-length binary data of n bytes. n must be a value from 1 through 8,000. Storage size is n+4 bytes.
varbinary[(n)]
Variable-length binary data of n bytes. n must be a value from 1 through 8,000. Storage size is the actual length of the data entered + 4 bytes, not n bytes. The data entered can be 0 bytes in length. The SQL-92 synonym for varbinary is binary varying.
Remarks

When n is not specified in a data definition or variable declaration statement, the default length is 1. When n is not specified with the CAST function, the default length is 30.

Use binary when the data entries in a column are expected to be consistently close to the same size.

Use varbinary when the data entries in a column are expected to vary considerably in size.

See Also
ALTER TABLE | DELETE
CAST and CONVERT | INSERT
CREATE TABLE | SET @local_variable
Data Types | UPDATE
DECLARE @local_variable |


bit

Integer data type that can be 1, 0, or NULL.

Remarks

Columns of type bit cannot have indexes on them.

Microsoft® SQL Server™ optimizes the storage used for bit columns. If there are 8 or fewer bit columns in a table, the columns are stored as 1 byte. If there are from 9 to 16 bit columns, they are stored as 2 bytes, and so on.

See Also
ALTER TABLE | DELETE
CAST and CONVERT | INSERT
CREATE TABLE | SET @local_variable
Data Types | UPDATE
DECLARE @local_variable | syscolumns


BREAK

Exits the innermost WHILE loop. Any statements following the END keyword are ignored. BREAK is often, but not always, activated by an IF test.

See Also
Control-of-Flow Language WHILE


BULK INSERT

Copies a data file into a database table or view in a user-specified format.

Syntax
BULK INSERT [['database_name'.]['owner'].]{'table_name' FROM data_file}
[WITH
(
[ BATCHSIZE [= batch_size]]
[[,] CHECK_CONSTRAINTS]
[[,] CODEPAGE [= 'ACP' | 'OEM' | 'RAW' | 'code_page']]
[[,] DATAFILETYPE [=
{'char' | 'native'| 'widechar' | 'widenative'}]]
[[,] FIELDTERMINATOR [= 'field_terminator']]
[[,] FIRSTROW [= first_row]]
[[,] FORMATFILE [= 'format_file_path']]
[[,] KEEPIDENTITY]
[[,] KEEPNULLS]
[[,] KILOBYTES_PER_BATCH [= kilobytes_per_batch]]
[[,] LASTROW [= last_row]]
[[,] MAXERRORS [= max_errors]]
[[,] ORDER ({column [ASC | DESC]} [,…n])]
[[,] ROWS_PER_BATCH [= rows_per_batch]]
[[,] ROWTERMINATOR [= 'row_terminator']]
[[,] TABLOCK]
)
]
Arguments
'database_name'
Is the name of the database in which the specified table or view resides. If not specified, this is the current database.
'owner'
Is the name of the table or view owner. owner is optional if the user performing the bulk copy operation owns the specified table or view. If owner is not specified and the user performing the bulk copy operation does not own the specified table or view, Microsoft® SQL Server™ returns an error message, and the bulk copy operation is canceled.
'table_name'
Is the name of the table or view to bulk copy data into. Only views in which all columns refer to the same base table can be used. For more information on the restrictions for copying data into views, see INSERT.
data_file
Is the full path of the data file that contains the data to be copied into the specified table or view. BULK INSERT can copy data from a disk (including network, floppy disk, hard disk, and so on).

data_file must specify a valid path from the server on which SQL Server is running. If data_file is a remote file, specify the UNC name.

BATCHSIZE [= batch_size]
Specifies the number of rows in a batch. Each batch is copied to the server as one transaction. SQL Server commits or rolls back, in the case of failure, the transaction for every batch. By default, all data in the specified data file is one batch.
CHECK_CONSTRAINTS
Specifies that any constraints on table_name are checked during the bulk copy operation. By default, constraints are ignored.
CODEPAGE [= 'ACP' | 'OEM' | 'RAW' | 'code_page']
Specifies the code page of the data in the data file. CODEPAGE is relevant only if the data contains char, varchar, or text columns with character values greater than 127 or less than 32.

CODEPAGE value | Description
ACP | Columns of char, varchar, or text data type are converted from the ANSI/Microsoft Windows® code page (ISO 1252) to the SQL Server code page.
OEM (default) | Columns of char, varchar, or text data type are converted from the system OEM code page to the SQL Server code page.
RAW | No conversion from one code page to another occurs; this is the fastest option.
code_page Specific code page number, for example, 850.

DATAFILETYPE [ = {'char' | 'native' | 'widechar' | 'widenative'}]
Specifies that BULK INSERT performs the copy operation using the specified default.

DATAFILETYPE value | Description
char (default) | Performs the bulk copy operation from a data file containing character data.
native | Performs the bulk copy operation using the native (database) data types of the data. The data file to be loaded was created by bulk copying data from SQL Server using the bcp utility.
widechar | Performs the bulk copy operation from a data file containing Unicode characters.
widenative | Performs the same bulk copy operation as native, except char, varchar, and text columns are stored as Unicode in the data file. The data file to be loaded was created by bulk copying data from SQL Server using the bcp utility. This option offers a higher performance alternative to the widechar option, and is intended for transferring data from one computer running SQL Server to another by using a data file. Use this option when you are transferring data that contains ANSI extended characters and you want to take advantage of the performance of native mode.

FIELDTERMINATOR [= 'field_terminator']
Specifies the field terminator to be used for char and widechar data files. The default is \t (tab character).
FIRSTROW [= first_row]
Specifies the number of the first row to copy. The default is 1, indicating the first row in the specified data file.
FORMATFILE [= 'format_file_path']
Specifies the full path of a format file. A format file describes the contents of the data file that contains stored responses created using the bcp utility on the same table or view. The format file should be used in cases in which:
  • The data file contains greater or fewer columns than the table or view.
  • The columns are in a different order.
  • The column delimiters vary.
  • There are other changes in the format of the data. Format files are usually created by using the bcp utility and modified with a text editor as needed.
KEEPIDENTITY
Specifies that the values for an identity column are present in the file being imported. If KEEPIDENTITY is not given, the identity values for this column in the data file being imported are ignored, and SQL Server automatically assigns unique values based on the seed and increment values specified during table creation. If the data file does not contain values for the identity column in the table or view, use a format file to specify that the identity column in the table or view should be skipped when importing data; SQL Server automatically assigns unique values for the column. For more information, see DBCC CHECKIDENT.
KEEPNULLS
Specifies that empty columns should retain a null value during the bulk copy operation, rather than have any default values for the columns inserted.
KILOBYTES_PER_BATCH [= kilobytes_per_batch]
Specifies the approximate number of kilobytes (K) of data per batch (as kilobytes_per_batch). By default, KILOBYTES_PER_BATCH is unknown.
LASTROW [= last_row]
Specifies the number of the last row to copy. The default is 0, indicating the last row in the specified data file.
MAXERRORS [= max_errors]
Specifies the maximum number of errors that can occur before the bulk copy operation is canceled. Each row that cannot be imported by the bulk copy operation is ignored and counted as one error. If max_errors is not specified, the default is 10.
ORDER ({column [ASC | DESC]} [,…n])
Specifies how the data in the data file is sorted. Bulk copy performance is improved if the data being loaded is sorted according to the clustered index on the table. If the data file is sorted in a different order, or there is no clustered index on the table, the ORDER clause is ignored. The names of the columns supplied must be valid columns in the destination table. By default, the bulk insert operation assumes the data file is unordered.
n
Is a placeholder indicating that multiple columns can be specified.
ROWS_PER_BATCH [= rows_per_batch]
Specifies the number of rows of data per batch (as rows_per_batch). Used when BATCHSIZE is not specified, resulting in the entire data file being sent to the server as a single transaction. The server optimizes the bulk load according to rows_per_batch. By default, ROWS_PER_BATCH is unknown.
ROWTERMINATOR [= 'row_terminator']
Specifies the row terminator to be used for char and widechar data files. The default is \n (newline character).
TABLOCK
Specifies that a table-level lock is acquired for the duration of the bulk copy operation. A table can be loaded concurrently by multiple clients if the table has no indexes and TABLOCK is specified. By default, locking behavior is determined by the table option table lock on bulk load. Holding a lock only for the duration of the bulk copy operation reduces lock contention on the table, thereby significantly improving performance.
Permissions

Only members of the sysadmin fixed server role can execute BULK INSERT.

Remarks

The BULK INSERT statement can be executed within a user-defined transaction. Rolling back a user-defined transaction that uses a BULK INSERT statement and BATCHSIZE clause to load data into a table or view using multiple batches rolls back all batches sent to SQL Server.

Examples

This example imports order detail information from the specified data file using a | character as the field terminator and |\n as the row terminator.

BULK INSERT Northwind.dbo.[Order Details]

    FROM 'f:\orders\lineitem.tbl'

    WITH

        (

            FIELDTERMINATOR = '|',

            ROWTERMINATOR = '|\n'

        )

See Also
sp_tableoption


CASE

Evaluates a list of conditions and returns one of multiple possible result expressions.

CASE has two formats:

  • The simple CASE function compares an expression to a set of simple expressions to determine the result.
  • The searched CASE function evaluates a set of Boolean expressions to determine the result.

Both formats support an optional ELSE argument.

Syntax

Simple CASE function:

CASE input_expression
WHEN when_expression THEN result_expression
[…n]
[
ELSE else_result_expression
]
END

Searched CASE function:

CASE
WHEN Boolean_expression THEN result_expression
[…n]
[
ELSE else_result_expression
]
END

Arguments
input_expression
Is the expression that is evaluated when using the simple CASE format. input_expression is any valid Microsoft® SQL Server™ expression.
WHEN when_expression
Is a simple expression to which input_expression is compared when using the simple CASE format. when_expression is any valid SQL Server expression. The data types of input_expression and each when_expression must be the same or must be an implicit conversion.
n
Is a placeholder indicating that multiple WHEN when_expression THEN result_expression clauses, or multiple WHEN Boolean_expression THEN result_expression clauses can be used.
THEN result_expression
Is the expression that is returned when input_expression equals when_expression evaluates to TRUE, or Boolean_expression evaluates to TRUE. result expression is any valid SQL Server expression.
ELSE else_result_expression
Is the expression that is returned if no comparison operation evaluates to TRUE. If this argument is omitted and no comparison operation evaluates to TRUE, CASE returns NULL. else_result_expression is any valid SQL Server expression. The data types of else_result_expression and any result_expression must be the same or must be an implicit conversion.
WHEN Boolean_expression
Is the Boolean expression that is evaluated when using the searched CASE format. Boolean_expression is any valid Boolean expression.
Result Types

Returns the highest precedence type from the set of types in result_expressions and the optional else_result_expression. For more information, see Data Type Precedence.

Result Values

Simple CASE function:

  • Evaluates input_expression, and then, in the order specified, evaluates input_expression = when_expression for each WHEN clause.
  • Returns the result_expression of the first (input_expression = when_expression) that evaluates to TRUE.
  • If no input_expression = when_expression evaluates to TRUE, SQL Server returns the else_result_expression if an ELSE clause is specified, or a NULL value if no ELSE clause is specified.

Searched CASE function:

  • Evaluates, in the order specified, Boolean_expression for each WHEN clause.
  • Returns result_expression of the first Boolean_expression that evaluates to TRUE.
  • If no Boolean_expression evaluates to TRUE, SQL Server returns the else_result_expression if an ELSE clause is specified, or a NULL value if no ELSE clause is specified.
Examples
A. Use a SELECT statement with a simple CASE function

Within a SELECT statement, a simple CASE function allows only an equality check; no other comparisons are made. This example uses the CASE function to alter the display of book categories to make them more understandable.

USE pubs

GO

SELECT    Category =

        CASE type

            WHEN 'popular_comp' THEN 'Popular Computing'

            WHEN 'mod_cook' THEN 'Modern Cooking'

            WHEN 'business' THEN 'Business'

            WHEN 'psychology' THEN 'Psychology'

            WHEN 'trad_cook' THEN 'Traditional Cooking'

            ELSE 'Not yet categorized'

        END,

    CAST(title AS varchar(25)) AS 'Shortened Title',

    price AS Price

FROM titles

WHERE price IS NOT NULL

ORDER BY type, price

COMPUTE AVG(price) BY type

GO

Here is the result set:

Category            Shortened Title           Price

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

Business            You Can Combat Computer S 2.99

Business            Cooking with Computers: S 11.95

Business            The Busy Executive's Data 19.99

Business            Straight Talk About Compu 19.99

                                              avg

                                              ==========================

                                              13.73

Category            Shortened Title           Price

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

Modern Cooking      The Gourmet Microwave     2.99

Modern Cooking      Silicon Valley Gastronomi 19.99

                                              avg

                                              ==========================

                                              11.49

Category            Shortened Title           Price

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

Popular Computing   Secrets of Silicon Valley 20.00

Popular Computing   But Is It User Friendly?  22.95

                                              avg

                                              ==========================

                                              21.48

Category            Shortened Title           Price

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

Psychology          Life Without Fear         7.00

Psychology          Emotional Security: A New 7.99

Psychology          Is Anger the Enemy?       10.95

Psychology          Prolonged Data Deprivatio 19.99

Psychology          Computer Phobic AND Non-P 21.59

                                              avg

                                              ==========================

                                              13.50

Category            Shortened Title           Price

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

Traditional Cooking Fifty Years in Buckingham 11.95

Traditional Cooking Sushi, Anyone?            14.99

Traditional Cooking Onions, Leeks, and Garlic 20.95

                                              avg

                                              ==========================

                                              15.96

(21 row(s) affected)

B. Use a SELECT statement with simple and searched CASE function

Within a SELECT statement, the searched CASE function allows values to be replaced in the result set based on comparison values. This example displays the price (a money column) as a text comment that is based on the cost range for a book.

USE pubs

GO

SELECT     'Price Category' =

        CASE

            WHEN price IS NULL THEN 'Not yet priced'

            WHEN price < 10 THEN 'Very Reasonable Title'

            WHEN price >= 10 and price < 20 THEN 'Coffee Table Title'

            ELSE 'Expensive book!'

        END,

    CAST(title AS varchar(20)) AS 'Shortened Title'

FROM titles

ORDER BY price

GO

Here is the result set:

Price Category        Shortened Title

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

Not yet priced        Net Etiquette

Not yet priced        The Psychology of Co

Very Reasonable Title The Gourmet Microwav

Very Reasonable Title You Can Combat Compu

Very Reasonable Title Life Without Fear

Very Reasonable Title Emotional Security:

Coffee Table Title    Is Anger the Enemy?

Coffee Table Title    Cooking with Compute

Coffee Table Title    Fifty Years in Bucki

Coffee Table Title    Sushi, Anyone?

Coffee Table Title    Prolonged Data Depri

Coffee Table Title    Silicon Valley Gastr

Coffee Table Title    Straight Talk About

Coffee Table Title    The Busy Executive's

Expensive book!       Secrets of Silicon V

Expensive book!       Onions, Leeks, and G

Expensive book!       Computer Phobic And

Expensive book!       But Is It User Frien

(18 row(s) affected)

C. Use CASE with SUBSTRING and SELECT

This example uses CASE and THEN to produce a list of authors, the book identification numbers, and the book types each author has written.

USE pubs

SELECT SUBSTRING((RTRIM(a.au_fname) + ' '+

    RTRIM(a.au_lname) + ' '), 1, 25) AS Name, a.au_id, ta.title_id,

    Type =

  CASE

    WHEN SUBSTRING(ta.title_id, 1, 2) = 'BU' THEN 'Business'

    WHEN SUBSTRING(ta.title_id, 1, 2) = 'MC' THEN 'Modern Cooking'

    WHEN SUBSTRING(ta.title_id, 1, 2) = 'PC' THEN 'Popular Computing'

    WHEN SUBSTRING(ta.title_id, 1, 2) = 'PS' THEN 'Psychology'

    WHEN SUBSTRING(ta.title_id, 1, 2) = 'TC' THEN 'Traditional Cooking'

  END

FROM titleauthor ta JOIN authors a ON ta.au_id = a.au_id

Here is the result set:

Name                      au_id       title_id Type

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

Johnson White             172-32-1176 PS3333   Psychology

Marjorie Green            213-46-8915 BU1032   Business

Marjorie Green            213-46-8915 BU2075   Business

Cheryl Carson             238-95-7766 PC1035   Popular Computing

Michael O'Leary           267-41-2394 BU1111   Business

Michael O'Leary           267-41-2394 TC7777   Traditional Cooking

Dean Straight             274-80-9391 BU7832   Business

Abraham Bennet            409-56-7008 BU1032   Business

Ann Dull                  427-17-2319 PC8888   Popular Computing

Burt Gringlesby           472-27-2349 TC7777   Traditional Cooking

Charlene Locksley         486-29-1786 PC9999   Popular Computing

Charlene Locksley         486-29-1786 PS7777   Psychology

Reginald Blotchet-Halls   648-92-1872 TC4203   Traditional Cooking

Akiko Yokomoto            672-71-3249 TC7777   Traditional Cooking

Innes del Castillo        712-45-1867 MC2222   Modern Cooking

Michel DeFrance           722-51-5454 MC3021   Modern Cooking

Stearns MacFeather        724-80-9391 BU1111   Business

Stearns MacFeather        724-80-9391 PS1372   Psychology

Livia Karsen              756-30-7391 PS1372   Psychology

Sylvia Panteley           807-91-6654 TC3218   Traditional Cooking

Sheryl Hunter             846-92-7186 PC8888   Popular Computing

Anne Ringer               899-46-2035 MC3021   Modern Cooking

Anne Ringer               899-46-2035 PS2091   Psychology

Albert Ringer             998-72-3567 PS2091   Psychology

Albert Ringer             998-72-3567 PS2106   Psychology

(25 row(s) affected)

See Also
Data Types | UPDATE
Expressions | WHERE
SELECT | System Functions


CAST and CONVERT

Explicitly converts an expression of one data type to another. CAST and CONVERT provide similar functionality.

Syntax

Using CAST:

CAST(expression AS data_type)

Using CONVERT:

CONVERT (data_type[(length)], expression [, style])

Arguments
expression
Is any valid Microsoft® SQL Server™ expression. For more information, see Expressions.
data_type
Is the target system-supplied data type. User-defined data types cannot be used. For more information about available data types, see Data Types.
length
Is an optional parameter of nchar, nvarchar, char, varchar, binary, or varbinary data types.
style
Is the style of date format you want when converting datetime or smalldatetime data to character data (nchar, nvarchar, char, varchar, nchar, or nvarchar data types), or the string format when converting float, real, money, or smallmoney data to character data (nchar, nvarchar, char, varchar, nchar, or nvarchar data types).

In the table, the two columns on the left represent the style values for datetime or smalldatetime conversion to character data. Add 100 to a style value to get a four-place year that includes the century (yyyy).

Without
century
(yy) 		With
century
(yyyy)

Standard

Input/Output**
- 0 or 100 (*) Default mon dd yyyy hh:miAM (or PM)
1 | 101 | USA | mm/dd/yy
2 | 102 | ANSI | yy.mm.dd
3 | 103 | British/French | dd/mm/yy
4 | 104 | German | dd.mm.yy
5 | 105 | Italian | dd-mm-yy
6 106 - dd mon yy
7 107 - mon dd, yy
8 108 - hh:mm:ss
- 9 or 109 (*) Default + milliseconds mon dd yyyy hh:mi:ss:mmmAM (or PM)
10 | 110 | USA | mm-dd-yy
11 | 111 | JAPAN | yy/mm/dd
12 | 112 | ISO | yymmdd
- 13 or 113 (*) Europe default + milliseconds dd mon yyyy hh:mm:ss:mmm(24h)
14 114 - hh:mi:ss:mmm(24h)
- 20 or 120 (*) ODBC canonical yyyy-mm-dd hh:mi:ss(24h)
- 21 or 121 (*) ODBC canonical (with milliseconds) yyyy-mm-dd hh:mi:ss.mmm(24h)
* The default values (style 0 or 100, 9 or 109, 13 or 113, 20 or 120, and 21 or 121) always return the century (yyyy).

** Input when converting to datetime; Output when converting to character data.

When you convert to character data from smalldatetime, the styles that include seconds or milliseconds show zeros in these positions. You can truncate unwanted date parts when converting from datetime or smalldatetime values by using an appropriate char or varchar data type length.

This table shows the style values for float or real conversion to character data.

Value | Output
0 (the default) | 6 digits maximum. Use in scientific notation, when appropriate.
1 | Always 8 digits. Always use in scientific notation.
2 | Always 16 digits. Always use in scientific notation.

In the following table, the column on the left represents the style value for money or smallmoney conversion to character data.

Value | Output
0 (the default) | No commas every three digits to the left of the decimal point, and two digits to the right of the decimal point; for example, 4235.98.
1 | Commas every three digits to the left of the decimal point, and two digits to the right of the decimal point; for example, 3,510.92.
2 | No commas every three digits to the left of the decimal point, and four digits to the right of the decimal point; for example, 4235.9819.

Return Types

Returns the same value as data type 0.

Remarks

Implicit conversions are those conversions that occur without specifying either the CAST or CONVERT function. Explicit conversions are those conversions that require the CAST (CONVERT) function to be specified. This chart shows all explicit and implicit data type conversions allowed for SQL Server system-supplied data types.

Note Because Unicode data always use an even number of bytes, use caution when converting binary or varbinary to or from Unicode supported data types. For example, this conversion does not return a hexadecimal value of 41, but of 4100:

SELECT CAST(CAST(0x41 AS nvarchar) AS varbinary)

Automatic data type conversion is not supported for the text and image data types. You can explicitly convert text data to character data, and image data to binary or varbinary, but the maximum length you can specify is 8000. If you attempt a conversion that is not possible (for example, if you convert a character expression that includes letters to an int), SQL Server generates an error message.

When converting character or binary expressions (char, nchar, nvarchar, varchar, binary, or varbinary) to an expression of a different data type, data can be truncated, only partially displayed, or an error is returned because the result is too short to display. Conversions to char, varchar, nchar, nvarchar, binary, and varbinary are truncated, except for the conversions shown in this table.

From data type | To data type | Result
int, smallint, or tinyint | char | *
 | varchar | *
 | nchar | E
 | nvarchar | E
money, smallmoney, numeric, decimal, float, or real | char | E
 | varchar | E
 | nchar | E
 | nvarchar | E
* Result length too short to display. E Error returned because result length is too short to display.

Microsoft SQL Server guarantees that only roundtrip conversions, conversions that convert a data type from its original data type and back again, will yield the same values from release to release. This example shows such a roundtrip conversion:

DECLARE @myval decimal (5, 2)

SET @myval = 193.57

SELECT CAST(CAST(@myval AS varbinary(20)) AS decimal(10,5))

-- Or, using CONVERT

SELECT CONVERT(decimal(10,5), CONVERT(varbinary(20), @myval))

Do not attempt to construct, for example, binary values and convert them to a data type of the numeric data type category. SQL Server does not guarantee that the result of a decimal or numeric data type conversion to binary will be the same between releases of SQL Server.

When data types are converted with a different number of decimal places, the value is truncated to the most precise digit. For example, the result of SELECT CAST(10.6496 AS int) is 10.

This example shows a resulting expression that is too small to display.

USE pubs

SELECT SUBSTRING(title, 1, 25) AS Title, CAST(ytd_sales AS char(2))

FROM titles

WHERE type = 'trad_cook'

Here is the result set:

Title

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

Onions, Leeks, and Garlic *

Fifty Years in Buckingham *

Sushi, Anyone?            *

(3 row(s) affected)

When data types in which the target data type has fewer decimal points than the source data type are converted, the value is rounded. For example, the result of CAST(10.3496 AS money) is $10.35.

SQL Server returns an error message when char, nchar, varchar, or nvarchar data is converted to int, float, numeric, or decimal; or when an empty string (“ “) is converted to int or float.

Using Binary String Data

When binary or varbinary data is converted to character data and an odd number of values is specified following the x, SQL Server adds a 0 (zero) after the x to make an even number of values.

Binary data consists of the characters 0 through 9 and A through F (or through f), in groups of two characters each. Binary strings must be preceded by 0x. For example, to input FF, type 0xFF. The maximum value is a binary value of 8000 bytes, each of which is FF. The binary data types are not for hexadecimal data, but rather for bit patterns. Conversions and calculations of hexadecimal numbers stored as binary data can be unreliable.

When specifying the length of a binary data type, every two characters count as one. A length of 10 signifies that 10 two-character groupings will be entered.

Empty binary strings, represented by 0x, can be stored as binary data.

Examples
A. Use both CAST and CONVERT

    Each example retrieves the titles for those books that have a 3 in the first digit of year-to-date sales, and converts their ytd_sales to char(20).

    -- Use CAST.

    USE pubs

    GO

    SELECT SUBSTRING(title, 1, 30) AS Title, ytd_sales

    FROM titles

    WHERE CAST(ytd_sales AS char(20)) LIKE '3%'

    GO

    -- Use CONVERT.

    USE pubs

    GO

    SELECT SUBSTRING(title, 1, 30) AS Title, ytd_sales

    FROM titles

    WHERE CONVERT(char(20), ytd_sales) LIKE '3%'

    GO

    Here is the result set for either query:

    Title                          ytd_sales

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

    Cooking with Computers: Surrep 3876

    Computer Phobic AND Non-Phobic 375

    Emotional Security: A New Algo 3336

    Onions, Leeks, and Garlic: Coo 375

    (4 row(s) affected)

    B. Use CAST with arithmetic operators

      This example calculates a single column computation (Copies) by dividing the total year-to-date sales (ytd_sales) divided by the individual book price (price). This result is converted to an int data type after being rounded to the nearest whole number.

      USE pubs

      GO

      SELECT CAST(ROUND(ytd_sales/price, 0) AS int) AS 'Copies'

      FROM titles

      GO

      Here is the result set:

      Copies

      -----------

      205

      324

      6262

      205

      102

      7440

      NULL

      383

      205

      NULL

      17

      187

      16

      204

      418

      18

      1263

      273

      (18 row(s) affected)

      C. Use CAST to concatenate

      This example concatenates noncharacter, nonbinary expressions using the CAST data type conversion function.

      USE pubs

      GO

      SELECT 'The price is ' + CAST(price AS varchar(12))

      FROM titles

      WHERE price > 10.00

      GO

      Here is the result set:

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

      The price is 19.99

      The price is 11.95

      The price is 19.99

      The price is 19.99

      The price is 22.95

      The price is 20.00

      The price is 21.59

      The price is 10.95

      The price is 19.99

      The price is 20.95

      The price is 11.95

      The price is 14.99

      (12 row(s) affected)

      D. Use CAST for more readable text

        This example uses CAST in the select list to convert the title column to a char(50) column so the results are more readable.

        USE pubs

        GO

        SELECT CAST(title AS char(50)), ytd_sales

        FROM titles

        WHERE type = 'trad_cook'

        GO

        Here is the result set:

                                                               ytd_sales

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

        Onions, Leeks, and Garlic: Cooking Secrets of the      375

        Fifty Years in Buckingham Palace Kitchens              15096

        Sushi, Anyone?                                         4095

        (3 row(s) affected)

        E. Use CAST with LIKE clause

          This example converts an int column (the ytd_sales column) to a char(20) column so that it can be used with the LIKE clause.

          USE pubs

          GO

          SELECT title, ytd_sales

          FROM titles

          WHERE CAST(ytd_sales AS char(20)) LIKE '15%'

              AND type = 'trad_cook'

          GO

          Here is the result set:

          title                                                        ytd_sales

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

          Fifty Years in Buckingham Palace Kitchens                    15096

          (1 row(s) affected)

          See Also
          SELECT System Functions


CEILING

A mathematical function that returns the smallest integer greater than or equal to the given numeric expression.

Syntax

CEILING(numeric_expression)

Arguments
numeric_expression
Is an expression of the exact numeric or approximate numeric data type category, except for the bit data type.
Return Types

Returns the same type as numeric_expression.

Examples

This example shows positive numeric, negative, and zero values with the CEILING function.

SELECT CEILING($123.45), CEILING($-123.45), CEILING($0.0)

GO

Here is the result set:

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

124.00    -123.00    0.00

(1 row(s) affected)

See Also
System Functions


char and varchar

Character data types that are either fixed-length (char) or variable-length (varchar) and are in the code page of the server.

char[(n)]
Fixed-length non-Unicode character data with length of n characters. n must be a value from 1 through 8,000. Storage size is n bytes. The SQL-92 synonym for char is character.
varchar[(n)]
Variable-length non-Unicode character data with length of n characters. n must be a value from 1 through 8,000. Storage size is the actual length of the data entered, not n bytes. The data entered can be 0 characters in length. The SQL-92 synonyms for varchar are char varying or character varying.
Remarks

When n is not specified in a data definition or variable declaration statement, the default length is 1. When n is not specified with the CAST function, the default length is 30.

If SET ANSI_PADDING is OFF when CREATE TABLE or ALTER TABLE is executed, a char column defined as NULL is handled as varchar.

Use char when the data entries in a column are expected to be consistently close to the same size.

Use varchar when the data entries in a column are expected to vary considerably in size.

When the server code page uses double-byte characters, the storage size is still n bytes. Depending on the character string, the storage size of n bytes may be less than n characters.

See Also
CAST and CONVERT | sp_dbcmptlevel
Data Types |


CHAR

A string function that converts an int ASCII code to a character.

Syntax

CHAR(integer_expression)

Arguments
integer_expression
Is an integer from 0 through 255. NULL is returned if the integer expression is not in this range.
Return Types

char(1)

Remarks

CHAR can be used to insert control characters into character strings. The table shows some commonly used control characters.

Control character | Value
Tab | CHAR(9)
Line feed | CHAR(10)
Carriage return | CHAR(13)

Examples
A. Use ASCII and CHAR to print ASCII values from a string

This example prints the ASCII value and character for each character in the string New Moon.

SET TEXTSIZE 0

-- Create variables for the character string and for the current

-- position in the string.

DECLARE @position int, @string char(8)

-- Initialize the current position and the string variables.

SET @position = 1

SET @string = 'New Moon'

WHILE @position <= DATALENGTH(@string)

    BEGIN

    SELECT ASCII(SUBSTRING(@string, @position, 1)),

        CHAR(ASCII(SUBSTRING(@string, @position, 1)))

    SET @position = @position + 1

    END

GO

Here is the result set:

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

78          N

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

101         e

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

119         w

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

32

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

77          M

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

111         o

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

111         o

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

110         n

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

B. Use CHAR to insert a control character

    This example uses CHAR(13) to print name, address, and city information on separate lines.

    USE Northwind

    SELECT FirstName + ' ' + LastName, + CHAR(13) + Address,
        + CHAR(13)+ City, Region

    FROM Employees

    WHERE EmployeeID = 1

    Here is the result set:

    Nancy Davolio

    507 - 20th Ave. E.

    Apt. 2A

    Seattle            WA

    Note In this record, the data in the Address column also contains a control character.

    See Also
    + (String Concatenation) String Functions


CHARINDEX

Returns the starting position of the specified expression in a character string.

Syntax

CHARINDEX(expression1, expression2 [, start_location])

Arguments
expression1
Is an expression containing the sequence of characters to be found. expression1 is an expression of the short character data type category.
expression2
Is an expression, usually a column that is searched for the specified sequence. expression2 is of the character string data type category.
start_location
Is the character position to start searching for expression1 in expression2. If start_location is not given, is a negative number, or is zero, the search starts at the beginning of expression2.
Return Types

int

Remarks

If either expression1 or expression2 is of a Unicode data type (nvarchar or nchar) and the other is not, the other is converted to a Unicode data type.

If either expression1 or expression2 is NULL, CHARINDEX returns NULL when the database compatibility level is 70. If the database compatibility level is 65 or earlier, CHARINDEX returns NULL only when both expression1 and expression2 are NULL.

Examples

The first code example returns the position at which the sequence wonderful begins in the notes column of the titles table. The second example uses the optional start_location parameter to begin looking for wonderful in the fifth character of the notes column.

USE pubs

GO

SELECT CHARINDEX('wonderful', notes)

FROM titles

WHERE title_id = 'TC3218'

GO

-- Use the optional start_location parameter to start searching

-- for wonderful starting with the fifth character in the notes

-- column.

USE pubs

GO

SELECT CHARINDEX('wonderful', notes, 5)

FROM titles

WHERE title_id = 'TC3218'

GO

Here is the result set for either query:

-----------

47

(1 row(s) affected)

See Also
+ (String Concatenation) String Functions


CHECKPOINT

Forces all dirty pages for the current database to be written to disk. Dirty pages are data or log pages that have been modified after they were read into the buffer cache, but the modifications have not yet been written to disk. If the current database is in log truncate mode, CHECKPOINT also truncates the inactive portion of the log. For more information about log truncation, see Truncating the Transaction Log.

Syntax

CHECKPOINT

Remarks

The CHECKPOINT statement saves time in a subsequent recovery by creating a point at which all modifications to data and log pages are guaranteed to have been written to disk.

A typical checkpoint takes 1 second to complete, although this figure varies depending on the amount of activity on SQL Server and the size of the data cache.

Checkpoints also occur:

  • When a database option is changed with sp_dboption. A checkpoint is executed in the database in which the option is changed.
  • When a server is stopped, a checkpoint is executed in each database on the server. These methods of stopping SQL Server 7.0 checkpoint each database:
    • Using SQL Server Service Manager.
    • Using SQL Server Enterprise Manager.
    • Using the SHUTDOWN statement.
    • Using the Windows NT command net stop mssqlserver on the command prompt.
    • Using the services icon in the Windows NT control panel, selecting the mssqlserver service, and clicking the stop button.

The SHUTDOWN WITH NOWAIT statement shuts down SQL Server without executing a checkpoint in each database. This may cause the subsequent restart to take a longer time than usual to recover the databases on the server.

SQL Server 7.0 also automatically checkpoints any database where the lesser of these two conditions occur:

  • The active portion of the log exceeds the size that the server could recover in the amount of time specified in the recovery interval server configuration option.
  • If the database is in log truncate mode and the log becomes 70% full.

A database is in log truncate mode when both these conditions are true:

  • The trunc. log on chkpt. database option is set to TRUE.
  • One of these events has occurred after the last BACKUP DATABASE statement referencing the database was executed:
    • A BACKUP LOG statement referencing the database is executed with either the NO_LOG or TRUNCATE_ONLY clauses.
    • A nonlogged operation is performed in the database, such as a nonlogged bulk copy operation or a nonlogged WRITETEXT statement is executed.
    • An ALTER DATABASE statement that adds or deletes a file in the database is executed.
Permissions

Permission to use the CHECKPOINT statement defaults to members of the db_owner fixed database role, and is not transferable.

See Also
SHUTDOWN sp_dboption


CLOSE

Closes an open cursor by releasing the current result set and freeing any cursor locks held on the rows on which the cursor is positioned. CLOSE leaves the data structures accessible for reopening, but fetches and positioned updates are not allowed until the cursor is reopened. CLOSE must be issued on an open cursor; it is not allowed on cursors that have only been declared or are already closed.

Syntax

CLOSE { { [GLOBAL] cursor_name } | cursor_variable_name }

Arguments
GLOBAL
Specifies that cursor_name refers to a global cursor.
cursor_name
Is the name of an open cursor. If both a global and a local cursor exist with cursor_name as their name, cursor_name refers to the global cursor when GLOBAL is specified; otherwise, cursor_name refers to the local cursor.
cursor_variable_name
Is the name of a cursor variable associated with an open cursor.
Examples

This example shows the correct placement of the CLOSE statement in a cursor based process.

USE pubs

GO

DECLARE authorcursor CURSOR FOR

SELECT au_fname, au_lname

FROM authors

ORDER BY au_fname, au_lname

OPEN authorcursor

FETCH NEXT FROM authorcursor

WHILE @@FETCH_STATUS = 0

BEGIN

   FETCH NEXT FROM authorcursor

END

CLOSE authorcursor

DEALLOCATE authorcursor

GO

See Also
OPEN | FETCH
DEALLOCATE |


COALESCE

Returns the first nonnull expression among its arguments.

Syntax

COALESCE(expression [,…n])

Arguments
expression
Is an expression of any type.
n
Is a placeholder indicating that multiple expressions can be specified. All expressions must be of the same type or must be implicitly convertible to the same type.
Return Types

Returns the same value as expression.

Remarks

If all arguments are NULL, COALESCE returns NULL.

COALESCE(expression1,…n) is equivalent to this CASE function:

CASE
    WHEN (expression1 IS NOT NULL) THEN expression1
    …
    WHEN (expressionN IS NOT NULL) THEN expressionN
    ELSE NULL

Examples

In this example, the wages table is shown to include three columns with information about an employee’s yearly wage: hourly_wage, salary, and commission. However, an employee receives only one type of pay. To determine the total amount paid to all employees, use the COALESCE function to receive only the nonnull value found in hourly_wage, salary, and commission.

SET NOCOUNT ON

GO

USE master

IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES

        WHERE TABLE_NAME = 'wages')

    DROP TABLE wages

GO

CREATE TABLE wages

(

    emp_id        tinyint     identity,

    hourly_wage    decimal    NULL,

    salary        decimal     NULL,

    commission    decimal    NULL,

    num_sales    tinyint    NULL

)

GO

INSERT wages VALUES(10.00, NULL, NULL, NULL)

INSERT wages VALUES(20.00, NULL, NULL, NULL)

INSERT wages VALUES(30.00, NULL, NULL, NULL)

INSERT wages VALUES(40.00, NULL, NULL, NULL)

INSERT wages VALUES(NULL, 10000.00, NULL, NULL)

INSERT wages VALUES(NULL, 20000.00, NULL, NULL)

INSERT wages VALUES(NULL, 30000.00, NULL, NULL)

INSERT wages VALUES(NULL, 40000.00, NULL, NULL)

INSERT wages VALUES(NULL, NULL, 15000, 3)

INSERT wages VALUES(NULL, NULL, 25000, 2)

INSERT wages VALUES(NULL, NULL, 20000, 6)

INSERT wages VALUES(NULL, NULL, 14000, 4)

GO

SET NOCOUNT OFF

GO

SELECT CAST(COALESCE(hourly_wage * 40 * 52,

    salary,

    commission * num_sales) AS money) AS 'Total Salary'

FROM wages

GO

Here is the result set:

Total Salary

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

20800.0000

41600.0000

62400.0000

83200.0000

10000.0000

20000.0000

30000.0000

40000.0000

45000.0000

50000.0000

120000.0000

56000.0000

(12 row(s) affected)

See Also
CASE System Functions


COL_LENGTH

Returns the defined length of a column.

Syntax

COL_LENGTH('table', 'column')

Arguments
'table'
Is the name of the table for which to determine column length information. table is an expression of type nvarchar.
'column'
Is the name of the column for which to determine length. column is an expression of type nvarchar.
Return Types

int

Examples

This example finds the length of the title column in the titles table. The x gives a column heading to the result.

USE pubs

SELECT COL_LENGTH('titles', 'title') AS x

Here is the result set:

x

------

80

(1 row(s) affected)

See Also
Expressions Metadata Functions


COL_NAME

Returns the name of a database column given the corresponding table identification number and column identification number.

Syntax

COL_NAME(table_id, column_id)

Arguments
table_id
Is the identification number of the table containing the database column. table_id is of type int.
column_id
Is the identification number of the column. column_id parameter is of type int.
Return Types

sysname

Remarks

The table_id and column_id parameters together produce a column name string.

For more information about obtaining table and column identification numbers, see OBJECT_ID.

Examples

This example returns the name of each column in the authors table of the pubs database.

Note The table identification number was generated by executing OBJECT_ID.

USE pubs

SET NOCOUNT OFF

SELECT COL_NAME(117575457, ORDINAL_POSITION)

FROM INFORMATION_SCHEMA.COLUMNS

WHERE TABLE_NAME = 'authors'

Here is the result set:

column_name

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

au_id                                                                                                                                                                                                                                                           au_id

au_lname                                                                                                                                                                                                                                                        au_lname

au_fname                                                                                                                                                                                                                                                        au_fname

phone                                                                                                                                                                                                                                                           phone

address                                                                                                                                                                                                                                                         address

city                                                                                                                                                                                                                                                            city

state                                                                                                                                                                                                                                                           state

zip                                                                                                                                                                                                                                                             zip

contract                                                                                                                                                                                                                                                        contract

(9 row(s) affected)

See Also
Expressions | Metadata Functions
sysobjects |


COLUMNPROPERTY

Returns information about a column or procedure parameter.

Syntax

COLUMNPROPERTY(id, column, property)

Arguments
id
Is an expression containing the id of the table or procedure.
column
Is an expression containing the name of the column or parameter.
property
Is an expression containing the information to be returned for id, and can be any of these values.

Value Description Value returned
AllowsNull Allows null values. 1 = True
0 = False
NULL = Invalid input
IsComputed The column is a computed column. 1 = True
0 = False
NULL = Invalid input
IsCursorType The procedure parameter is of type CURSOR. 1 = True
0 = False
NULL = Invalid input
IsFulltextIndexed The column has been registered for Full-Text indexing. 1 = True
0 = False
NULL = Invalid input
IsIdentity The column uses the IDENTITY property. 1 = True
0 = False
NULL = Invalid input
IsIdNotForRepl The column checks for the IDENTITY_INSERT setting. If IDENTITY NOT FOR REPLICATION is specified, the IDENTITY_INSERT setting is not checked. 1 = True
0 = False
NULL = Invalid input
IsOutParam The procedure parameter is an output parameter. 1 = True
0 = False
NULL = Invalid input
IsRowGuidCol The column has the uniqueidentifier data type and is defined with the ROWGUIDCOL property. 1 = True
0 = False
NULL = Invalid input
Precision Precision for the data type of the column or parameter. The precision of the specified column data type.

NULL = Invalid input
Scale Scale for the data type of the column or parameter. The scale

NULL = Invalid input
UsesAnsiTrim ANSI padding setting was ON when the table was initially created. 1= True
0= False
NULL = Invalid input

Return Types

int

Examples

This example returns the length of the au_lname column.

SELECT COLUMNPROPERTY( OBJECT_ID('authors'),'au_lname','PRECISION')

See Also
OBJECTPROPERTY | Metadata Functions
TYPEPROPERTY |


COMMIT TRANSACTION

Marks the end of a successful implicit or user-defined transaction. If @@TRANCOUNT is 1, COMMIT TRANSACTION makes all data modifications performed since the start of the transaction a permanent part of the database, frees the resources held by the connection, and decrements @@TRANCOUNT to 0. If @@TRANCOUNT is greater than 1, COMMIT TRANSACTION decrements @@TRANCOUNT only by 1.

Syntax

COMMIT [ TRAN[SACTION] [transaction_name | @tran_name_variable] ]

Arguments
transaction_name
Is ignored by Microsoft® SQL Server™. transaction_name specifies a transaction name assigned by a previous BEGIN TRANSACTION. transaction_name must conform to the rules for identifiers, but only the first 32 characters of the transaction name are used. transaction_name can be used as a readability aid by indicating to programmers which nested BEGIN TRANSACTION the COMMIT TRANSACTION is associated with.
@tran_name_variable
Is the name of a user-defined variable containing a valid transaction name. The variable must be declared with a char, varchar, nchar, or nvarchar data type.
Remarks

It is the responsibility of Transact-SQL programmers to issue COMMIT TRANSACTION only at a point when all data referenced by the transaction is logically correct.

If the transaction being committed was a Transact-SQL distributed transaction, COMMIT TRANSACTION triggers MS DTC to use a two-phase commit protocol to commit all the servers involved in the transaction. If a local transaction spans two or more databases on the same server, SQL Server uses an internal two-phase commit to commit all the databases involved in the transaction.

When used in nested transactions, commits of the inner transactions do not free resources or make their modifications permanent. The data modifications are made permanent and resources freed only when the outer transaction is committed. Each COMMIT TRANSACTION issued when @@TRANCOUNT is greater than 1 simply decrements @@TRANCOUNT by 1. When @@TRANCOUNT is finally decremented to 0, the entire outer transaction is committed. Because transaction_name is ignored by SQL Server, issuing a COMMIT TRANSACTION referencing the name of an outer transaction when there are outstanding inner transactions only decrements @@TRANCOUNT by 1.

Issuing a COMMIT TRANSACTION when @@TRANCOUNT is 0 results in an error that there is no corresponding BEGIN TRANSACTION.

You cannot roll back a transaction after a COMMIT TRANSACTION statement is issued because the data modifications have been made a permanent part of the database.

Examples
A. Commit a transaction.

    This example increases the advance to be paid to an author when year-to-date sales of a title are greater than $8,000.

    BEGIN TRANSACTION

    USE pubs

    GO

    UPDATE titles

    SET advance = advance * 1.25

    WHERE ytd_sales > 8000

    GO

    COMMIT

    GO

    B. Commit a nested transaction.

      This example creates a table, generates three levels of nested transactions, and then commits the nested transaction. Although each COMMIT TRANSACTION statement has a transaction_name parameter, there is no relationship between the COMMIT TRANSACTION and BEGIN TRANSACTION statements. The transaction_name parameters are simply readability aids to help the programmer ensure the proper number of commits are coded to decrement @@TRANCOUNT to 0, and thereby commit the outer transaction.

      CREATE TABLE TestTran (Cola INT PRIMARY KEY, Colb CHAR(3))

      GO

      BEGIN TRANSACTION OuterTran -- @@TRANCOUNT set to 1.

      GO

      INSERT INTO TestTran VALUES (1, 'aaa')

      GO

      BEGIN TRANSACTION Inner1 -- @@TRANCOUNT set to 2.

      GO

      INSERT INTO TestTran VALUES (2, 'bbb')

      GO

      BEGIN TRANSACTION Inner2 -- @@TRANCOUNT set to 3.

      GO

      INSERT INTO TestTran VALUES (3, 'ccc')

      GO

      COMMIT TRANSACTION Inner2 -- Decrements @@TRANCOUNT to 2.

      -- Nothing committed.

      GO

      COMMIT TRANSACTION Inner1 -- Decrements @@TRANCOUNT to 1.

      -- Nothing committed.

      GO

      COMMIT TRANSACTION OuterTran -- Decrements @@TRANCOUNT to 0.

      -- Commits outer transaction OuterTran.

      GO

      See Also
      BEGIN TRANSACTION | ROLLBACK TRANSACTION
BEGIN DISTRIBUTED TRANSACTION | ROLLBACK WORK
COMMIT WORK | @@TRANCOUNT
SAVE TRANSACTION |


COMMIT WORK

Marks the end of a transaction.

Syntax

COMMIT [WORK]

Remarks

This statement functions identically to COMMIT TRANSACTION, except COMMIT TRANSACTION accepts a user-defined transaction name. This COMMIT syntax, with or without specifying the optional keyword WORK, is compatible with SQL-92.

See Also
BEGIN TRANSACTION | SAVE TRANSACTION
BEGIN DISTRIBUTED TRANSACTION | ROLLBACK WORK
COMMIT TRANSACTION | @@TRANCOUNT
ROLLBACK TRANSACTION |


Constants

A constant, also known as a literal or a scalar value, is a symbol that represents a specific data value. The format of a constant depends on the data type of the value it represents.

Character string constants
Character string constants are enclosed in single quotation marks and include alphanumeric characters (a-z, A-Z, and 0-9) and special characters, such as !, @, and #. Character strings are evaluated through the code page of the computer.

If the QUOTED_IDENTIFIER option has been set OFF for a connection, character strings can also be enclosed in double quotation marks, but the Microsoft® OLE DB Provider for SQL Server and ODBC driver automatically use SET QUOTED_IDENTIFIER ON. The use of single quotation marks is recommended.

If a character string enclosed in single quotation marks contains an embedded quotation mark, represent the embedded single quotation mark with two single quotation marks. This is not necessary in strings embedded in double quotation marks.

Examples of character strings are:

'Cincinnati'

'O''Brien'

'Process X is 50% complete.'

'The level for job_id: %d should be between %d and %d.'

"O'Brien"

Empty strings are represented as '' (two single quotation marks with nothing in between). In 6.x compatibility mode, an empty string is treated as a single space.

Unicode strings
Unicode strings have a format similar to character strings, but are preceded by an N identifier (N stands for National Language in the SQL-92 standard). The N prefix must be uppercase. For example, ‘Michél’ is a character constant while N’Michél’ is a Unicode constant. Unicode constants are interpreted as Unicode data, and are not evaluated using a code page. Unicode data is stored using 2 bytes per character, as opposed to 1 byte per character for character data.
Binary constants
Binary constants have the suffix 0x and are a string of hexadecimal numbers. They are not enclosed in quotation marks. Examples of binary strings are:

0xAE

0x12Ef

0x69048AEFDD010E

0x  (empty binary string)

Bit constants
Bit constants are represented by the numbers 0 or 1, and are not enclosed in quotation marks. If a number larger than 1 is used, it is converted to 1.
Datetime constants
Datetime constants are represented using character date values in specific formats, enclosed in single quotation marks. Examples of date constants are:

'April 15, 1998'

'15 April, 1998'

'980415'

'04/15/98'

Examples of time constants are:

'14:30:24'

'04:24 PM'

Integer constants
Integer constants are represented by a string of numbers that are not enclosed in quotation marks and do not contain decimal points. Integer constants must be whole numbers; they cannot contain decimals. Examples of integer constants are:

1894

2

Decimal constants
Decimal constants are represented by a string of numbers that are not enclosed in quotation marks and contain a decimal point. Examples of decimal constants are:

1894.1204

2.0

Float and real constants
Float and real constants are represented using scientific notation. Examples of float or real values are:

101.5E5

0.5E-2

Money constants
Money constants are represented as string of numbers with an optional decimal point and an optional currency symbol as a prefix. They are not enclosed in quotation marks. Examples of money constants are:

$12

$542023.14

Uniqueidentifier constants
Uniqueidentifier constants are a string representing a globally unique identifier (GUID) value. They can be specified in either a character or binary string format. Both of these examples specify the same GUID:

'6F9619FF-8B86-D011-B42D-00C04FC964FF'

0xff19966f868b11d0b42d00c04fc964ff

Specifying Negative and Positive Numbers

To indicate whether a number is positive or negative, apply the + or - unary operators to a numeric constant. This creates a numeric expression that represents the signed numeric value. Numeric constants default to positive if the + or - unary operators are not applied.

  • Signed integer expressions:

    +145345234

    -2147483648

  • Signed decimal expressions:

    +145345234.2234

    -2147483648.10

  • Signed float expressions:

    +123E-3

    -12E5

  • Signed money expressions:

    -$45.56

    +$423456.99

See Also
Expressions | Operators
Data Types |


CONTAINS

Is a predicate used to search columns containing character-based data types for precise or “fuzzy” (less precise) matches to single words and phrases, the proximity of words within a certain distance of one another, or weighted matches. CONTAINS can search for:

  • A word or phrase.
  • The prefix of a word or phrase.
  • A word that is near another word.
  • A word that is inflectionally generated from another (for example, the word drive is the inflectional stem of drives, drove, driving, and driven.)
  • A word that has a higher designated weighting than another word.
Syntax

CONTAINS
( {column | *}, '<contains_search_condition>'
)

<contains_search_condition> ::=
{
| <generation_term>
| <prefix_term>
| <proximity_term>
| <simple_term>
| <weighted_term>
}
| { (<contains_search_condition>)
 {AND | AND NOT | OR} <contains_search_condition> […n]
}

<weighted_term> ::=
 ISABOUT
( { {
<generation_term>
| <prefix_term>
| <proximity_term>
| <simple_term>
}
[WEIGHT (weight_value)]
} [,…n]
)

<generation_term> ::=
 FORMSOF (INFLECTIONAL, <simple_term> [,…n] )

<prefix term> ::=
{ "word * " | "phrase * " }

<proximity_term> ::=
 {<simple_term> | <prefix_term>}
{ {NEAR | ~} {<simple_term> | <prefix_term>} } […n]

<simple_term> ::=
 word | " phrase "

Arguments
column
Is the name of a specific column that has been registered for full-text searching. Columns of the character string data types are valid full-text searching columns.
*
Specifies that all columns in the table that have been registered for full-text searching should be used to search for the given contains search condition(s). If more than one table is in the FROM clause, * must be qualified by the table name.
<contains_search_condition>
Specifies some text to search for in column. Variables cannot be used for the search condition.
word
Is a string of characters without spaces or punctuation.
phrase
Is one or more words with spaces between each word.

Note Some languages, such as those in the Far East, can have phrases that consist of one or more words without spaces between them.

<weighted_term>
Specifies that the matching rows (returned by the query) match a list of words and phrases, each optionally given a weighting value.
ISABOUT
Specifies the <weighted_term> keyword.
WEIGHT (weight_value)
Specifies a weight value which is a number between 0.0 and 1.0. Each component in <weighted_term> may include a weight_value. weight_value is a way to change how various portions of a query affect the rank value assigned to each row matching the query. Weighting forces a different measurement of the ranking of a value because all the components of <weighted_term> are used together to determine the match. A row is returned if there is a match on any one of the ISABOUT parameters, whether or not a weight value is assigned. To determine the rank values for each returned row that indicates the degree of matching between the returned rows, see CONTAINSTABLE.
AND | AND NOT | OR
Specifies a logical operation between two contains search conditions. When <contains_search_condition> contains parenthesized groups, these parenthesized groups are evaluated first. After evaluating parenthesized groups, these rules apply when using these logical operators with contains search conditions:
  • NOT is applied before AND.
  • NOT can only occur after AND, as in AND NOT. The OR NOT operator is not allowed. NOT cannot be specified before the first term (for example, CONTAINS(mycolumn, ‘NOT “phrase_to_search_for” ‘ ).
  • AND is applied before OR.
  • Boolean operators of the same type (AND, OR) are associative and can therefore be applied in any order.
<generation_term>
Specifies a match of words when the included simple terms include variants of the original word for which to search.
INFLECTIONAL
Specifies that both plural and singular forms of nouns and the various tenses of verbs are to be matched. A given <simple_term> within a <generation_term> will not match both nouns and verbs.
<prefix_term>
Specifies a match of words or phrases beginning with the specified text. Enclose a prefix term in double quotation marks (““) and an asterisk (*) before the ending quotation mark. All text starting with the simple term specified before the asterisk is matched. The asterisk matches zero, one or more characters (of the root word or words in the word or phrase). When <prefix_term> is a phrase, each word contained in the phrase is considered to be a separate prefix. Therefore, a query specifying a prefix term of “local wine *” matches any rows with the text of “local winery”, “locally wined and dined”, and so on.
<proximity_term>
Specifies a match of words or phrases that must be close to one another. <proximity_term> operates similarly to the AND operator: both require that more than one word or phrase exist in the column being searched. As the words in <proximity_term> appear closer together, the better the match.

NEAR | ~

Indicates that the word or phrase on the left side of the NEAR or ~ operator should be approximately close to the word or phrase on the right side of the NEAR or ~ operator. Multiple proximity terms can be chained, for example:

a NEAR b NEAR c

This means word or phrase a should be near word or phrase b, which should be near word or phrase c.

Microsoft® SQL Server™ ranks the distance between the left and right word or phrase. A low rank value (for example, 0) indicates a large distance between the two. If the specified words or phrases are far apart from each other, the query is considered to be satisfied; however, the query has a very low (0) rank value. However, if <contains_search_condition> consists of only one or more NEAR proximity terms, SQL Server does not return rows with a rank value of 0. For more information about ranking, see CONTAINSTABLE.

<simple_term>
Specifies a match for an exact word (one or more characters without spaces or punctuation in single-byte languages) or a phrase (one or more consecutive words separated by spaces and optional punctuation in single-byte languages). Examples of valid simple terms are “blue berry”, blueberry, and “Microsoft SQL Server”. Phrases should be enclosed in double quotation marks (““). Words in a phrase must appear in the same order as specified in <contains_search_condition> as they appear in the database column. The search for characters in the word or phrase is case insensitive. Noise words (such as a, and, or the) in full-text indexed columns are not stored in the full-text index. If a noise word is used in a single word search, SQL Server returns an error message indicating that only noise words are present in the query. SQL Server includes a standard list of noise words in the directory \Mssql7\Ftdata\Sqlserver\Config.

Punctuation is ignored. Therefore, CONTAINS(testing, “computer failure”) matches a row with the value, “Where is my computer? Failure to find it would be expensive.”.

n
Is a placeholder indicating that multiple contains search conditions and terms within them can be specified.
Examples
A. Use CONTAINS with <simple_term>

    This example finds all products with a price of $15.00 that contains the word bottles.

    USE Northwind

    GO

    SELECT ProductName

    FROM Products

    WHERE UnitPrice = 15.00

        AND CONTAINS(QuantityPerUnit, 'bottles')

    GO

    B. Use CONTAINS and phrase in <simple_term>

      This example returns all products that contain either the phrase “sasquatch ale” or “steeleye stout”.

      USE Northwind

      GO

      SELECT ProductName

      FROM Products

      WHERE CONTAINS(ProductName, ' "Sasquatch ale" OR "steeleye stout" ')

      GO

      C. Use CONTAINS with <prefix_term>

        This example returns all product names with at least one word starting with the prefix spread in the ProductName column.

        USE Northwind

        GO

        SELECT ProductName

        FROM Products

        WHERE CONTAINS(ProductName, ' "spread*" ')

        GO

        D. Use CONTAINS and OR with <prefix_term>

        This example returns all category descriptions containing the strings sea or bread.

        USE Northwind

        SELECT CategoryName

        FROM Categories

        WHERE CONTAINS(Description, '"sea*" OR "bread*"')

        GO

        E. Use CONTAINS with <proximity_term>

          This example returns all product names that have the word Boysenberry near the word spread.

          USE Northwind

          GO

          SELECT ProductName

          FROM Products

          WHERE CONTAINS(ProductName, 'spread NEAR Boysenberry')

          GO

          F. Use CONTAINS with <generation_term>

          This example searches for all products with words of the form dry: dried, drying, and so on.

          USE Northwind

          GO

          SELECT ProductName

          FROM Products

          WHERE CONTAINS(ProductName, ' FORMSOF (INFLECTIONAL, dry) ')

          GO

          G. Use CONTAINS with <weighted_term>

          This example searches for all product names containing the words spread, sauces, or relishes and different weightings are given to each word.

          USE Northwind

          GO

          SELECT CategoryName, Description

          FROM Categories

          WHERE CONTAINS(Description, 'ISABOUT (spread weight (.8),

              sauces weight (.4), relishes weight (.2) )' )

          GO

          See Also
          CONTAINSTABLE | FREETEXTTABLE
FREETEXT | WHERE


CONTAINSTABLE

Returns a table of zero, one, or more rows for those columns containing character-based data types for precise or “fuzzy” (less precise) matches to single words and phrases, the proximity of words within a certain distance of one another, or weighted matches. CONTAINSTABLE can be referenced in the FROM clause of a SELECT statement as if it were a regular table name.

Queries using CONTAINSTABLE specify contains-type full-text queries that return a relevance ranking value (RANK) for each row. The CONTAINSTABLE function uses the same search conditions as the CONTAINS predicate.

Syntax

CONTAINSTABLE (table, {column | *}, '<contains_search_condition>')

<contains_search_condition> ::=
{
| <generation_term>
| <prefix_term>
| <proximity_term>
| <simple_term>
| <weighted_term>
}
| { (<contains_search_condition>)
 {AND | AND NOT | OR} <contains_search_condition> […n]
}

<weighted_term> ::=
 ISABOUT
( { {
<generation_term>
| <prefix_term>
| <proximity_term>
| <simple_term>
}
[WEIGHT (weight_value)]
} [,…n]
)

<generation_term> ::=
 FORMSOF (INFLECTIONAL, <simple_term> [,…n] )

<prefix term> ::=
{ "word * " | "phrase * " }

<proximity_term> ::=
 {<simple_term> | <prefix_term>}
{ {NEAR | ~} {<simple_term> | <prefix_term>} } […n]

<simple_term> ::=
 word | " phrase "

Arguments
table
Is the name of the table that has been marked for full-text querying. table can be a one-part database object name or a multipart database object name. For more information, see Transact-SQL Syntax Conventions.
column
Is the name of the column to search, which resides in table. Columns of the character string data types are valid full-text searching columns.
*
Specifies that all columns in the table that have been registered for full-text searching should be used to search for the given contains search condition(s).
<contains_search_condition>
Specifies some text to search for in column. Variables cannot be used for the search condition. For more information, see CONTAINS.
Remarks

The table returned has a column named KEY that contains full-text key values. Each full-text indexed table has a column whose values are guaranteed to be unique and the values returned in the KEY column are the full-text key values of the rows that match the selection criteria specified in the contains search condition. The TableFulltextKeyColumn property, obtained from the OBJECTPROPERTY function, provides the identity for this unique key column. To obtain the rows you want from the original table, specify a join with the CONTAINSTABLE rows. The typical form of the FROM clause for a SELECT statement using CONTAINSTABLE is:

SELECT select_list

FROM table AS FT_TBL INNER JOIN

    CONTAINSTABLE(table, column, contains_search_condition) AS KEY_TBL

    ON FT_TBL.unique_key_column = KEY_TBL.[KEY]

The table produced by CONTAINSTABLE includes a column named RANK. The RANK column is a value (between 0 and 1000) for each row indicating how well a row matched the selection criteria. This rank value is typically used in one of these ways in the SELECT statement:

  • In the ORDER BY clause to return the highest-ranking rows as the first rows in the table.
  • In the select list to see the rank value assigned to each row.
  • In the WHERE clause to filter out rows with low rank values.
Permissions

Execute permissions are available only by users with the appropriate SELECT privileges on the table or the referenced table’s columns.

Examples
A. Return rank values using CONTAINSTABLE

This example searches for all product names containing the words breads, fish, or beers, and different weightings are given to each word. For each returned row matching this search criteria, the relative closeness (ranking value) of the match is shown. In addition, the highest ranking rows are returned first.

USE Northwind

GO

SELECT FT_TBL.CategoryName, FT_TBL.Description, KEY_TBL.RANK

FROM Categories AS FT_TBL INNER JOIN

    CONTAINSTABLE(Categories, Description,

    'ISABOUT (breads weight (.8),

    fish weight (.4), beer weight (.2) )' ) AS KEY_TBL

    ON FT_TBL.CategoryID = KEY_TBL.[KEY]

ORDER BY KEY_TBL.RANK DESC

GO

B. Return rank values greater than specified value using CONTAINSTABLE

    This example returns the description and category name of all food categories for which the Description column contains the words “sweet and savory” near either the word sauces or the word candies. All rows with a category name of Seafood are disregarded. Only rows with a rank value of 5 or higher are returned.

    USE Northwind

    GO

    SELECT FT_TBL.Description,

        FT_TBL.CategoryName,

        KEY_TBL.RANK

    FROM Categories AS FT_TBL INNER JOIN

        CONTAINSTABLE (Categories, Description,

            '("sweet and savory" NEAR sauces) OR

            ("sweet and savory" NEAR candies)'

        ) AS KEY_TBL

        ON FT_TBL.CategoryID = KEY_TBL.[KEY]

    WHERE KEY_TBL.RANK > 5

        AND FT_TBL.CategoryName <> 'Seafood'

    ORDER BY KEY_TBL.RANK DESC

    See Also
    CONTAINS | WHERE
SELECT | Rowset Functions


CONTINUE

Restarts a WHILE loop. Any statements after the CONTINUE keyword are ignored. CONTINUE is often, but not always, activated by an IF test. For more information, see WHILE and Control-of-Flow Language.


Control-of-Flow Language

The table shows the Transact-SQL control-of-flow keywords.

Keyword | Description
BEGIN …END | Defines a statement block.
BREAK | Exits the innermost WHILE loop.
CONTINUE | Restarts a WHILE loop.
GOTO label | Continues processing at the statement following the label as defined by label.
IF …ELSE | Defines conditional, and optionally, alternate execution when a condition is FALSE.
RETURN | Exits unconditionally.
WAITFOR | Sets a delay for statement execution.
WHILE | Repeats statements while a specific condition is TRUE.

Other Transact-SQL statements that can be used with Control-of-flow Language statements are:

/*…*/ (Comment) | EXECUTE
-- (Comment) | PRINT
CASE | RAISERROR
DECLARE @local_variable |


COS

A mathematical function that returns the trigonometric cosine of the given angle (in radians) in the given expression.

Syntax

COS(float_expression)

Arguments
float_expression
Is an expression of type float.
Return Types

float

Examples

This example returns the COS of the given angle.

DECLARE @angle float

SET @angle = 14.78

SELECT 'The COS of the angle is: ' + CONVERT(varchar,COS(@angle))

GO

Here is the result set:

The COS of the angle is: -0.599465

(1 row(s) affected)

See Also

Mathematical Functions


COT

A mathematical function that returns the trigonometric cotangent of the specified angle (in radians) in the given float expression.

Syntax

COT(float_expression)

Arguments
float_expression
Is an expression of type float.
Return Types

float

Examples

This example returns the COT for the given angle.

DECLARE @angle float

SET @angle = 124.1332

SELECT 'The COT of the angle is: ' + CONVERT(varchar,COT(@angle))

GO

Here is the result set:

The COT of the angle is: -0.040312

(1 row(s) affected)

See Also

Mathematical Functions


COUNT

Returns the number of items in a group.

Syntax

COUNT({[ALL | DISTINCT] expression] | *})

Arguments
ALL
Applies the aggregate function to all values. ALL is the default.
DISTINCT
Specifies that COUNT returns the number of unique nonnull values.
expression
Is an expression of any type except uniqueidentifier, text, image, or ntext. Aggregate functions and subqueries are not permitted.
*
Specifies that all rows should be counted to return the total number of rows in a table. COUNT(*) takes no parameters and cannot be used with DISTINCT. COUNT(*) does not require an expression parameter because, by definition, it does not use information about any particular column. COUNT(*) returns the number of rows in a specified table without eliminating duplicates. It counts each row separately, including rows that contain null values.

Important Distinct aggregates, for example AVG(DISTINCT column_name), COUNT(DISTINCT column_name), MAX(DISTINCT column_name), MIN(DISTINCT column_name), and SUM(DISTINCT column_name), are not supported when using CUBE or ROLLUP. If used, Microsoft® SQL Server™ returns an error message and cancels the query.

Return Types

int

Remarks

COUNT(*) returns the number of items in a group, including NULL values and duplicates.

COUNT(ALL expression) evaluates expression for each row in a group and returns the number of non-NULL values.

COUNT(DISTINCT expression) evaluates expression for each row in a group and returns the number of unique, non-NULL values.

Examples
A. Use COUNT and DISTINCT

This example finds the number of different cities in which authors live.

USE pubs

GO

SELECT COUNT(DISTINCT city)

FROM authors

GO

Here is the result set:

-----------

16

(1 row(s) affected)

B. Use COUNT(*)

This example finds the total number of books and titles.

USE pubs

GO

SELECT COUNT(*)

FROM titles

GO

Here is the result set:

-----------

18

(1 row(s) affected)

C. Use COUNT(*) with other aggregates

The example shows that COUNT(*) can be combined with other aggregate functions in the select list.

USE pubs

GO

SELECT COUNT(*), AVG(price)

FROM titles

WHERE advance > $1000

GO

Here is the result set:

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

15          14.42

(1 row(s) affected)

See Also

Aggregate Functions


CREATE DATABASE

Creates a new database and the files used to store the database, or attaches a database from the files of a previously created database.

Syntax

CREATE DATABASE database_name
[ ON [PRIMARY]
[ <filespec> [,…n] ]
[, <filegroup> [,…n] ]
]
[ LOG ON { <filespec> [,…n]} ]
[ FOR LOAD | FOR ATTACH ]

<filespec> ::=

( [ NAME = logical_file_name, ]
FILENAME = 'os_file_name'
[, SIZE = size]
[, MAXSIZE = { max_size | UNLIMITED } ]
[, FILEGROWTH = growth_increment] ) [,…n]

<filegroup> ::=

FILEGROUP filegroup_name <filespec> [,…n]

Arguments
database_name
Is the name of the new database. Database names must be unique within a server and conform to the rules for identifiers. database_name can be up to 128 characters, unless no logical name is specified for the log. If no logical log file name is specified, Microsoft® SQL Server™ generates a logical name by appending a suffix to database_name. This limits database_name to 123 characters so that the generated logical log file name is less than 128 characters.
ON
Specifies that the disk files used to store the data portions of the database (data files) are defined explicitly. The keyword is followed by a comma-delimited list of <filespec> items defining the data files for the primary filegroup. The list of files in the primary filegroup can be followed by an optional, comma-delimited list of <filegroup> items defining user filegroups and their files.
PRIMARY
Specifies that the associated <filespec> list defines the primary file. The primary filegroup contains all of the database system tables. It also contains all objects not assigned to user filegroups. The first <filespec> entry in the primary filegroup becomes the primary file, which is the file containing the logical start of the database and its system tables. A database can have only one primary file. If PRIMARY is not specified, the first file listed in the CREATE DATABASE statement becomes the primary file.
n
Is a placeholder indicating that multiple files can be specified for the new database.
LOG ON
Specifies that the disk files used to store the database log (log files) are explicitly defined. The keyword is followed by a comma-delimited list of <filespec> items defining the log files. If LOG ON is not specified, a single log file is automatically created with a system-generated name and a size that is 25 percent of the sum of the sizes of all the data files for the database.
FOR LOAD
This clause is supported for compatibility with earlier versions of Microsoft SQL Server. The database is created with the dbo use only database option turned on, and the status is set to loading. This is not needed in SQL Server version 7.0 because the RESTORE statement can re-create a database as part of the restore operation.

If you attach a database to a server other than the server from which the database was detached, and the detached database was enabled for replication, you should run sp_removedbreplication to remove replication from the database.

FOR ATTACH
Specifies that a database is attached from an existing set of operating system files. There must be a <filespec> entry specifying the first primary file. The only other <filespec> entries needed are those for any files that have a different path from when the database was first created or last attached. A <filespec> entry must be specified for these files. The database being attached must have been created using the same code page and sort order as SQL Server. Use the sp_attach_db system stored procedure instead of using CREATE DATABASE FOR ATTACH directly. Use CREATE DATABASE FOR ATTACH only when you must specify more than 16 <filespec> items.
NAME
Specifies the logical name for the file defined by the <filespec>. The NAME parameter is not required when FOR ATTACH is specified.
logical_file_name
Is the name used to reference the file in any Transact-SQL statements executed after the database is created. logical_file_name must be unique in the database and conform to the rules for identifiers. The name can be a character or Unicode constant, or a regular or delimited identifier.
FILENAME
Specifies the operating-system file name for the file defined by the <filespec>.
'os_file_name'
Is the path and file name used by the operating system when it creates the physical file defined by the <filespec>. The path in os_file_name must specify a directory on the server in which SQL Server is installed. os_file_name cannot specify a directory in a compressed file system.

If the file is being created on a raw partition, os_file_name must specify only the drive letter of an existing raw partition. Only one file can be created on each raw partition. Files on raw partitions do not autogrow; therefore, the MAXSIZE and FILEGROWTH parameters are not needed when os_file_name specifies a raw partition.

SIZE
Specifies the size of the file defined in the <filespec>. When a SIZE parameter is not supplied in the <filespec> for a primary file, SQL Server uses the size of the primary file in the model database. When a SIZE parameter is not specified in the <filespec> for a secondary or log file, SQL Server makes the file 1 MB.
size
Is the initial size of the file defined in the <filespec>. The KB and MB suffixes can be used to specify kilobytes or megabytes, the default is MB. Specify a whole number; do not include a decimal. The minimum value for size is
512 KB. If size is not specified, the default is 1 MB. The size specified for the primary file must be at least as large as the primary file of the model database.
MAXSIZE
Specifies the maximum size to which the file defined in the <filespec> can grow.
max_size
Is the maximum size to which the file defined in the <filespec> can grow. The KB and MB suffixes can be used to specify kilobytes or megabytes, the default is MB. Specify a whole number; do not include a decimal. If max_size is not specified, the file grows until the disk is full.

Note The Microsoft Windows NT® S/B system log warns the SQL Server system administrator if a disk is about to become full.

UNLIMITED
Specifies that the file defined in the <filespec> grows until the disk is full.
FILEGROWTH
Specifies the growth increment of the file defined in the <filespec>. The FILEGROWTH setting for a file cannot exceed the MAXSIZE setting.
growth_increment
Is the amount of space added to the file each time new space is needed. Specify a whole number; do not include a decimal. A value of 0 indicates no growth. The value can be specified in MB, KB, or %. If a number is specified without an MB, KB, or % suffix, the default is MB. When % is specified, the growth increment size is the specified percentage of the size of the file at the time the increment occurs. If FILEGROWTH is not specified, the default value is 10% and the minimum value is 64 KB. The size specified is rounded to the nearest 64 KB.
Remarks

You can use one CREATE DATABASE statement to create a database and the files that store the database. SQL Server implements the CREATE DATABASE statement in two steps:

  1. SQL Server uses a copy of the model database to initialize the database and its metadata.
  2. SQL Server then fills the rest of the database with empty pages, except for pages that have internal data recording how the space is used in the database.

Any user-defined objects in the model database are therefore copied to all newly created databases. You can add to the model database any objects (such as tables, views, stored procedures, data types, and so on) that you want to have in all your databases.

Each new database inherits the database option settings from the model database (unless FOR ATTACH is specified). For example, the database option select into/bulkcopy is set to OFF in model and any new databases you create. If you use sp_dboption to change the options for the model database, these option settings will be in effect for any new databases you create. If FOR ATTACH is specified on the CREATE DATABASE statement, the new database inherits the database option settings of the original database.

A maximum of 32,767 databases can be specified on a server.

There are three types of files used to store a database:

  • The primary file contains the startup information for the database. The primary file is also used to store data. Every database has one primary file.
  • Secondary files hold all of the data that does not fit in the primary data file. Databases need not have any secondary data files if the primary file is large enough to hold all of the data in the database. Other databases may be large enough to need multiple secondary data files, or they may use secondary files on separate disk drives to spread the data across multiple disks.
  • Transaction log files hold the log information used to recover the database. There must be at least one transaction log file for each database, although there may be more than one. The minimum size for a transaction log file is 512 KB.

Every database has at least two files, a primary file and a transaction log file.

Although os_file_name can be any valid operating-system file name, the name more clearly reflects the purpose of the file if you use the following recommended extensions.

File type | Recommended file name extension
Primary data file | .mdf
Secondary data file | .ndf
Transaction log file | .ldf

Note The master database should be backed up after a user database is created.

Fractions cannot be specified in the SIZE, MAXSIZE, and FILEGROWTH parameters. To specify a fraction of a megabyte in the size parameters, convert to kilobytes by multiplying the number by 1024. For example, specify 1536 KB instead of 1.5MB (1.5 times 1024 equals 1536).

When a simple CREATE DATABASE database_name statement is specified with no additional parameters, the database is made the same size as the model database.

All databases have at least a primary filegroup. All system tables are allocated in the primary filegroup. A database can also have user-defined filegroups. If an object is created with an ON filegroup clause specifying a user-defined filegroup, then all the pages for the object are allocated from the specified filegroup. The pages for all user objects created without an ON filegroup clause, or with an ON DEFAULT clause, are allocated from the default filegroup. When a database is first created the primary filegroup is the default filegroup. You can specify a user-defined filegroup as the default filegroup using ALTER DATABASE:

ALTER DATABASE database_name MODIFY FILEGROUP filegroup_name DEFAULT

Each database has an owner who has the ability to perform special activities in the database. The owner is the user who creates the database. The database owner can be changed through sp_changedbowner.

To display a report on a database or on all the databases on a server running SQL Server, execute sp_helpdb. For a report on the space used in a database, use sp_spaceused. For a report on the filegroups in a database use sp_helpfilegroup, and use sp_helpfile for a report of the files in a database.

Earlier versions of SQL Server used DISK INIT statements to create the files for a database before the CREATE DATABASE statement was executed. For backward compatibility with earlier versions of SQL Server, the CREATE DATABASE statement can also create a new database on files or devices that were created with the DISK INIT statement.

Permissions

CREATE DATABASE permission defaults to members of the sysadmin and dbcreator fixed server roles. Members of the sysadmin and securityadmin fixed server roles can grant CREATE DATABASE permissions to other logins. Members of the sysadmin and dbcreator fixed server role can add other logins to the dbcreator role. CREATE DATABASE permission must be explicitly granted; it is not granted by the GRANT ALL statement.

CREATE DATABASE permission is usually limited to a few logins to maintain control over disk usage on the computer running SQL Server.

Examples
A. Create a database specifying the data and transaction log files

This example creates a database called Sales. Because the keyword PRIMARY is not used, the first file (Sales_dat) defaults to being the primary file. Because neither MB or KB are specified in the SIZE parameter for the Sales_dat file, it defaults to MB and is allocated in megabytes. The Sales_log file is allocated in megabytes because the MB suffix is explicitly stated in the SIZE parameter.

USE master

GO

CREATE DATABASE Sales

ON

( NAME = Sales_dat,

  FILENAME = 'c:\mssql7\data\saledat.mdf',

  SIZE = 10,

  MAXSIZE = 50,

  FILEGROWTH = 5 )

LOG ON

( NAME = 'Sales_log',

  FILENAME = 'c:\mssql7\data\salelog.ldf',

  SIZE = 5MB,

  MAXSIZE = 25MB,

  FILEGROWTH = 5MB )

GO

B. Create a database specifying multiple data and transaction log files

    This example creates a database called Archive with three 100-MB data files and two 100-MB transaction log files. The primary file is the first file in the list and is explicitly specified with the PRIMARY keyword. The transaction log files are specified following the LOG ON keywords. Note the extensions used for the files in the FILENAME option: .mdf is used for primary files, .ndf is used for the secondary files, and .ldf is used for transaction log files.

    USE master

    GO

    CREATE DATABASE Archive

    ON

    PRIMARY ( NAME = Arch1,

              FILENAME = 'c:\mssql7\data\archdat1.mdf',

              SIZE = 100MB,

              MAXSIZE = 200,

              FILEGROWTH = 20),

    ( NAME = Arch2,

      FILENAME = 'c:\mssql7\data\archdat2.ndf',

      SIZE = 100MB,

      MAXSIZE = 200,

      FILEGROWTH = 20),

    ( NAME = Arch3,

      FILENAME = 'c:\mssql7\data\archdat3.ndf',

      SIZE = 100MB,

      MAXSIZE = 200,

      FILEGROWTH = 20)

    LOG ON

    ( NAME = Archlog1,

      FILENAME = 'c:\mssql7\data\archlog1.ldf',

      SIZE = 100MB,

      MAXSIZE = 200,

      FILEGROWTH = 20),

    ( NAME = Archlog2,

      FILENAME = 'c:\mssql7\data\archlog2.ldf',

      SIZE = 100MB,

      MAXSIZE = 200,

      FILEGROWTH = 20)

    GO

    C. Create a simple database

    This example creates a database called Products and specifies a single file. The file specified defaults to being the primary file, and a 1-MB transaction log file is automatically created. Because neither MB or KB are specified in the SIZE parameter for the primary file, the primary file is allocated in megabytes. Because there is so <filespec> for the transaction log file, the transaction log file has no MAXSIZE and can grow to fill all available space on the disk.

    USE master

    GO

    CREATE DATABASE Products

    ON

    ( NAME = prods_dat,

      FILENAME = 'c:\mssql7\data\prods.mdf',

      SIZE = 4,

      MAXSIZE = 10,

      FILEGROWTH = 1 )

    GO

    D. Create a database without specifying files

    This example creates a database named mytest and creates a corresponding primary and transaction log file. Because the statement has no <filespec> items, the primary database file is the size of the model database primary file. The transaction log is the size of the model database transaction log file. Because MAXSIZE is not specified, the files can grow to fill all available space on the disk.

    CREATE DATABASE mytest

    E. Create a database without specifying SIZE

      This example creates a database named products2. The file prods2_dat defaults to being the primary file with a size equal to the size of the primary file in the model database. The transaction log file is created automatically and is 25 percent of the size of the primary file or 512 KB, whichever is larger. Because MAXSIZE is not specified, the files can grow to fill all available space on the disk.

      USE master

      GO

      CREATE DATABASE Products2

      ON

      ( NAME = prods2_dat,

        FILENAME = 'c:\mssql7\data\prods2.mdf' )

      GO

      F. Create a database with filegroups

      This example creates a database named sales with three filegroups:

      • The primary filegroup with the files Spri1_dat and Spri2_dat. The FILEGROWTH increments for these files is specified as 15%.
      • A filegroup named SalesGroup1 with the files SGrp1Fi1 and SGrp1Fi2.
      • A filegroup named SalesGroup2 with the files SGrp2Fi1 and SGrp2Fi2.

      CREATE DATABASE Sales

      ON PRIMARY

      ( NAME = SPri1_dat,

        FILENAME = 'c:\mssql7\data\SPri1dat.mdf',

        SIZE = 10,

        MAXSIZE = 50,

        FILEGROWTH = 15% ),

      ( NAME = SPri2_dat,

        FILENAME = 'c:\mssql7\data\SPri2dt.ndf',

        SIZE = 10,

        MAXSIZE = 50,

        FILEGROWTH = 15% ),

      FILEGROUP SalesGroup1

      ( NAME = SGrp1Fi1_dat,

        FILENAME = 'c:\mssql7\data\SG1Fi1dt.ndf',

        SIZE = 10,

        MAXSIZE = 50,

        FILEGROWTH = 5 ),

      ( NAME = SGrp1Fi2_dat,

        FILENAME = 'c:\mssql7\data\SG1Fi2dt.ndf',

        SIZE = 10,

        MAXSIZE = 50,

        FILEGROWTH = 5 ),

      FILEGROUP SalesGroup2

      ( NAME = SGrp2Fi1_dat,

        FILENAME = 'c:\mssql7\data\SG2Fi1dt.ndf',

        SIZE = 10,

        MAXSIZE = 50,

        FILEGROWTH = 5 ),

      ( NAME = SGrp2Fi2_dat,

        FILENAME = 'c:\mssql7\data\SG2Fi2dt.ndf',

        SIZE = 10,

        MAXSIZE = 50,

        FILEGROWTH = 5 )

      LOG ON

      ( NAME = 'Sales_log',

        FILENAME = 'c:\mssql7\data\salelog.ldf',

        SIZE = 5MB,

        MAXSIZE = 25MB,

        FILEGROWTH = 5MB )

      GO

      G. Attach a database

      Example B created a database named Archive with the following physical files:

      c:\mssql7\data\archdat1.mdf

      c:\mssql7\data\archdat2.ndf

      c:\mssql7\data\archdat3.ndf

      c:\mssql7\data\archlog1.ldf

      c:\mssql7\data\archlog2.ldf

      The database can be detached using the sp_detach_db stored procedure, and then reattached using CREATE DATABASE with the FOR ATTACH clause:

      sp_detach_db Archive

      GO

      CREATE DATABASE Archive

      ON PRIMARY (FILENAME = 'c:\mssql7\data\archdat1.mdf')

      FOR ATTACH

      GO

      H. Use raw partitions

      This example creates a database called Employees using raw partitions. The raw partitions must exist when the statement is executed, and only one file can go on each raw partition.

      USE master

      GO

      CREATE DATABASE Employees

      ON

      ( NAME = Empl_dat,

        FILENAME = 'f:',

        SIZE = 10,

        MAXSIZE = 50,

        FILEGROWTH = 5 )

      LOG ON

      ( NAME = 'Sales_log',

        FILENAME = 'g:',

        SIZE = 5MB,

        MAXSIZE = 25MB,

        FILEGROWTH = 5MB )

      GO

      See Also
      ALTER DATABASE | sp_removedbreplication
DROP DATABASE | sp_helpfile
sp_attach_db | sp_helpfilegroup
sp_changedbowner | sp_renamedb
sp_detach_db | sp_spaceused
sp_helpdb |


CREATE DEFAULT

Creates an object called a default. When bound to a column or a user-defined data type, a default specifies a value to be inserted into the column to which the object is bound (or into all columns, in the case of a user-defined data type) when no value is explicitly supplied during an insert. Defaults, a backward compatibility feature, perform some of the same functions as default definitions created using the DEFAULT keyword of ALTER or CREATE TABLE statements. Default definitions are the preferred, standard way to restrict column data because the definition is stored with the table and automatically dropped when the table is dropped. A default is beneficial, however, when the default is used multiple times for multiple columns.

Syntax

CREATE DEFAULT default
AS constant_expression

Arguments
default
Is the name of the default. Default names must conform to the rules for identifiers. Specifying the default owner name is optional.
constant_expression
Is an expression that contains only constant values (it cannot include the names of any columns or other database objects). Any constant, built-in function, or mathematical expression can be used. Enclose character and date constants in single quotation marks (‘); monetary, integer, and floating-point constants do not require quotation marks. Binary data must be preceded by 0x, and monetary data must be preceded by a dollar sign ($). The default value must be compatible with the data type of the column.
Remarks

A default can be created only in the current database. Within a database, default names must be unique by owner. After a default has been created, use sp_bindefault to bind it to a column or to a user-defined data type.

If the default is not compatible with the column to which it is bound, Microsoft® SQL Server™ generates an error message when trying to insert the default value. For example, N/A cannot be used as a default for a numeric column.

If the default value is too long for the column to which it is bound, the value is truncated.

CREATE DEFAULT statements cannot be combined with other Transact-SQL statements in a single batch.

A default must be dropped before creating a new one of the same name, and the default must be unbound by executing sp_unbindefault before it is dropped.

If a column has both a default and a rule associated with it, the default value must not violate the rule. A default that conflicts with a rule is never inserted, and SQL Server generates an error message each time it attempts to insert the default.

After bound to a column, a default value is inserted when:

  • A value is not explicitly inserted.
  • Either the DEFAULT VALUES or DEFAULT keywords are used with INSERT to insert default values. For more information and examples, see INSERT.

If NOT NULL is specified when creating a column and a default is not created for it, an error message is generated whenever a user fails to make an entry in that column. This table illustrates the relationship between the existence of a default and the definition of a column as NULL or NOT NULL. The entries in the table show the result.

Note Whether SQL Server interprets an empty string as a single space or as a true empty string is controlled by the setting of sp_dbcmptlevel. If the compatibility level is less than or equal to 65, SQL Server interprets empty strings as single spaces. If the compatibility level is equal to 70, SQL Server interprets empty strings as empty strings. For more information, see sp_dbcmptlevel.

Column definition | No entry, no default | No entry, default | Enter NULL, no default | Enter NULL, default
NULL | NULL | default | NULL | NULL
NOT NULL | error | default | error | error

To rename a default, use sp_rename. For a report on a default, use sp_help.

Permissions

CREATE DEFAULT permissions default to members of the db_owner fixed database role, who can transfer it to other users.

Examples
A. Create a simple character default

This example creates a character default of unknown.

USE pubs

GO

CREATE DEFAULT phonedflt AS 'unknown'

B. Bind a default

    This example binds the default created in example A. The default takes effect only if there is no entry in the phone column of the authors table. Note that no entry is not the same as an explicit null value.

    Note Because a default named phonedflt does not exist, the following Transact-SQL statement fails. This example is for illustration only.

    USE pubs

    GO

    sp_bindefault phonedflt, 'authors.phone'

    See Also
    ALTER TABLE | INSERT
CREATE RULE | sp_bindefault
CREATE TABLE | sp_help
DROP DEFAULT | sp_helptext
DROP RULE | sp_rename
Expressions | sp_unbindefault


CREATE INDEX

Creates an index on a given table. This statement either changes the physical ordering of the table or provides the optimizer with a logical ordering of the table to increase query efficiency. When an index is created for the primary key, use the table- and column-level PRIMARY KEY constraints by specifying the PRIMARY KEY keywords provided with either the CREATE TABLE or ALTER TABLE statements.

Only the table owner can create indexes on that table. The owner of a table can create an index at any time, whether or not there is data in the table. Indexes can be created on tables in another database by specifying a qualified database name.

Syntax

CREATE [UNIQUE] [CLUSTERED | NONCLUSTERED]
INDEX index_name ON table (column [,…n])
[WITH
[PAD_INDEX]
[[,] FILLFACTOR = fillfactor]
[[,] IGNORE_DUP_KEY]
[[,] DROP_EXISTING]
[[,] STATISTICS_NORECOMPUTE]
]
[ON filegroup]

Arguments
UNIQUE
Creates a unique index (one in which no two rows are permitted to have the same index value). Microsoft® SQL Server™ checks for duplicate values when the index is created (if data already exists) and checks each time data is added with an INSERT or UPDATE statement. If duplicate key values exist, the CREATE INDEX statement is canceled and an error message giving the first duplicate is returned. A unique index cannot be created on a single column or multiple columns (composite index) in which the complete key (all columns of that key) is NULL in more than one row; these are treated as duplicate values for indexing purposes.

When a unique index exists, UPDATE or INSERT statements that would generate duplicate key values are rolled back, and SQL Server displays an error message. This is true even if the UPDATE or INSERT statement changes many rows but causes only one duplicate. If an attempt is made to enter data for which there is a unique index and the IGNORE_DUP_KEY clause is specified, only the rows violating the UNIQUE index fail. When processing an UPDATE statement, IGNORE_DUP_KEY has no effect. (For more information, see the IGNORE_DUP_KEY clause, later in this topic.)

SQL Server does not allow the creation of a unique index on columns that already include duplicate values, whether or not IGNORE_DUP_KEY is set. If attempted, SQL Server displays an error message; duplicates must be eliminated before a unique index can be created on the column(s).

CLUSTERED
Creates an object where the physical order of rows is the same as the indexed order of the rows, and the bottom (leaf) level of the clustered index contains the actual data rows. Because nonclustered indexes are rebuilt when a clustered index is created, create the clustered index before creating any nonclustered indexes.

If CLUSTERED is not specified, a nonclustered index is created.

Note Because the leaf level of a clustered index and its data pages are the same by definition, creating a clustered index and using the ON filegroup clause effectively moves a table from the file on which the table was created to the new filegroup. Before creating tables or indexes on specific filegroups, verify which filegroups are available and that they have enough empty space for the index. It is vital that the filegroup have at least 1.2 times the space required for the entire table.

NONCLUSTERED
Creates an object that specifies the logical ordering of a table. With a nonclustered index, the physical order of the rows is not the same as their indexed order. The leaf level of a nonclustered index contains index rows. Each index row contains the nonclustered key value and one or more row locators that point to the row that contains the value. If the table does not have a clustered index, the row locator is the row’s disk address. If the table does have a clustered index, the row locator is the clustered index key for the row.

Each table can have as many as 249 nonclustered indexes (regardless of how they are created: implicitly with PRIMARY KEY and UNIQUE constraints, or explicitly with CREATE INDEX). Each index can provide access to the data in a different sort order.

index_name
Is the name of the index. Index names must be unique within a table but need not be unique within a database. Index names must follow the rules of identifiers.

Note A computed column, as created in a CREATE TABLE statement, cannot be used as a key column or as part of any PRIMARY KEY, UNIQUE, FOREIGN KEY, or CHECK constraint definition.

table
Is the table that contains the column or columns to be indexed. Specifying the database and table owner names is optional.
column
Is the column or columns to which the index applies. Specify two or more column names to create a composite index on the combined values in the specified columns. List the columns to be included in the composite index (in sort-priority order) inside the parentheses after table.

Note Columns consisting of the ntext, text, image, or bit data types or computed columns cannot be specified as columns for an index, nor can functions be used.

Composite indexes are used when two or more columns are best searched as a unit or if many queries reference only the columns that are specified in the index. As many as 16 columns can be combined into a single composite index. All the columns in a composite index must be in the same table. The maximum allowable size of the combined index values is 900 bytes. (That is, the sum of the lengths of the columns that make up the composite index cannot exceed 900 bytes.)

n
Is a placeholder indicating that multiple columns can be specified for any particular index.
PAD_INDEX
Specifies the space to leave open on each page (node) in the intermediate levels of the index. The PAD_INDEX option is useful only when FILLFACTOR is specified, because PAD_INDEX uses the percentage specified by FILLFACTOR. By default, SQL Server ensures that each index page has enough empty space to accommodate at least one row of the maximum size the index can have, given the set of keys on the intermediate pages. If the percentage specified for FILLFACTOR is not large enough to accommodate one row, SQL Server internally overrides the percentage to allow the minimum.

Note The number of rows on an intermediate index page is never less than two, regardless of how low the value of FILLFACTOR.

FILLFACTOR = fillfactor
Specifies a percentage that indicates how full SQL Server should make the leaf level of each index page during index creation. When an index page fills up, SQL Server must take time to split the index page to make room for new rows, which is quite expensive. For update-intensive tables, a properly chosen FILLFACTOR value yields better update performance than an improper FILLFACTOR value. The value of the original FILLFACTOR is stored with the index in sysindexes.

When FILLFACTOR is specified, SQL Server rounds up the number of rows to be placed on each page. For example, issuing CREATE CLUSTERED INDEX … FILLFACTOR = 33 creates a clustered index with a FILLFACTOR of 33 percent. Assume that SQL Server calculates that 5.2 rows is 33 percent of the space on a page. SQL Server rounds so that 6 rows are placed on each page.

Note An explicit FILLFACTOR setting applies only when the index is first created. SQL Server does not dynamically keep the specified percentage of empty space in the pages.

User-specified FILLFACTOR values can be from 1 through 100. If no value is specified, the default value is 0. When FILLFACTOR is set to 0, only the leaf pages are filled. Space is left in nonleaf pages for at least one row. You can change the default FILLFACTOR setting by executing sp_configure.

Use a FILLFACTOR of 100 only if no INSERT or UPDATE statements will occur, such as with a read-only table. If FILLFACTOR is 100, SQL Server creates indexes with leaf pages 100 percent full. An INSERT or UPDATE made after the creation of an index with a 100 percent FILLFACTOR causes page splits for each INSERT and possibly each UPDATE.

Setting FILLFACTOR to 100 fills the leaf pages of the index to full and leaves space to accommodate one row of maximum size on the intermediate pages.

Smaller FILLFACTOR values (except 0) cause SQL Server to create new indexes with leaf pages that are not completely full. For example, a FILLFACTOR of 10 can be a reasonable choice when creating an index on a table that is known to contain a small portion of the data that it will eventually hold. Smaller FILLFACTOR values also cause each index to take more storage space.

When FILLFACTOR is set to any value other than 0 or 100, space is left in nonleaf pages for one row (two for nonunique clustered indexes), and space is left in leaf pages so that no leaf page is more full than the percentage specified by FILLFACTOR, as shown in the table.

FILLFACTOR | Intermediate page | Leaf page
0% | One free entry | 100% full
1 - 99% | One free entry | <= FILLFACTOR % full
100% | One free entry | 100% full

One free entry is the space on the page that can accommodate another index entry.

Important Creating a clustered index with a FILLFACTOR affects the amount of storage space the data occupies because SQL Server redistributes the data when it creates the clustered index.

IGNORE_DUP_KEY
Controls what happens when an attempt is made to insert a duplicate key value into a column that is part of a unique clustered index. If IGNORE_DUP_KEY was specified for the index and an INSERT statement that creates a duplicate key is executed, SQL Server issues a warning message and ignores (does not insert) the duplicate row.

If IGNORE_DUP_KEY was not specified for the index, SQL Server issues an error message and rolls back the entire INSERT statement.

A unique index cannot be created on a column that already includes duplicate values, whether or not IGNORE_DUP_KEY is set. If attempted, SQL Server displays an error message and lists the duplicate values. Eliminate the duplicate values before creating a unique index on the column.

The table shows when IGNORE_DUP_KEY can be used.

Index type | Options
Clustered | Not allowed
Unique clustered | IGNORE_DUP_KEY allowed
Nonclustered | Not allowed
Unique nonclustered | IGNORE_DUP_KEY allowed

DROP_EXISTING
Specifies that the named, preexisting clustered or nonclustered index should be dropped and the specified index rebuilt. The index name specified must be the same as a currently existing index. Because nonclustered indexes contain the clustering keys, the nonclustered indexes must be rebuilt when a clustered index is dropped. If a clustered index is re-created, the nonclustered indexes must be rebuilt to take the new set of keys into account.

The DROP_EXISTING clause enhances performance when recreating a clustered index (with either the same or a different set of keys) on a table that also has nonclustered indexes. The DROP_EXISTING clause replaces the execution of a DROP INDEX statement on the old clustered index followed by the execution of a CREATE INDEX statement for the new clustered index. The nonclustered indexes are rebuilt once, and only if the keys are different.

If the keys do not change (the same index name and columns as the original index are provided), the DROP_EXISTING clause does not sort the data again. This can be useful if the index must be compacted.

Note When executing a CREATE INDEX statement with the DROP_EXISTING clause, SQL Server assumes that the index is consistent (there is no corruption in the index). The rows in the specified index should be sorted by the specified key referenced in the CREATE INDEX statement.

STATISTICS_NORECOMPUTE
Specifies that out-of-date index statistics are not automatically recomputed. To restore automatic statistics updating, execute UPDATE STATISTICS without the NORECOMPUTE clause.

Important Disabling automatic recomputation of distribution statistics may prevent the SQL Server optimizer from picking optimal execution plans for queries involving the table.

ON filegroup
Creates the specified index on the given filegroup. The filegroup must have already been created by executing either CREATE DATABASE or ALTER DATABASE.
Remarks

Space is allocated to tables and indexes in increments of one extent (eight 8-KB pages) at a time. Each time an extent is filled, another is allocated. Indexes on very small or empty tables will use single page allocations until eight pages have been added to the index and then will switch to extent allocations. For a report on the amount of space allocated and used by an index, use sp_spaceused.

Creating a clustered index requires space available in your database equal to approximately 1.2 times the size of the data. This is space in addition to the space used by the existing table; the data is duplicated in order to create the clustered index, and the old, nonindexed data is deleted when the index is complete. When using the DROP_EXISTING clause, the space needed for the clustered index is the amount of space equal to the existing index’s space requirements.

Note Because the maximum allowable index size is 900 bytes, large char, varchar, binary, and varbinary columns (greater than 900 bytes) or nchar or nvarchar columns (greater than 450 characters) cannot be used in an index.

If CREATE INDEX is performed in the context of an explicit transaction, allocation locks are taken and held until the explicit transaction is committed. Therefore, large index creation operations may consume large amounts of memory for obtaining these locks, or the index creation may fail if lock space is exhausted. If the same CREATE INDEX statement is performed using an implicit transaction, it does not fail because allocation locks are not held for implicit transactions.

Indexes can be created on a temporary table. When the table is dropped or the session ends, all indexes and triggers are dropped.

To display a report on an object’s indexes, execute sp_helpindex.

Entire filegroups affected by a CREATE INDEX statement since the last filegroup backup must be backed up as a unit. For more information about file and filegroup backups, see BACKUP.

If CREATE INDEX is executed during a database or transaction log backup, SQL Server ends the BACKUP statement and the backup operation fails.

Permissions

CREATE INDEX permission defaults to the table owner and is not transferable.

Examples
A. Use a simple index

This example creates an index on the au_id column of the authors table.

SET NOCOUNT OFF

USE pubs

IF EXISTS (SELECT name FROM sysindexes

        WHERE name = 'au_id_ind')

    DROP INDEX authors.au_id_ind

GO

USE pubs

CREATE INDEX au_id_ind

    ON authors (au_id)

GO

B. Use a unique clustered index

This example creates an index on the employeeID column of the emp_pay table that enforces uniqueness. This index physically orders the data on disk because the CLUSTERED clause is specified.

SET NOCOUNT ON

USE pubs

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES

        WHERE TABLE_NAME = 'emp_pay')

    DROP TABLE emp_pay

GO

USE pubs

IF EXISTS (SELECT name FROM sysindexes

        WHERE name = 'employeeID_ind')

    DROP INDEX emp_pay.employeeID_ind

GO

USE pubs

GO

CREATE TABLE emp_pay

(

 employeeID int NOT NULL,

 base_pay money NOT NULL,

 commission decimal(2, 2) NOT NULL

)

INSERT emp_pay

    VALUES (1, 500, .10)

INSERT emp_pay

    VALUES (2, 1000, .05)

INSERT emp_pay

    VALUES (3, 800, .07)

INSERT emp_pay

    VALUES (5, 1500, .03)

INSERT emp_pay

    VALUES (9, 750, .06)

GO

SET NOCOUNT OFF

CREATE UNIQUE CLUSTERED INDEX employeeID_ind

    ON emp_pay (employeeID)

GO

C. Use a simple composite index

This example creates an index on the orderID and employeeID columns of the order_emp table.

SET NOCOUNT ON

USE pubs

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES

        WHERE TABLE_NAME = 'order_emp')

    DROP TABLE order_emp

GO

USE pubs

IF EXISTS (SELECT name FROM sysindexes

        WHERE name = 'emp_order_ind')

    DROP INDEX order_emp.emp_order_ind

GO

USE pubs

GO

CREATE TABLE order_emp

(

 orderID int IDENTITY(1000, 1),

 employeeID int NOT NULL,

 orderdate datetime NOT NULL DEFAULT GETDATE(),

 orderamount money NOT NULL

)

INSERT order_emp (employeeID, orderdate, orderamount)

    VALUES (5, '4/12/98', 315.19)

INSERT order_emp (employeeID, orderdate, orderamount)

    VALUES (5, '5/30/98', 1929.04)

INSERT order_emp (employeeID, orderdate, orderamount)

    VALUES (1, '1/03/98', 2039.82)

INSERT order_emp (employeeID, orderdate, orderamount)

    VALUES (1, '1/22/98', 445.29)

INSERT order_emp (employeeID, orderdate, orderamount)

    VALUES (4, '4/05/98', 689.39)

INSERT order_emp (employeeID, orderdate, orderamount)

    VALUES (7, '3/21/98', 1598.23)

INSERT order_emp (employeeID, orderdate, orderamount)

    VALUES (7, '3/21/98', 445.77)

INSERT order_emp (employeeID, orderdate, orderamount)

    VALUES (7, '3/22/98', 2178.98)

GO

SET NOCOUNT OFF

CREATE INDEX emp_order_ind

    ON order_emp (orderID, employeeID)

D. Use the FILLFACTOR option

This example uses the FILLFACTOR clause set to 100. A FILLFACTOR of 100 fills every page completely and is useful only when you know that index values in the table will never change.

SET NOCOUNT OFF

USE pubs

IF EXISTS (SELECT name FROM sysindexes

        WHERE name = 'zip_ind')

    DROP INDEX authors.zip_ind

GO

USE pubs

GO

CREATE NONCLUSTERED INDEX zip_ind

    ON authors (zip)

    WITH FILLFACTOR = 100

E. Use the IGNORE_DUP_KEY

This example creates a unique clustered index on the emp_pay table. If a duplicate key is entered, the INSERT or UPDATE statement is ignored.

SET NOCOUNT ON

USE pubs

IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES

        WHERE TABLE_NAME = 'emp_pay')

    DROP TABLE emp_pay

GO

USE pubs

IF EXISTS (SELECT name FROM sysindexes

        WHERE name = 'employeeID_ind')

    DROP INDEX emp_pay.employeeID_ind

GO

USE pubs

GO

CREATE TABLE emp_pay

(

 employeeID int NOT NULL,

 base_pay money NOT NULL,

 commission decimal(2, 2) NOT NULL

)

INSERT emp_pay

    VALUES (1, 500, .10)

INSERT emp_pay

    VALUES (2, 1000, .05)

INSERT emp_pay

    VALUES (3, 800, .07)

INSERT emp_pay

    VALUES (5, 1500, .03)

INSERT emp_pay

    VALUES (9, 750, .06)

GO

SET NOCOUNT OFF

GO

CREATE UNIQUE CLUSTERED INDEX employeeID_ind

    ON emp_pay(employeeID)

    WITH IGNORE_DUP_KEY

F. Create an index with PAD_INDEX

This example creates an index on the author’s identification number in the authors table. Without the PAD_INDEX clause, SQL Server creates leaf pages that are 10 percent full, but the pages are filled almost completely. With PAD_INDEX, the intermediate pages are also 10 percent full.

Note At least two entries appear on the index pages of unique clustered indexes when PAD_INDEX is not specified.

SET NOCOUNT OFF

USE pubs

IF EXISTS (SELECT name FROM sysindexes

        WHERE name = 'au_id_ind')

    DROP INDEX authors.au_id_ind

GO

USE pubs

CREATE INDEX au_id_ind

    ON authors (au_id)

    WITH PAD_INDEX, FILLFACTOR = 10

See Also
ALTER DATABASE | sp_autostats
CREATE DATABASE | sp_createstats
CREATE STATISTICS | sp_dbcmptlevel
CREATE TABLE | sp_dboption
Data Types | sp_helpindex
DBCC SHOW_STATISTICS | sp_spaceused
DROP INDEX | sysindexes
DROP STATISTICS | Transactions
INSERT | UPDATE
RECONFIGURE | UPDATE STATISTICS
SET |


CREATE PROCEDURE

Creates a stored procedure (a saved collection of Transact-SQL statements) that can take and return user-supplied parameters.

Procedures can be created for permanent use or for temporary use within a user’s session (local temporary procedure) or for temporary use within all user’s sessions (global temporary procedure).

Stored procedures can also be created to run automatically when Microsoft® SQL Server™ starts.

Syntax

CREATE PROC[EDURE] procedure_name [;number]
[
{@parameter data_type} [VARYING] [= default] [OUTPUT]
]
[,…n]
[WITH
{
RECOMPILE
| ENCRYPTION
| RECOMPILE, ENCRYPTION
}
]
[FOR REPLICATION]
AS
sql_statement […n]

Arguments
procedure_name
Is the name of the new stored procedure. Procedure names must conform to the rules for identifiers and must be unique within the database and its owner.

Local or global temporary procedures can be created by preceding the procedure_name with a single number sign (#procedure_name) for local temporary procedures and a double number sign (##procedure_name) for global temporary procedures. The complete name, including # or ##, cannot exceed 128 characters. Specifying the procedure owner name is optional.

;number
Is an optional integer used to group procedures of the same name so they can be dropped together with a single DROP PROCEDURE statement. For example, the procedures used with an application called orders may be named orderproc;1, orderproc;2, and so on. The statement DROP PROCEDURE orderproc drops the entire group. If the name contains delimited identifiers, the number should not be included as part of the identifier; use the appropriate delimiter around procedure only.
@parameter
Is a parameter in the procedure. One or more parameters can be declared in a CREATE PROCEDURE statement. The value of each declared parameter must be supplied by the user when the procedure is executed (unless a default for the parameter has been defined). A stored procedure can have a maximum of 1,024 parameters.

Specify a parameter name using an at sign (@) as the first character. The parameter name must conform to the rules for identifiers. Parameters are local to the procedure; the same parameter names can be used in other procedures. By default, parameters can take the place only of constants; they cannot be used in place of table names, column names, or the names of other database objects. For more information, see EXECUTE.

data_type
Is the data type of the parameter. All data types, including text and image, can be used as a parameter for a stored procedure. However, the cursor data type can only be used on OUTPUT parameters. When specifying a data type of cursor, the VARYING and OUTPUT keywords must also be specified. For more information about a list of SQL Server - supplied data types and their syntax, see Data Types.

Note There is no limit on the maximum number of output parameters that can be of cursor data type.

VARYING
Specifies the result set supported as an output parameter (constructed dynamically by the stored procedure and whose contents can vary). Applies only to cursor parameters.
default
Is a default value for the parameter. If a default is defined, the procedure can be executed without specifying a value for that parameter. The default must be a constant or it can be NULL. It can include wildcard characters (%, _, [], and [^]) if the procedure uses the parameter with the LIKE keyword.
OUTPUT
Indicates that the parameter is a return parameter. The value of this option can be returned to EXEC[UTE]. Use return parameters to return information to the calling procedure. Text parameters cannot be used as OUTPUT parameters. An output parameter using the OUTPUT keyword can be a cursor placeholder.
n
Is a placeholder indicating that up to 1,024 parameters can be specified.
{RECOMPILE | ENCRYPTION | RECOMPILE, ENCRYPTION}
RECOMPILE indicates that SQL Server does not cache a plan for this procedure and the procedure is recompiled each time it is executed. Use the RECOMPILE option when using atypical or temporary values without overriding the execution plan that is cached in memory.

When created, a stored procedure is resolved, which allows the procedure to be associated with a particular table. When that table is dropped at a later date, then all stored procedures associated with that table should be dropped and re-created to be resolved again.

The WITH RECOMPILE option does not perform the resolution process; therefore, using WITH RECOMPILE with new tables after the procedure was originally created is not useful. Executing the WITH RECOMPILE option allows SQL Server to rebuild the query plan that SQL Server uses each time the procedure is executed.

Note If any constraints are added or altered, any stored procedures referencing the table are automatically recompiled.

ENCRYPTION indicates that SQL Server encrypts the syscomments table entry containing the text of the CREATE PROCEDURE statement.

Note During an upgrade, SQL Server uses the encrypted comments stored in syscomments to re-create encrypted procedures.

FOR REPLICATION
This option is mutually exclusive of the WITH RECOMPILE option. Specifies that stored procedures created for replication cannot be executed on the subscribing server and is used when creating a filter stored procedure that is executed only by replication.
AS
Specifies the actions the procedure is to take.
sql_statement
Is any number and type of Transact-SQL statements to be included in the procedure. Some limitations do apply. For more information, see sql_statement Limitations later in this topic.
n
Is a placeholder indicating that multiple Transact-SQL statements may be included in this procedure. For more information, see sql_statement Limitations later in this topic.
Remarks

The maximum size of a stored procedure is 128 MB.

A user-defined stored procedure can be created only in the current database (except for temporary procedures, which are always created in tempdb). The CREATE PROCEDURE statement cannot be combined with other Transact-SQL statements in a single batch.

Parameters are nullable, by default. If a NULL parameter value is passed and that parameter is used (in a CREATE or ALTER TABLE statement) in which the column referenced does not allow NULLs, SQL Server generates an error. To prevent passing a NULL parameter value to a column that does not allow NULLs, either add programming logic to the procedure or use a default value (with the DEFAULT keyword of CREATE or ALTER TABLE) for the column.

SQL Server saves the settings of both SET QUOTED_IDENTIFIER and SET ANSI_NULLS when a stored procedure is created or altered. These original settings are restored when the stored procedure is executed. Therefore, any client session settings for SET QUOTED_IDENTIFIER and SET ANSI_NULLS are restored after stored procedure execution. Within the stored procedure, any changes to SET ANSI_NULLS does not take effect until the stored procedure completes execution.

Other SET options, such as SET ARITHABORT, SET ANSI_WARNINGS, or SET ANSI_PADDINGS are not saved when a stored procedure is created or altered. If the logic of the stored procedure is dependent on a particular setting, include a SET statement at the start of the procedure to ensure the proper setting. When a SET statement is executed from a stored procedure, the setting remains in effect only until the stored procedure completes. The setting is then restored to the value it had when the stored procedure was called. This allows individual clients freedom to set the options wanted without affecting the logic of the stored procedure.

Note Whether SQL Server interprets an empty string as either a single space or as a true empty string is controlled by the compatibility level setting. If the compatibility level is less than or equal to 65, SQL Server interprets empty strings as single spaces. If the compatibility level is equal to 70, SQL Server interprets empty strings as empty strings. For more information, see sp_dbcmptlevel.

Getting Information About Stored Procedures

To display the text used to create the procedure, execute sp_helptext (in the database in which the procedure exists) with the procedure name as the parameter.

Note Stored procedures created with the ENCRYPTION option cannot be viewed with sp_helptext.

For a report on the objects referenced by a procedure, use sp_depends.

To rename a procedure, use sp_rename.

Referencing Objects

SQL Server allows the creation of stored procedures that reference objects that do not yet exist. At creation time, only syntax checking is done. The stored procedure is compiled to generate an execution plan when it is executed, if a valid plan does not already exist in the cache. Only during compilation are all objects referenced in the stored procedure resolved. Thus, a syntactically correct stored procedure that references objects which do not exist can be created successfully, but will fail at execution. time because referenced objects do not exist.

Deferred Name Resolution

SQL Server allows Transact-SQL stored procedures, triggers, and batches to refer to tables that do not exist at compile time. This ability is called deferred name resolution. If, however, the Transact-SQL stored procedure, trigger, or batch refers to a table defined in the stored procedure or trigger, a warning is issued at creation time only if the compatibility level setting (set by executing sp_dbcmptlevel) is 65. A warning is issued at compile time if a batch is used. An error message is returned at execution time if the table referenced does not exist. For more information, see sp_dbcmptlevel.

Executing Stored Procedures

When a CREATE PROCEDURE statement is executed successfully, the procedure’s name is stored in the sysobjects system table and the text of the CREATE PROCEDURE statement is stored in syscomments. When executed for the first time, the procedure is compiled to determine an optimal access plan to retrieve the data.

Parameters Using the cursor Data Type

Stored procedures can use the cursor data type only for OUTPUT parameters. If the cursor data type is specified for a parameter, then both the VARYING and OUTPUT parameters are required. If the VARYING keyword is specified for a parameter, the data type must be cursor and the OUTPUT keyword must be specified.

Note The cursor data type cannot be bound to application variables through the database APIs such as OLE DB, ODBC, ADO, and DB-Library. Because OUTPUT parameters must be bound before an application can execute a stored procedure, stored procedures with cursor OUTPUT parameters cannot be called from the database APIs. These procedures can be called from Transact-SQL batches, stored procedures, or triggers only when the cursor OUTPUT variable is assigned to a Transact-SQL local cursor variable.

Cursor Output Parameters

The following rules pertain to cursor output parameters when the procedure is executed:

  • For a forward-only cursor, the rows returned in the cursor’s result set are only those rows at and beyond the position of the cursor at the conclusion of the stored procedure executed, for example:
    1. A nonscrollable cursor is opened in a procedure on a result set named RS of 100 rows.
    2. The procedure fetches the first 5 rows of result set RS.
    3. The procedure returns to its caller.
    4. The result set RS returned to the caller consists of rows 6 through 100 of RS, and the cursor in the caller is positioned before the first row of RS.
  • For a forward-only cursor, if the cursor is positioned before the first row upon completion of the stored procedure, the entire result set is returned to the calling batch, stored procedure, or trigger. When it is returned, the cursor’s position is set before the first row.
  • For a forward-only cursor, if the cursor is positioned beyond the end of the last row upon completion of the stored procedure, an empty result set is returned to the calling batch, stored procedure, or trigger.

    Note An empty result set is not the same thing as a null value.

  • For a scrollable cursor, all the rows in the result set are returned to the calling batch, stored procedure, or trigger at the conclusion of the execution of the stored procedure. When it is returned, the cursor’s position is left at the position of the last fetch executed in the procedure.
  • For any type of cursor, if the cursor has been closed, then a null value is passed back to the calling batch, stored procedure, or trigger. This will also be the case if a cursor has been assigned to a parameter but that cursor is never opened.

Note The closed state matters only at return time. For example it is valid to close a cursor part way through the procedure, to open it again later in the procedure, and return that cursor’s result set to the calling batch, stored procedure, or trigger.

Temporary Stored Procedures

SQL Server supports two types of temporary procedures: local and global. A local temporary procedure is visible only to the connection that created it. A global temporary procedure is available to all connections. Local temporary procedures are automatically dropped at the end of the current session. Global temporary procedures are dropped at the end of the last session using the procedure. Usually, this is when the session that created the procedure ends.

Temporary procedures named with # and ## can be created by any user. After the procedure is created, the owner of the local procedure is the only one who can use it. Permission to execute a local temporary procedure cannot be granted to other users. If a global temporary procedure is created, all users can access it; permissions cannot be revoked explicitly. Explicitly creating a temporary procedure in tempdb (naming without a number sign) can be performed only by those with explicit CREATE PROCEDURE permission in the tempdb database. Permission can be granted to and revoked from these procedures.

Note Heavy use of temporary stored procedures can create contention on the system tables in tempdb and adversely affect performance. It is recommended that sp_executesql be used instead. sp_executesql does not store data in the system tables and therefore avoids the problem.

Automatically Executing Stored Procedures

One or more stored procedures can execute automatically when SQL Server starts. The stored procedures must be created by the system administrator and executed under the sysadmin fixed server role as a background process. The procedure(s) cannot have any input parameters.

There is no limit to the number of startup procedures you can have, but be aware that each consumes one connection while executing. If you must execute multiple procedures at startup but don’t need to execute them in parallel, make one procedure the startup procedure and have that procedure call the other procedures. This uses only one connection.

Execution of the stored procedures starts when the last database has been recovered at startup. To skip launching these stored procedures, you can specify trace flag 4022 as a startup parameter. If you start SQL Server with minimal configuration (using the -f flag), the startup stored procedures are not executed. For more information, see Trace Flags.

To create a startup stored procedure, you must be logged in as a member of the sysadmin fixed server role and create the stored procedure in the master database.

Use sp_procoption to:

  • Make an existing stored procedure a startup procedure.
  • Stop a procedure from executing at SQL Server startup.
  • View a list of all procedures that execute at SQL Server startup.
Stored Procedure Nesting

Stored procedures can be nested (one stored procedure calling another). The nesting level is incremented when the called procedure starts execution, and it is decremented when the called procedure finishes execution. Exceeding the maximum levels of nesting causes the whole calling procedure chain to fail. The current nesting level is stored in the @@NESTLEVEL function.

To estimate the size of a compiled stored procedure, use these Performance Monitor Counters.

Performance Monitor object name | Performance Monitor Counter name
SQLServer:Buffer Manager | Procedure Cache Size (pages)
SQLServer: Procedure Cache | Procedure Cache Hit Ratio
 | Procedure Cache Pages
 | Procedure Cache Object Counts*
* These counters are available for various categories of cache objects including adhoc sql, prepared sql, procedures, triggers, and so on.

sql_statement Limitations

Any SET statement can be specified inside a stored procedure except SET SHOWPLAN_TEXT and SET SHOWPLAN_ALL, which must be the only statements in the batch. The SET option chosen remains in effect during the execution of the stored procedure and then reverts to its former setting.

Inside a stored procedure, object names used with certain statements (the utility statements) must be qualified with the name of the object owner if other users are to use the stored procedure. The utility statements are:

  • ALTER TABLE
  • CREATE INDEX
  • CREATE TABLE
  • All DBCC statements
  • DROP TABLE
  • DROP INDEX
  • TRUNCATE TABLE
  • UPDATE STATISTICS
Permissions

CREATE PROCEDURE permissions default to the members of the db_owner and db_ddladmin fixed database roles. Members of the sysadmin fixed server role and the db_owner fixed database role can transfer CREATE PROCEDURE permissions to other users. Permissions to execute a stored procedure are given to the procedure owner, who can grant execution permission on it to other database users.

Examples
A. Use a simple procedure with a complex SELECT

This stored procedure returns all authors (first and last names supplied), their titles, and their publishers from a four-table join. This stored procedure does not use any parameters.

USE pubs

IF EXISTS (SELECT name FROM sysobjects
            WHERE name = 'au_info_all' AND type = 'P')

    DROP PROCEDURE au_info_all

GO

CREATE PROCEDURE au_info_all

AS

SELECT au_lname, au_fname, title, pub_name

    FROM authors a INNER JOIN titleauthor ta

        ON a.au_id = ta.au_id INNER JOIN titles t

        ON t.title_id = ta.title_id INNER JOIN publishers p

        ON t.pub_id = p.pub_id

GO

The au_info_all stored procedure can be executed in these ways:

EXECUTE au_info_all

-- Or

EXEC au_info_all

Or, if this procedure is the first statement within the batch:

au_info_all

B. Use a simple procedure with parameters

This stored procedure returns only the specified authors (first and last names supplied), their titles, and their publishers from a four-table join. This stored procedure accepts exact matches for the parameters passed.

USE pubs

IF EXISTS (SELECT name FROM sysobjects

            WHERE name = 'au_info' AND type = 'P')

    DROP PROCEDURE au_info

GO

USE pubs

GO

CREATE PROCEDURE au_info

    @lastname varchar(40),

    @firstname varchar(20)

AS

SELECT au_lname, au_fname, title, pub_name

    FROM authors a INNER JOIN titleauthor ta

        ON a.au_id = ta.au_id INNER JOIN titles t

        ON t.title_id = ta.title_id INNER JOIN publishers p

        ON t.pub_id = p.pub_id

    WHERE  au_fname = @firstname

        AND au_lname = @lastname

GO

The au_info stored procedure can be executed in these ways:

EXECUTE au_info 'Dull', 'Ann'

-- Or

EXECUTE au_info @lastname = 'Dull', @firstname = 'Ann'

-- Or

EXECUTE au_info @firstname = 'Ann', @lastname = 'Dull'

-- Or

EXEC au_info 'Dull', 'Ann'

-- Or

EXEC au_info @lastname = 'Dull', @firstname = 'Ann'

-- Or

EXEC au_info @firstname = 'Ann', @lastname = 'Dull'

Or, if this procedure is the first statement within the batch:

au_info 'Dull', 'Ann'

-- Or

au_info @lastname = 'Dull', @firstname = 'Ann'

-- Or

au_info @firstname = 'Ann', @lastname = 'Dull'

C. Use a simple procedure with wildcard parameters

This stored procedure returns only the specified authors (first and last names supplied), their titles, and their publishers from a four-table join. This stored procedure pattern matches the parameters passed or, if not supplied, uses the preset defaults.

USE pubs

IF EXISTS (SELECT name FROM sysobjects

        WHERE name = 'au_info2' AND type = 'P')

    DROP PROCEDURE au_info2

GO

USE pubs

GO

CREATE PROCEDURE au_info2

    @lastname varchar(30) = 'D%',

    @firstname varchar(18) = '%'

AS

SELECT au_lname, au_fname, title, pub_name

FROM authors a INNER JOIN titleauthor ta

    ON a.au_id = ta.au_id INNER JOIN titles t

    ON t.title_id = ta.title_id INNER JOIN publishers p

    ON t.pub_id = p.pub_id

WHERE au_fname LIKE @firstname

    AND au_lname LIKE @lastname

GO

The au_info2 stored procedure can be executed in many combinations. Only a few combinations are shown here:

EXECUTE au_info2

-- Or

EXECUTE au_info2 'Wh%'

-- Or

EXECUTE au_info2 @firstname = 'A%'

-- Or

EXECUTE au_info2 '[CK]ars[OE]n'

-- Or

EXECUTE au_info2 'Hunter', 'Sheryl'

-- Or

EXECUTE au_info2 'H%', 'S%'

D. Use OUTPUT parameters

OUTPUT parameters allow an external procedure, a batch, or more than one Transact-SQL statements to access a value set during the procedure execution. In this example, a stored procedure (titles_sum) is created and allows one optional input parameter and one output parameter.

First, create the procedure:

USE pubs

GO

IF EXISTS(SELECT name FROM sysobjects

        WHERE name = 'titles_sum' AND type = 'P')

    DROP PROCEDURE titles_sum

GO

USE pubs

GO

CREATE PROCEDURE titles_sum @@TITLE varchar(40) = '%', @@SUM money OUTPUT

AS

SELECT 'Title Name' = title

FROM titles

WHERE title LIKE @@TITLE

SELECT @@SUM = SUM(price)

FROM titles

WHERE title LIKE @@TITLE

GO

Next, use the OUTPUT parameter with control-of-flow language.

Note The OUTPUT variable must be defined during the table creation as well as during use of the variable.

The parameter name and variable name do not have to match; however, the data type and parameter positioning must match (unless @@SUM = variable is used).

DECLARE @@TOTALCOST money

EXECUTE titles_sum 'The%', @@TOTALCOST OUTPUT

IF @@TOTALCOST < 200

BEGIN

    PRINT ' '

    PRINT 'All of these titles can be purchased for less than $200.'

END

ELSE

    SELECT 'The total cost of these titles is $'

            + RTRIM(CAST(@@TOTALCOST AS varchar(20)))

Here is the result set:

Title Name

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

The Busy Executive's Database Guide

The Gourmet Microwave

The Psychology of Computer Cooking

(3 row(s) affected)

Warning, null value eliminated from aggregate.

All of these titles can be purchased for less than $200.

E. Use an OUTPUT cursor parameter

OUTPUT cursor parameters are used to pass a cursor that is local to a stored procedure back to the calling batch, stored procedure, or trigger.

First, create the procedure that declares and then opens a cursor on the titles table:

USE pubs

IF EXISTS (SELECT name FROM sysobjects

        WHERE name = 'titles_cursor' and type = 'P')

DROP PROCEDURE titles_cursor

GO

CREATE PROCEDURE titles_cursor @titles_cursor CURSOR VARYING OUTPUT

AS

SET @titles_cursor = CURSOR

FORWARD_ONLY STATIC FOR

SELECT *

FROM titles

OPEN @titles_cursor

GO

Next, execute a batch that declares a local cursor variable, executes the procedure to assign the cursor to the local variable, and then fetches the rows from the cursor.

USE pubs

GO

DECLARE @MyCursor CURSOR

EXEC titles_cursor @titles_cursor = @MyCursor OUTPUT

WHILE (@@FETCH_STATUS = 0)

BEGIN

    FETCH NEXT FROM @MyCursor

END

CLOSE @MyCursor

DEALLOCATE @MyCursor

GO

F. Use the WITH RECOMPILE option

    The WITH RECOMPILE clause is helpful when the parameters supplied to the procedure will not be typical and when a new execution plan should not be cached or stored in memory.

    USE pubs

    IF EXISTS (SELECT name FROM sysobjects

            WHERE name = 'titles_by_author' AND type = 'P')

        DROP PROCEDURE titles_by_author

    GO

    CREATE PROCEDURE titles_by_author @@LNAME_PATTERN varchar(30) = '%'

    WITH RECOMPILE

    AS

    SELECT RTRIM(au_fname) + ' ' + RTRIM(au_lname) AS 'Authors full name',

        title AS Title

    FROM authors a INNER JOIN titleauthor ta

        ON a.au_id = ta.au_id INNER JOIN titles t

        ON ta.title_id = t.title_id

    WHERE au_lname LIKE @@LNAME_PATTERN

    GO

    G. Use the WITH ENCRYPTION option

    The WITH ENCRYPTION clause hides the text of a stored procedure from users. This example creates an encrypted procedure and uses the sp_helptext system stored procedure and then attempts to select directly from the syscomments table.

    IF EXISTS (SELECT name FROM sysobjects

            WHERE name = 'encrypt_this' AND type = 'P')

        DROP PROCEDURE encrypt_this

    GO

    USE pubs

    GO

    CREATE PROCEDURE encrypt_this

    WITH ENCRYPTION

    AS

    SELECT *

    FROM authors

    GO

    EXEC sp_helptext encrypt_this

    Here is the result set from the encrypt_this stored procedure:

    The object's comments have been encrypted.

    Next, select the identification number and text of the encrypted stored procedure contents.

    SELECT c.id, c.text

    FROM syscomments c INNER JOIN sysobjects o

        ON c.id = o.id

    WHERE o.name = 'encrypt_this'

    Here is the result set:

    Note The text column output is shown on a separate line. When executed, this information appears on the same line as the id column information.

    id         text

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

    1413580074 ?????????????????????????????????e??????????????????????????????????????????????????????????????????????????

    (1 row(s) affected)

    H. Create a user-defined system stored procedure

    This example creates a procedure to display all the tables and their corresponding indexes with a table name beginning with the string emp. If not specified, this procedure returns all tables (and indexes) with a table name beginning with sys.

    IF EXISTS (SELECT name FROM sysobjects

            WHERE name = 'sp_showindexes' AND type = 'P')

        DROP PROCEDURE sp_showindexes

    GO

    USE master

    GO

    CREATE PROCEDURE sp_showindexes

        @@TABLE varchar(30) = 'sys%'

    AS

    SELECT o.name AS TABLE_NAME,

        i.name AS INDEX_NAME,

        indid AS INDEX_ID

    FROM sysindexes i INNER JOIN sysobjects o

        ON o.id = i.id

    WHERE o.name LIKE @@TABLE

    GO

    USE pubs

    EXEC sp_showindexes 'emp%'

    GO

    Here is the result set:

    TABLE_NAME       INDEX_NAME       INDEX_ID

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

    emp_pay          employeeID_ind   1

    employee         employee_ind     1

    employee         PK_emp_id        2

    (3 row(s) affected)

    I. Use deferred name resolution

    This example shows four procedures and the various ways that deferred name resolution can be used. Each stored procedure is created, although the table or column referenced does not exist at compile time.

    IF EXISTS (SELECT name FROM sysobjects

            WHERE name = 'proc1' AND type = 'P')

        DROP PROCEDURE proc1

    GO

    -- Creating a procedure on a nonexistent table.

    USE pubs

    GO

    CREATE PROCEDURE proc1

    AS

        SELECT *

        FROM does_not_exist

    GO

    -- Here is the statement to actually see the text of the procedure.

    SELECT o.id, c.text

    FROM sysobjects o INNER JOIN syscomments c

        ON o.id = c.id

    WHERE o.type = 'P' AND o.name = 'proc1'

    GO

    USE master

    GO

    IF EXISTS (SELECT name FROM sysobjects

            WHERE name = 'proc2' AND type = 'P')

        DROP PROCEDURE proc2

    GO

    -- Creating a procedure that attempts to retrieve information from a

    -- nonexistent column in an existing table.

    USE pubs

    GO

    CREATE PROCEDURE proc2

    AS

        DECLARE @middle_init char(1)

        SET @middle_init = NULL

        SELECT au_id, middle_initial = @middle_init

        FROM authors

    GO

    -- Here is the statement to actually see the text of the procedure.

    SELECT o.id, c.text

    FROM sysobjects o INNER JOIN syscomments c

        ON o.id = c.id

    WHERE o.type = 'P' and o.name = 'proc2'

    See Also
    ALTER PROCEDURE | sp_addextendedproc
Control-of-Flow Language | sp_depends
DBCC | sp_helptext
DECLARE @local_variable | sp_procoption
DROP PROCEDURE | sp_recompile
Functions | sp_rename
GRANT | System Tables
SELECT |


CREATE RULE

Creates an object called a rule. When bound to a column or a user-defined data type, a rule specifies the acceptable values that can be inserted into that column. Rules, a backward compatibility feature, perform some of the same functions as check constraints. CHECK constraints, created using the CHECK keyword of ALTER or CREATE TABLE, are the preferred, standard way to restrict the values in a column (multiple constraints can be defined on a column or multiple columns). A column or user-defined data type can have only one rule bound to it. However, a column can have both a rule and one or more check constraints associated with it. When this is true, all restrictions are evaluated.

Syntax

CREATE RULE rule
AS condition_expression

Arguments
rule
Is the name of the new rule. Rule names must conform to the rules for identifiers. Specifying the rule owner name is optional.
condition_expression
Is the condition(s) defining the rule. A rule can be any expression that is valid in a WHERE clause and can include such elements as arithmetic operators, relational operators, and predicates (for example, IN, LIKE, BETWEEN). A rule cannot reference columns or other database objects. Built-in functions that do not reference database objects can be included.

condition_expression includes one variable. The at sign (@) precedes each local variable. The expression refers to the value that is entered with the UPDATE or INSERT statement. Any name or symbol can be used to represent the value when creating the rule, but the first character must be @.

Remarks

The CREATE RULE statement cannot be combined with other Transact-SQL statements in a single batch. Rules do not apply to data already existing in the database at the time the rules are created, and rules cannot be bound to system data types. A rule can be created only in the current database. After creating a rule, execute sp_bindrule to bind the rule to a column or to a user-defined data type.

The rule must be compatible with the data type of the column. A rule cannot be bound to a text, image, or timestamp column. Be sure to enclose character and date constants with single quotation marks (‘) and to precede binary constants with 0x. For example, “@value LIKE A%” cannot be used as a rule for a numeric column. If the rule is not compatible with the column to which it has been bound, Microsoft® SQL Server™ returns an error message when inserting a value (not when the rule is bound).

A rule bound to a user-defined data type is activated only when you attempt to insert a value into or to update a database column of the user-defined data type. Because rules do not test variables, do not assign a value to a user-defined data type variable that would be rejected by a rule bound to a column of the same data type.

To get a report on a rule, use sp_help. To display the text of a rule, execute sp_helptext with the rule name as the parameter. To rename a rule, use sp_rename.

A rule must be dropped (using DROP RULE) before a new one with the same name is created, and the rule must be unbound (using sp_unbindrule) before it is dropped. Use sp_unbindrule to unbind a rule from a column.

You can bind a new rule to a column or data type without unbinding the previous one; the new rule overrides the previous one. Rules bound to columns always take precedence over rules bound to user-defined data types. Binding a rule to a column replaces a rule already bound to the user-defined data type of that column. But binding a rule to a data type does not replace a rule bound to a column of that user-defined data type. The table shows the precedence in effect when binding rules to columns and to user-defined data types where rules already exist.

 | Old rule bound to
New rule bound to | User-defined data type | Column
User-defined data type | Old rule replaced | No change
Column | Old rule replaced | Old rule replaced

If a column has both a default and a rule associated with it, the default must fall within the domain defined by the rule. A default that conflicts with a rule is never inserted. SQL Server generates an error message each time it attempts to insert such a default.

Note Whether SQL Server interprets an empty string as a single space or as a true empty string is controlled by the setting of sp_dbcmptlevel. If the compatibility level is less than or equal to 65, SQL Server interprets empty strings as single spaces. If the compatibility level is equal to 70, SQL Server interprets empty strings as empty strings. For more information, see sp_dbcmptlevel.

Permissions

CREATE RULE permissions default to the members of the db_owner fixed database role, who can transfer permissions to other users.

Examples
A. Rule with a range

This example creates a rule that restricts the range of integers inserted into the column(s) to which this rule is bound.

CREATE RULE range_rule

AS

@range >= $1000 AND @range < $20000

B. Rule with a list

This example creates a rule that restricts the actual values entered into the column(s) to which this rule is bound to only those listed in the rule.

CREATE RULE list_rule

AS

@list IN ('1389', '0736', '0877')

C. Rule with a pattern

This example creates a rule to follow a pattern of any two characters followed by a hyphen, any number of characters (or no characters), and ending with an integer between 0 and 9.

CREATE RULE pattern_rule

AS

@value LIKE '_ _-%[0-9]'

See Also
ALTER TABLE | sp_bindrule
CREATE DEFAULT | sp_help
CREATE TABLE | sp_helptext
DROP DEFAULT | sp_rename
DROP RULE | sp_unbindrule
Expressions | WHERE


CREATE SCHEMA

Creates a schema that can be thought of as a conceptual object containing definitions of tables, views, and granted permissions.

Syntax

CREATE SCHEMA AUTHORIZATION owner
[ <schema_element> […n] ]

<schema_element> ::=
{table_definition | view_definition | grant_statement}

Arguments
AUTHORIZATION owner
Specifies the ID of the schema object owner. This identifier must be a valid security account in the database.
table_definition
Specifies a CREATE TABLE statement that creates a table within the schema.
view_definition
Specifies a CREATE VIEW statement that creates a view within the schema.
grant_statement
Specifies a GRANT statement that grants permissions to a user or group of users.
Remarks

CREATE SCHEMA provides a way to create tables and views and to grant permissions on the objects, all within a single statement. If errors occur when creating any of the objects or granting any permissions specified in a CREATE SCHEMA statement, none of the objects is created.

The created objects do not have to appear in logical order, except for views that reference other views. For example, a GRANT statement can grant permission to an object before the object itself has been created, or a CREATE VIEW statement can appear before the CREATE TABLE statements creating the tables referenced by the view. Also, CREATE TABLE statements can declare foreign keys to tables that are specified later. The exception is that if the select from one view references another view, the referenced view must be specified before the view that references it.

Permissions

CREATE SCHEMA permissions default to members of the db_owner and db_ddladmin fixed database roles.

Examples
A. Grant access to objects before object creation

This example shows permissions being granted before the objects have been created.

CREATE SCHEMA AUTHORIZATION ross

GRANT SELECT on v1 TO public

CREATE VIEW v1(c1) AS SELECT c1 from t1

CREATE TABLE t1(c1 int)

B. Create mutually dependent FOREIGN KEY constraints

This example creates mutually dependent FOREIGN KEY constraints. Other methods would take several steps to accomplish what is enabled by this CREATE SCHEMA example.

CREATE SCHEMA AUTHORIZATION ross

CREATE TABLE t1 (c1 INT PRIMARY KEY, c2 INT REFERENCES t2(c1))

CREATE TABLE t2 (c1 INT PRIMARY KEY, c2 INT REFERENCES t1(c1))


CREATE STATISTICS

Creates a histogram and associated density groups (collection) over the supplied column or set of columns.

Syntax

CREATE STATISTICS statistics_name ON table (column [,…n])
[ WITH
[ [ FULLSCAN
| SAMPLE number PERCENT ] [,] ]
[ NORECOMPUTE]
]

Arguments
statistics_name
Is the name of the statistics group to create. Statistics names must conform to the rules for identifiers.
table
Is the name of the table on which to create the named statistics. Table names must conform to the rules for identifiers. table is the table with which the column is associated. Specifying the table owner name is optional. Statistics can be created on tables in another database by specifying a qualified database name.
column
Is the column or set of columns on which to create statistics. Computed columns and columns of the ntext, text, or image data types cannot be specified as statistics columns.
n
Is a placeholder indicating that multiple columns can be specified.
FULLSCAN
Specifies that all rows in table should be read to gather the statistics. Specifying FULLSCAN provides the same behavior as SAMPLE 100 PERCENT. This option cannot be used with the SAMPLE option.
SAMPLE number PERCENT
Specifies that a percentage of the data should be read using random sampling to gather the statistics. number can be fractional. This option cannot be used with the FULLSCAN option. If no SAMPLE or FULLSCAN option is given, an automatic sample fraction is computed by SQL Server.
NORECOMPUTE
Specifies that automatic recomputation of the statistics should be disabled. For more information, see UPDATE STATISTICS and sp_autostats. If this option is specified, SQL Server continues to use previously created (“old”) statistics even as the data changes. The statistics are not automatically updated and maintained by SQL Server, which may produce suboptimal plans.

Warning It is recommended that this option be used rarely and only by a trained system administrator.

Remarks

Only the table owner can create statistics on that table. The owner of a table can create a statistics group (collection) at any time, whether or not there is data in the table.

Permissions

CREATE STATISTICS permissions default to the owner of the table.

Examples
A. Use CREATE STATISTICS with SAMPLE number PERCENT

This example creates the names statistics group (collection), which calculates random sampling statistics on 5 percent of the CompanyName and ContactName columns of the Customers table.

CREATE STATISTICS names

    ON Customers (CompanyName, ContactName)

    WITH SAMPLE 5 PERCENT

GO

B. Use CREATE STATISTICS with FULLSCAN and NORECOMPUTE

This example creates the names statistics group (collection), which calculates statistics for all rows in the CompanyName and ContactName columns of the Customers table and disables automatic recomputation of statistics.

CREATE STATISTICS names

    ON Northwind..Customers (CompanyName, ContactName)

    WITH FULLSCAN, NORECOMPUTE

GO

See Also
CREATE INDEX | sp_createstats
DBCC SHOW_STATISTICS | sp_dboption
DROP STATISTICS | UPDATE STATISTICS
sp_autostats |


CREATE TABLE

Creates a new table.

Syntax

CREATE TABLE
[
database_name.[owner].
| owner.
] table_name
(
 { <column_definition>
| column_name AS computed_column_expression
 | <table_constraint>
} [,…n]
)
[ON {filegroup | DEFAULT} ]
[TEXTIMAGE_ON {filegroup | DEFAULT} ]

<column_definition> ::= { column_name data_type }
[ [ DEFAULT constant_expression ]
| [ IDENTITY [(seed, increment ) [NOT FOR REPLICATION] ] ]
]
[ ROWGUIDCOL ]
[ <column_constraint>] [ …n]

<column_constraint> ::= [CONSTRAINT constraint_name]
{
[ NULL | NOT NULL ]
| [ { PRIMARY KEY | UNIQUE }
[CLUSTERED | NONCLUSTERED]
[WITH FILLFACTOR = fillfactor]
[ON {filegroup | DEFAULT} ]]
]
| [ [FOREIGN KEY]
REFERENCES ref_table [(ref_column) ]
[NOT FOR REPLICATION]
]
| CHECK [NOT FOR REPLICATION]
(logical_expression)
}

<table_constraint> ::= [CONSTRAINT constraint_name]
{
[ { PRIMARY KEY | UNIQUE }
[ CLUSTERED | NONCLUSTERED]
{ ( column[,…n] ) }
[ WITH FILLFACTOR = fillfactor]
[ON {filegroup | DEFAULT} ]
]
| FOREIGN KEY
[(column[,…n])]
REFERENCES ref_table [(ref_column[,…n])]
[NOT FOR REPLICATION]
| CHECK [NOT FOR REPLICATION]
(search_conditions)
}

Arguments
database_name
Is the name of the database in which the table is created. database_name must specify the name of an existing database. database_name defaults to the current database if it is not specified. The login for the current connection must be associated with an existing user ID in the database specified by database_name, and that user ID must have create table privileges.
owner
Is the name of the user ID that owns the new table. owner must be an existing user ID in the database specified by database_name. owner defaults to the user ID associated with the login for the current connection in the database specified in database_name. If the CREATE TABLE statement is executed by a member of the sysadmin fixed server role, or a member of the db_dbowner or db_ddladmin fixed database roles in the database specified by database_name, owner can specify a user ID other than the one associated with the login of the current connection. If the CREATE TABLE statement is executed by a login associated with a user ID that has been granted only create table privileges, owner must specify the user ID associated with the current login. Members of the sysadmin fixed server role, the database owner, or logins aliased to the dbo user are associated with the user ID dbo; therefore, tables created by these users default to having dbo as the owner. Tables created by any logins not in either of these two roles have owner default to the user ID associated with the login.
table_name
Is the name of the new table. Table names must conform to the rules for identifiers. The combination of owner.table_name must be unique within the database. table_name can contain up to 128 characters, except for local temporary table names (names prefixed with a single number sign (#)) that cannot exceed 116 characters.
column_name
Is the name of a column in the table. Column names must conform to the rules for identifiers and must be unique in the table. column_name can be omitted for columns created with a timestamp data type. The name of a timestamp column defaults to timestamp if column_name is not specified.
computed_column_expression
Is an expression defining the value of a computed column. A computed column is a virtual column not physically stored in the table. It is computed from an expression using other columns in the same table. For example, a computed column can have the definition: cost AS price * qty. The expression can be a noncomputed column name, constant, function, variable, and any combination of these connected by one or more operators. The expression cannot be a subquery.

Computed columns can be used in select lists, WHERE clauses, ORDER BY clauses, or any other locations in which regular expressions can be used, with the following exceptions:

  • A computed column cannot be used as a key column in an index or as part of any PRIMARY KEY, UNIQUE, FOREIGN KEY, or DEFAULT constraint definition.
  • A computed column cannot be the target of an INSERT or UPDATE statement.

Note Because each row in a table can have different values for columns involved in a computed column, the computed column may not have the same value for each row.

ON {filegroup | DEFAULT}
Specifies the filegroup on which the table is stored. If filegroup is specified, the table is stored in the named filegroup. The filegroup must exist within the database. If DEFAULT is specified, or if ON is not specified at all, the table is stored on the default filegroup.

ON {filegroup | DEFAULT} can also be specified in a PRIMARY KEY or UNIQUE constraint. These constraints create indexes. If filegroup is specified, the index is stored in the named filegroup. If DEFAULT is specified, the index is stored in the default filegroup. If no filegroup is specified in a constraint, the index is stored on the same filegroup as the table. If the PRIMARY KEY or UNIQUE constraint creates a clustered index, the data pages for the table are stored in the same filegroup as the index.

TEXTIMAGE_ON
Are keywords indicating that the text, ntext, and image columns are stored on the specified filegroup. TEXTIMAGE ON is not allowed if there are no text, ntext, or image columns in the table. If TEXTIMAGE_ON is not specified, the text, ntext, and image columns are stored in the same filegroup as the table.
data_type
Specifies the data type of the column. System or user-defined data types are acceptable. User-defined data types are created with sp_addtype before they can be used in a table definition.

The NULL/NOT NULL assignment for a user-defined data type can be overridden during the CREATE TABLE statement. However, the length specification cannot be changed; you cannot specify a length for a user-defined data type in a CREATE TABLE statement.

DEFAULT
Specifies the value provided for the column when a value is not explicitly supplied during an insert. DEFAULT definitions can be applied to any columns except those defined as timestamp, or those with the IDENTITY property. DEFAULT definitions are removed when the table is dropped. Only a constant value, such as a character string; a system function, such as SYSTEM_USER(); or NULL can be used as a default. To maintain compatibility with earlier versions of SQL Server, a constraint name can be assigned to a DEFAULT.
constant_expression
Is a constant, NULL, or a system function used as the default value for the column.
IDENTITY
Indicates that the new column is an identity column. When a new row is added to the table, Microsoft® SQL Server™ provides a unique, incremental value for the column. Identity columns are commonly used in conjunction with PRIMARY KEY constraints to serve as the unique row identifier for the table. The IDENTITY property can be assigned to tinyint, smallint, int, decimal(p,0), or numeric(p,0) columns. Only one identity column can be created per table. Bound defaults and DEFAULT constraints cannot be used with an identity column. You must specify both the seed and increment or neither. If neither is specified, the default is (1,1).
seed
Is the value that is used for the very first row loaded into the table.
increment
Is the incremental value that is added to the identity value of the previous row that was loaded.
NOT FOR REPLICATION
Indicates that the IDENTITY property should not be enforced when a replication login such as sqlrepl inserts data into the table. Replicated rows must retain the key values they were assigned in the publishing database, the NOT FOR REPLICATION clause ensures that rows inserted by a replication process are not assigned new identity values. Rows inserted by other logins continue to have new identity values created in the usual way. It is recommended that a CHECK constraint with NOT FOR REPLICATION also be defined to ensure that the identity values being assigned are within the range wanted for the current database.
ROWGUIDCOL
Indicates that the new column is a row global unique identifier column. Only one uniqueidentifier column per table can be designated as the ROWGUIDCOL column. The ROWGUIDCOL property can be assigned only to a uniqueidentifier column.

The ROWGUIDCOL property does not enforce uniqueness of the values stored in the column. It also does not automatically generate values for new rows inserted into the table. To generate unique values for each column, either use the NEWID function on INSERT statements or use the NEWID function as the default for the column.

CONSTRAINT
Is an optional keyword indicating the beginning of a PRIMARY KEY, NOT NULL, UNIQUE, FOREIGN KEY, or CHECK constraint definition. Constraints are special properties that enforce data integrity and create special types of indexes for the table and its columns.
constraint_name
Is the name of a constraint. Constraint names must be unique within a database.
NULL | NOT NULL
Are keywords that determine whether or not null values are allowed in the column. NULL is not strictly a constraint, but can be specified in the same manner as NOT NULL.
PRIMARY KEY
Is a constraint that enforces entity integrity for a given column or columns through a unique index. Only one PRIMARY KEY constraint can be created per table.
UNIQUE
Is a constraint that provides entity integrity for a given column or columns through a unique index. A table can have multiple UNIQUE constraints.
CLUSTERED | NONCLUSTERED
Are keywords to indicate that a clustered or a nonclustered index is created for the PRIMARY KEY or UNIQUE constraint. PRIMARY KEY constraints default to CLUSTERED and UNIQUE constraints default to NONCLUSTERED.

You can specify CLUSTERED for only one constraint in a CREATE TABLE statement. If you specify CLUSTERED for a UNIQUE constraint and also specify a PRIMARY KEY constraint, the PRIMARY KEY defaults to NONCLUSTERED.

[WITH FILLFACTOR = fillfactor]
Specifies how full SQL Server should make each index page used to store the index data. User-specified fillfactor values can be from 1 through 100, with a default of 0. A lower fill factor creates the index with more space available for new index entries without having to allocate new space.
FOREIGN KEY…REFERENCES
Is a constraint that provides referential integrity for the data in the column or columns. FOREIGN KEY constraints require that each value in the column exists in the corresponding referenced column(s) in the referenced table. FOREIGN KEY constraints can reference only columns that are PRIMARY KEY or UNIQUE constraints in the referenced table.
ref_table
Is the name of the table referenced by the FOREIGN KEY constraint.
(ref_column[,…n])
Is a column, or list of columns, from the table referenced by the FOREIGN KEY constraint.
CHECK
Is a constraint that enforces domain integrity by limiting the possible values that can be entered into a column or columns.
NOT FOR REPLICATION
Keywords used to prevent the CHECK constraint from being enforced during the distribution process used by replication. When tables are Subscribers to a replication publication, do not update the subscription table directly, instead update the publishing table, and let replication distribute the data back to the subscribing table. A CHECK constraint can be defined on the subscription table to prevent users from modifying it. Unless the NOT FOR REPLICATION clause is added, however, the CHECK constraint also prevents the replication process from distributing modifications from the publishing table to the subscribing table. The NOT FOR REPLICATION clause means the constraint is enforced on user modifications, but not on the replication process.

The NOT FOR REPLICATION CHECK constraint is applied to both the before and after image of an updated record to prevent records from being added to or deleted from the replicated range. All deletes and inserts are checked; if they fall within the replicated range, they are rejected.

When this constraint is used with an identity column, SQL Server allows the table not to have its identity column values reseeded when a replication user updates the identity column.

logical_expression
Is a logical expression that returns TRUE or FALSE.
column
Is a column, or list of columns, in parentheses used in table constraints to indicate the columns that are used in the constraint definition.
n
Is a placeholder indicating that the preceding item can be repeated n number of times.
Remarks

SQL Server can have as many as 2 billion tables per database and 1,024 columns per table. The number of rows and total size of the table are limited only by the available storage. The maximum number of bytes per row is 8,092. If you create tables with varchar, nvarchar, or varbinary columns in which the total defined width exceeds 8,092 bytes, the table is created but a warning message appears. Trying to insert more than 8,092 bytes into such a row or to update a row so that its total row size exceeds 8,092 produces an error message and the statement fails.

Each table can contain up to 249 nonclustered indexes and 1 clustered index. These include the indexes generated to support any PRIMARY KEY and UNIQUE constraints defined for the table.

SQL Server does not enforce an order in which DEFAULT, IDENTITY, ROWGUIDCOL, or column constraints are specified in a column definition.

Temporary Tables

You can create local and global temporary tables. Local temporary tables are visible only in the current session; global temporary tables are visible to all sessions.

Prefix local temporary table names with single number sign (#table_name), and prefix global temporary table names with a double number sign (##table_name).

SQL statements reference the temporary table using the value specified for table_name in the CREATE TABLE statement:

CREATE TABLE #MyTempTable (cola INT PRIMARY KEY)

INSERT INTO #MyTempTable VALUES (1)

If a local temporary table is created in a stored procedure or application that can be executed at the same time by several users, SQL Server has to be able to distinguish the tables created by the different users. SQL Server does this by internally appending a numeric suffix to each local temporary table name. The full name of a temporary table as stored in the sysobjects table in tempdb consists of table name specified in the CREATE TABLE statement and the system-generated numeric suffix. To allow for the suffix, table_name specified for a local temporary name cannot exceed 116 characters.

Temporary tables are automatically dropped when they go out of scope, unless they have already been explicitly dropped using DROP TABLE:

  • A local temporary table created in a stored procedure is dropped automatically when the stored procedure completes. The table can be referenced by any nested stored procedures executed by the stored procedure that created the table. The table cannot be referenced by the process which called the stored procedure that created the table.
  • All other local temporary tables are dropped automatically at the end of the current session.
  • Global temporary tables are automatically dropped when the session that created the table ends and all other tasks have stopped referencing them. The association between a task and a table is maintained only for the life of a single Transact-SQL statement. This means that a global temporary table is dropped at the completion of the last Transact-SQL statement that was actively referencing the table when the creating session ended.

A local temporary table created within a stored procedure or trigger is distinct from a temporary table with the same name created before the stored procedure or trigger is called. All references to the name within the stored procedure or trigger are resolved against the temporary table created in the procedure or trigger, not the version that existed before the procedure or trigger was called. Nested stored procedures can also create temporary tables with the same name as a temporary table created by the stored procedure that called it. All references to the table name in the nested stored procedure are resolved to the table created in the nested procedure, for example:

CREATE PROCEDURE Test2

AS

CREATE TABLE #t(x INT PRIMARY KEY)

INSERT INTO #t VALUES (2)

SELECT Test2Col = x FROM #t

GO

CREATE PROCEDURE Test1

AS

CREATE TABLE #t(x INT PRIMARY KEY)

INSERT INTO #t VALUES (1)

SELECT Test1Col = x FROM #t

EXEC Test2

GO

CREATE TABLE #t(x INT PRIMARY KEY)

INSERT INTO #t VALUES (99)

GO

EXEC Test1

GO

The results of running this script are:

(1 row(s) affected)

Test1Col

-----------

1

(1 row(s) affected)

Test2Col

-----------

2

When you create local or global temporary tables, the CREATE TABLE syntax supports constraint definitions with the exception of FOREIGN KEY constraints. If a FOREIGN KEY constraint is specified in a temporary table, the statement returns a warning message indicating that the constraint was skipped, and the table is still created without the FOREIGN KEY constraints. Temporary tables cannot be referenced in FOREIGN KEY constraints.

PRIMARY KEY Constraints
  • A table can contain only one PRIMARY KEY constraint.
  • The index generated by a PRIMARY KEY constraint cannot cause the number of indexes on the table to exceed 249 nonclustered indexes and 1 clustered index.
  • If CLUSTERED or NONCLUSTERED is not specified for a PRIMARY KEY constraint, CLUSTERED is used if there are no clustered indexes specified for UNIQUE constraints.
  • All columns defined within a PRIMARY KEY constraint must be defined as NOT NULL. If nullability is not specified, all columns participating in a PRIMARY KEY constraint have their nullability set to NOT NULL.
UNIQUE Constraints
  • If CLUSTERED or NONCLUSTERED is not specified for a UNIQUE constraint, NONCLUSTERED is used by default.
  • Each UNIQUE constraint generates an index. The number of UNIQUE constraints cannot cause the number of indexes on the table to exceed 249 nonclustered indexes and 1 clustered index.
FOREIGN KEY Constraints
  • When a value other than NULL is entered into the column of a FOREIGN KEY constraint, the value must exist in the referenced column; otherwise, a foreign key violation error message is returned.
  • FOREIGN KEY constraints can reference only tables within the same database on the same server. Cross-database referential integrity must be implemented through triggers. For more information, see CREATE TRIGGER.
  • FOREIGN KEY constraints can reference another column in the same table (a self-reference).
  • The REFERENCES clause of a column-level FOREIGN KEY constraint can list only one reference column, which must have the same data type as the column on which the constraint is defined.
  • The REFERENCES clause of a table-level FOREIGN KEY constraint must have the same number of reference columns as the number of columns in the constraint column list. The data type of each reference column must also be the same as the corresponding column in the column list.
  • A table can contain a maximum of 253 FOREIGN KEY constraints.
  • FOREIGN KEY constraints are not enforced on temporary tables.
  • A table can reference up to 253 different tables in its FOREIGN KEY constraints.
  • FOREIGN KEY constraints can reference only columns in PRIMARY KEY or UNIQUE constraints in the referenced table.
DEFAULT Definitions
  • A column can have only one DEFAULT definition.
  • A DEFAULT definition can contain constant values, functions, SQL-92 niladic functions, or NULL. The table shows the niladic functions and the values they return for the default during an INSERT statement.
SQL-92 niladic function | Value returned
CURRENT_TIMESTAMP | Current date and time
CURRENT_USER | Name of user performing insert
SESSION_USER | Name of user performing insert
SYSTEM_USER | Name of user performing insert
USER | Name of user performing insert

  • constant_expression in a DEFAULT definition cannot refer to another column in the table, or to other tables, views, or stored procedures.
  • DEFAULT definitions cannot be created on columns with a timestamp data type or columns with an IDENTITY property.
  • DEFAULT definitions cannot be created for columns with user-defined data types if the user-defined data type is bound to a default object.
CHECK Constraints
  • A column can have any number of CHECK constraints, and the condition can include multiple logical expressions combined with AND and OR. Multiple CHECK constraints for a column are validated in the order they are created.
  • The search condition must evaluate to a Boolean expression and cannot reference another table.
  • A column-level CHECK constraint can reference only the constrained column, and a table-level CHECK constraint can reference only columns in the same table.

    CHECK CONSTRAINTS and rules serve the same function of validating the data during INSERT and DELETE statements.

  • When a rule and one or more CHECK constraints exist for a column or columns, all restrictions are evaluated.
Additional Constraint Information
  • An index created for a constraint cannot be dropped with the DROP INDEX statement; the constraint must be dropped with the ALTER TABLE statement. An index created for and used by a constraint can be rebuilt with the DBCC DBREINDEX statement.
  • Constraint names must follow the rules for identifiers, except that the name cannot begin with a number sign (#). If constraint_name is not supplied, a system-generated name is assigned to the constraint. The constraint name appears in any error message about constraint violations.
  • When a constraint is violated in an INSERT, UPDATE, or DELETE statement, the statement is terminated. However, the transaction (if the statement is part of an explicit transaction) continues to be processed. You can use the ROLLBACK TRANSACTION statement with the transaction definition by checking the @@ERROR system function.

If a table has FOREIGN KEY or CHECK CONSTRAINTS and triggers, the constraint conditions are evaluated before the trigger is executed.

For a report on a table and its columns, use sp_help or sp_helpconstraint. To rename a table, use sp_rename. For a report on the views and stored procedures that depend on a table, use sp_depends.

Space is generally allocated to tables and indexes in increments of one extent at a time. When the table or index is created, it is allocated pages from mixed extents until it has enough pages to fill a uniform extent. After it has enough pages to fill a uniform extent, another extent is allocated each time the currently allocated extents become full. For a report on the amount of space allocated and used by a table, execute sp_spaceused.

Nullability Rules Within a Table Definition

The nullability of a column determines whether or not that column can allow a null value (NULL) as the data in that column. NULL is not zero or blank. It means no entry has been made or an explicit NULL was supplied, and it usually implies that the value is either unknown or not applicable.

When you create or alter a table with the CREATE TABLE or ALTER TABLE statements, database and session settings influence and possibly override the nullability of the data type used in a column definition. It is recommended that you always explicitly define a column as NULL or NOT NULL or, if you use a user-defined data type, that you allow the column to use the default nullability of the data type.

When not explicitly specified, column nullability follows these rules:

  • If the column is defined with a user-defined data type:
    • SQL Server uses the nullability specified when the data type was created. Use sp_help to get the default nullability of the data type.
  • If the column is defined with a system-supplied data type:
    • If the system-supplied data type has only one option, it takes precedence. timestamp data types must be NOT NULL.
    • If the setting of sp_dbcmptlevel is 65 or lower, bit data types default to NOT NULL if the column does not have an explicit NULL or NOT NULL. For more information, see sp_dbcmptlevel.
    • If any session settings are ON (turned on with the SET statement), then:

      ·If ANSI_NULL_DFLT_ON is ON, NULL is assigned.

      ·If ANSI_NULL_DFLT_OFF is ON, NOT NULL is assigned.

    • If any database settings are configured (changed with sp_dboption), then:

      ·If ANSI null default is true, NULL is assigned.

      ·If ANSI null default is false, NOT NULL is assigned.

  • When (neither of the ANSI_NULL_DFLT options is set) for the session and the database is set to the default (ANSI null default is false), then the SQL Server default of NOT NULL is assigned.

Note The SQL Server ODBC driver and Microsoft OLE DB Provider for SQL Server both default to having ANSI_NULL_DFLT_ON set to ON. ODBC and OLE DB users can configure this in ODBC data sources, or with connection attributes or properties set by the application.

Permissions

CREATE TABLE permission defaults to the members of the db_owner and db_ddladmin fixed database roles. Members of the db_owner fixed database role and members of the sysadmin fixed server role can transfer CREATE TABLE permission to other users.

Examples
A. Use PRIMARY KEY constraints

This example shows the column definition for a PRIMARY KEY constraint with a clustered index on the job_id column of the jobs table (allowing the system to supply the constraint name) in the pubs sample database.

job_id    smallint

        PRIMARY KEY CLUSTERED

This example shows how a name can be supplied for the PRIMARY KEY constraint. This constraint is used on the emp_id column of the employee table. This column is based on a user-defined data type.

emp_id    empid

        CONSTRAINT PK_emp_id PRIMARY KEY NONCLUSTERED

B. Use FOREIGN KEY constraints

A FOREIGN KEY constraint is used to reference another table. Foreign keys can be single-column keys or multicolumn keys. This example shows a single-column FOREIGN KEY constraint on the employee table that references the jobs table. Only the REFERENCES clause is required for a single-column FOREIGN KEY constraint.

job_id    smallint        NOT NULL

        DEFAULT 1

        REFERENCES jobs(job_id)

You can also explicitly use the FOREIGN KEY clause and restate the column attribute (note that the column name does not have to be the same in both tables).

FOREIGN KEY (job_id) REFERENCES jobs(job_id)

Multicolumn key constraints are created as table constraints. In the pubs database, the sales table includes a multicolumn PRIMARY KEY. This example shows how to reference this key from another table (an explicit constraint name is optional).

CONSTRAINT FK_sales_backorder FOREIGN KEY (stor_id, ord_num, title_id)     REFERENCES sales (stor_id, ord_num, title_id)

C. Use UNIQUE constraints

UNIQUE constraints are used to enforce uniqueness on nonprimary key columns. A PRIMARY KEY constraint column includes a restriction for uniqueness automatically; however, a UNIQUE constraint can allow null values. This example shows a column called pseudonym on the authors table. It enforces a restriction that authors’ pen names must be unique.

pseudonym varchar(30)    NULL

UNIQUE NONCLUSTERED

This example shows a UNIQUE constraint created on the stor_name and city columns of the stores table, where the stor_id is actually the PRIMARY KEY; no two stores in the same city should be the same.

CONSTRAINT U_store UNIQUE NONCLUSTERED (stor_name, city)

D. Use DEFAULT definitions

    Defaults supply a value (with the INSERT and UPDATE statements) when no value is supplied. In the pubs database, many DEFAULT definitions are used to ensure that valid data or placeholders are entered.

    On the jobs table, a character string default supplies a description (column job_desc) when the actual description is not entered explicitly.

    DEFAULT 'New Position - title not formalized yet'

    In the employee table, the employees can be employed by an imprint company or by the parent company. When an explicit company is not supplied, the parent company is entered (note that, as shown here, comments can be nested within the table definition).

    DEFAULT ('9952')

    /* By default the Parent Company Publisher is the company

    to whom each employee reports. */

    In addition to constants, DEFAULT definitions can include functions. Use this example to get the current date for an entry:

    DEFAULT (getdate())

    Niladic-functions can also improve data integrity. To keep track of the user who inserted a row, use the niladic-function for USER (do not surround the niladic-functions with parentheses):

    DEFAULT USER

    E. Use CHECK constraints

    This example shows restrictions made to the values entered into the min_lvl and max_lvl columns of the jobs table. Both of these constraints are unnamed:

    CHECK (min_lvl >= 10)

    and

    CHECK (max_lvl <= 250)

    This example shows a named constraint with a pattern restriction on the character data entered into the emp_id column of the employee table.

    CONSTRAINT CK_emp_id CHECK (emp_id LIKE

        '[A-Z][A-Z][A-Z][1-9][0-9][0-9][0-9][0-9][FM]' OR

        emp_id LIKE '[A-Z]-[A-Z][1-9][0-9][0-9][0-9][0-9][FM]')

    This example specifies that the pub_id must be within a specific list or follow a given pattern. This constraint is for the pub_id of the publishers table.

    CHECK (pub_id IN ('1389', '0736', '0877', '1622', '1756')

        OR pub_id LIKE '99[0-9][0-9]')

    F. Complete table definitions

    This example shows complete table definitions with all constraint definitions for three tables (jobs, employee, and publishers) created in the pubs database.

    /* ************************** jobs table ************************** */

    CREATE TABLE jobs

    (

        job_id  smallint

            IDENTITY(1,1)

            PRIMARY KEY CLUSTERED,

        job_desc        varchar(50)     NOT NULL

            DEFAULT 'New Position - title not formalized yet',

        min_lvl tinyint NOT NULL

            CHECK (min_lvl >= 10),

        max_lvl tinyint NOT NULL

            CHECK (max_lvl <= 250)

    )

    /* ************************* employee table ************************* */

    CREATE TABLE employee

    (

        emp_id  empid

            CONSTRAINT PK_emp_id PRIMARY KEY NONCLUSTERED

            CONSTRAINT CK_emp_id CHECK (emp_id LIKE

                '[A-Z][A-Z][A-Z][1-9][0-9][0-9][0-9][0-9][FM]' or

                emp_id LIKE '[A-Z]-[A-Z][1-9][0-9][0-9][0-9][0-9][FM]'),

            /* Each employee ID consists of three characters that

            represent the employee's initials, followed by a five

            digit number ranging from 10000 to 99999 and then the

            employee's gender (M or F). A (hyphen) - is acceptable

            for the middle initial. */

        fname   varchar(20)     NOT NULL,

        minit   char(1) NULL,

        lname   varchar(30)     NOT NULL,

        job_id  smallint        NOT NULL

            DEFAULT 1

            /* Entry job_id for new hires. */

            REFERENCES jobs(job_id),

        job_lvl tinyint

            DEFAULT 10,

            /* Entry job_lvl for new hires. */

        pub_id  char(4) NOT NULL

            DEFAULT ('9952')

            REFERENCES publishers(pub_id),

            /* By default, the Parent Company Publisher is the company

            to whom each employee reports. */

        hire_date       datetime        NOT NULL

            DEFAULT (getdate())

            /* By default, the current system date will be entered. */

    )

    /* ***************** publishers table ******************** */

    CREATE TABLE publishers

    (

        pub_id  char(4) NOT NULL

                CONSTRAINT UPKCL_pubind PRIMARY KEY CLUSTERED

                CHECK (pub_id IN ('1389', '0736', '0877', '1622', '1756')

                    OR pub_id LIKE '99[0-9][0-9]'),

        pub_name        varchar(40)     NULL,

        city            varchar(20)     NULL,

        state        char(2) NULL,

        country        varchar(30)     NULL

                    DEFAULT('USA')

    )

    G. Use the uniqueidentifier data type in a column

    This example creates a table with a uniqueidentifier column. It uses a PRIMARY KEY constraint to protect the table against users inserting duplicated values, and it uses the NEWID() function in the DEFAULT constraint to provide values for new rows.

    CREATE TABLE Globally_Unique_Data

    (guid uniqueidentifier

        CONSTRAINT Guid_Default

        DEFAULT NEWID(),

    Employee_Name varchar(60),

    CONSTRAINT Guid_PK PRIMARY KEY (Guid)

    )

    H. Use an expression for a computed column

      This example illustrates the use of an expression ((low + high)/2) for calculating the myavg computed column.

      CREATE TABLE mytable

          (

           low int,

           high int,

           myavg AS (low + high)/2

          )

      I. Use the USER_NAME function for a computed column

      This example uses the USER_NAME function in the myuser_name column.

      CREATE TABLE mylogintable

          (

           date_in datetime,

           user_id int,

           myuser_name AS USER_NAME()

          )

      J. Use NOT FOR REPLICATION

      This example shows using the IDENTITY property on a table that is subscribed to a replication. The table includes a CHECK constraint to ensure that the SaleID values generated on this system do not grow into the range assigned to the replication Publisher.

      CREATE TABLE Sales

          (SaleID INT IDENTITY(100000,1) NOT FOR REPLICATION,

                       CHECK NOT FOR REPLICATION (SaleID <= 199999),

           SalesRegion CHAR(2),

          CONSTRAINT ID_PK PRIMARY KEY (SaleID)

          )

      See Also
      ALTER TABLE | DROP TABLE
CREATE INDEX | sp_addtype
CREATE RULE | sp_depends
CREATE VIEW | sp_help
Data Types | sp_helpconstraint
DROP INDEX | sp_rename
DROP RULE | sp_spaceused


CREATE TRIGGER

Creates a trigger, which is a special kind of stored procedure that executes automatically when a user attempts the specified data-modification statement on the specified table. Microsoft® SQL Server™ allows the creation of multiple triggers for any given INSERT, UPDATE, or DELETE statement.

Syntax

CREATE TRIGGER trigger_name
ON table
[WITH ENCRYPTION]
{
{FOR { [DELETE] [,] [INSERT] [,] [UPDATE] }
[WITH APPEND]
[NOT FOR REPLICATION]
AS
sql_statement […n]
}
|
{FOR { [INSERT] [,] [UPDATE] }
[WITH APPEND]
[NOT FOR REPLICATION]
AS
{ IF UPDATE (column)
[{AND | OR} UPDATE (column)]
[…n]
| IF (COLUMNS_UPDATED() {bitwise_operator} updated_bitmask)
{ comparison_operator} column_bitmask […n]
}
sql_statement [ …n]
}
}

Arguments
trigger_name
Is the name of the trigger. A trigger name must conform to the rules for identifiers and must be unique within the database. Specifying the trigger owner name is optional.
table
Is the table on which the trigger is executed; sometimes called the trigger table. Specifying the owner name of the table is optional. Views cannot be specified.
WITH ENCRYPTION
Encrypts the syscomments entries that contain the text of CREATE TRIGGER.
{ [DELETE] [,] [INSERT] [,] [UPDATE] } | { [INSERT] [,] [UPDATE]}
Are keywords that specify which data modification statements, when attempted against this table, activate the trigger. At least one option must be specified. Any combination of these in any order is allowed in the trigger definition. If more than one option is specified, separate the options with commas.
WITH APPEND

Specifies that an additional trigger of an existing type should be added. Use of this optional clause is needed only when the compatibility level is less than or equal to 65. If the compatibility level is greater than or equal to 70, the WITH APPEND optional clause is not needed to add an additional trigger of an existing type (this is the default behavior of CREATE TRIGGER with the compatibility level setting greater than or equal to 70.) For more information, see sp_dbcmptlevel.

NOT FOR REPLICATION
Indicates that the trigger should not be executed when a replication process modifies the table involved in the trigger.
AS
Are the actions the trigger is to take.
sql_statement
Is the trigger condition(s) and action(s). Trigger conditions specify additional criteria that determine whether the attempted DELETE, INSERT, or UPDATE statements cause the trigger action(s) to be carried out.

The trigger actions specified in the Transact-SQL statements go into effect when the user action (DELETE, INSERT, or UPDATE) is attempted.

Triggers can include any number and kind of Transact-SQL statements except SELECT. A trigger is designed to check or change data based on a data modification statement; it should not return data to the user. The Transact-SQL statements in a trigger often include control-of-flow language. A few special tables are used in CREATE TRIGGER statements:

  • deleted and inserted are logical (conceptual) tables. They are structurally similar to the table on which the trigger is defined (that is, the table on which the user action is attempted) and hold the old values or new values of the rows that may be changed by the user action. For example, to retrieve all values in the deleted table, use:

SELECT *

FROM deleted

  • In a DELETE, INSERT, or UPDATE trigger, SQL Server does not allow text, ntext or image column references in the inserted and deleted tables if the compatibility level is equal to 70. The text, ntext, and image values in the inserted and deleted tables cannot be accessed. To retrieve the new value in either an INSERT or UPDATE trigger, join the inserted table with the original update table. When the compatibility level is 65 or lower, null values are returned for inserted or deleted text, ntext, or image columns that allow null values; zero-length strings are returned if the columns are not nullable.
n
Is a placeholder indicating that multiple Transact-SQL statements can be included in the trigger. For the IF UPDATE (column) statement, multiple columns can be included by repeating the UPDATE (column) clause.
IF UPDATE (column)
Tests for an INSERT or UPDATE action to a specified column and is not used with DELETE operations. More than one column can be specified. Because the table name is specified in the ON clause, do not include the table name before the column name in an IF UPDATE clause. To test for an INSERT or UPDATE action for more than one column, specify a separate UPDATE(column) clause following the first one.

Note The IF UPDATE (column) clause functions identically to an IF, IF…ELSE or WHILE statement and can use the BEGIN…END block. For more information, see Control-of-Flow Language.

UPDATE(column) can be used anywhere inside the body of the trigger.

column
Is the name of the column to test for either an INSERT or UPDATE action. This column can be of any data type supported by SQL Server. For more information, see Data Types.
IF (COLUMNS_UPDATED())
Tests, in an INSERT or UPDATE trigger only, whether the mentioned column or columns were inserted or updated. COLUMNS_UPDATED returns a varbinary bit pattern that indicates which columns in the table were inserted or updated.

COLUMNS_UPDATED can be used anywhere inside the body of the trigger.

bitwise_operator
Is the bitwise operator to use in the comparison.
updated_bitmask
Is the integer bitmask of those columns actually updated or inserted. For example, table t1 contains columns C1, C2, C3, C4, and C5. To check whether columns C2, C3, and C4 are all updated (with table t1 having an UPDATE trigger), specify a value of 14. To check whether only column C2 is updated, specify a value of 2.
comparison_operator
Is the comparison operator. Use the equals sign (=) to check whether all columns specified in updated_bitmask are actually updated. Use the greater than symbol (>) to check whether any or some of the columns specified in updated_bitmask are updated.
column_bitmask
Is the integer bitmask of those columns to check whether they are updated or inserted.
Remarks

Triggers are often used for enforcing business rules and data integrity. SQL Server provides declarative referential integrity (DRI) through the table creation statements (ALTER TABLE and CREATE TABLE); however, DRI does not provide cross-database referential integrity. To enforce referential integrity (rules about the relationships between the primary and foreign keys of tables), use primary and foreign key constraints (the PRIMARY KEY and FOREIGN KEY keywords of ALTER TABLE and CREATE TABLE). If constraints exist on the trigger table, they are checked prior to trigger execution. If either PRIMARY KEY or FOREIGN KEY constraints are violated, the trigger is not executed (fired).

Note Whether SQL Server interprets an empty string as a single space or as a true empty string is controlled by the setting of sp_dbcmptlevel. If the compatibility level is less than or equal to 65, SQL Server interprets empty strings as single spaces. If the compatibility level is equal to 70, SQL Server interprets empty strings as empty strings. For more information, see sp_dbcmptlevel.

Trigger Limitations

CREATE TRIGGER must be the first statement in the batch and can apply to only one table.

A trigger is created only in the current database; however, a trigger can reference objects outside the current database.

If the trigger owner name is specified (to qualify the trigger), qualify the table name in the same way.

The same trigger action can be defined for more than one user action (for example, INSERT and UPDATE) in the same CREATE TRIGGER statement.

Any SET statement can be specified inside a trigger. The SET option chosen remains in effect during the execution of the trigger and then reverts to its former setting.

When a trigger fires, results are returned to the calling application, just as with stored procedures. To eliminate having results returned to an application due to a trigger firing, do not include either SELECT statements that return results, or statements that perform variable assignment in a trigger. A trigger that includes either SELECT statements that return results to the user or statements that perform variable assignment requires special handling; these returned results would have to be written into every application in which modifications to the trigger table are allowed. If variable assignment must occur in a trigger, use a SET NOCOUNT statement at the beginning of the trigger to eliminate the return of any result sets.

A trigger cannot be created on a view.

A TRUNCATE TABLE statement is not caught by a DELETE trigger. Although a TRUNCATE TABLE statement is, in effect, a DELETE without a WHERE clause (it removes all rows), it is not logged and thus cannot execute a trigger. Because permission for the TRUNCATE TABLE statement defaults to the table owner and is not transferable, only the table owner should be concerned about inadvertently circumventing a DELETE trigger with a TRUNCATE TABLE statement.

The WRITETEXT statement, whether logged or unlogged, does not activate a trigger.

These Transact-SQL statements are not allowed in a trigger:

ALTER DATABASE | ALTER PROCEDURE | ALTER TABLE
ALTER TRIGGER | ALTER VIEW | CREATE DATABASE
CREATE DEFAULT | CREATE INDEX | CREATE PROCEDURE
CREATE RULE | CREATE SCHEMA | CREATE TABLE
CREATE TRIGGER | CREATE VIEW | DENY
DISK INIT | DISK RESIZE | DROP DATABASE
DROP DEFAULT | DROP INDEX | DROP PROCEDURE
DROP RULE | DROP TABLE | DROP TRIGGER
DROP VIEW | GRANT | LOAD DATABASE
LOAD LOG | RESTORE DATABASE | RESTORE LOG
REVOKE | RECONFIGURE |
TRUNCATE TABLE | UPDATE STATISTICS |

Note Because SQL Server does not support user-defined triggers on system tables, it is recommended that no user-defined triggers be created on system tables.

Multiple Triggers

SQL Server allows multiple triggers to be created for each data modification event (DELETE, INSERT, or UPDATE). For example, if CREATE TRIGGER FOR UPDATE is executed for a table that already has an UPDATE trigger, then an additional update trigger is created. In earlier versions, only one trigger for each data modification event (INSERT, UPDATE, DELETE) was allowed for each table.

Note The default behavior for CREATE TRIGGER (with the compatibility level of 70) is to add additional triggers to existing triggers, if the trigger names differ. If trigger names are the same, SQL Server returns an error message. However, if the compatibility level is equal to or less than 65, any new triggers created with the CREATE TRIGGER statement replace any existing triggers of the same type, even if the trigger names are different. For more information, see sp_dbcmptlevel.

Recursive Triggers

SQL Server also allows recursive invocation of triggers when the recursive triggers setting is enabled in sp_dboption.

Recursive triggers allow two types of recursion to occur:

  • Indirect recursion
  • Direct recursion

With indirect recursion, an application updates table T1, which fires trigger TR1, updating table T2. In this scenario, trigger T2 then fires and updates table T1.

With direct recursion, the application updates table T1, which fires trigger TR1, updating table T1. Because table T1 has been updated, trigger TR1 fires again, and so on.

This example uses both indirect and direct trigger recursion. Assume that two update triggers, TR1 and TR2, are defined on table T1. Trigger TR1 updates table T1 recursively. An UPDATE statement executes each TR1 and TR2 one time. In addition, the execution of TR1 triggers the execution of TR1 (recursively) and TR2. The inserted and deleted tables for a given trigger contain rows corresponding only to the UPDATE statement that invoked the trigger.

Note The above behavior occurs only if the recursive triggers setting of sp_dboption is enabled. There is no defined order in which multiple triggers defined for a given event are executed. Each trigger should be self-contained.

If any of the triggers do a ROLLBACK TRANSACTION, regardless of the nesting level, no further triggers are executed.

Nested Triggers

Triggers can be nested up to 32 levels. If a trigger changes a table on which there is another trigger, the second trigger is activated and can then call a third trigger, and so on. If any trigger in the chain sets off an infinite loop, the nesting level is exceeded and the trigger is canceled. To disable nested triggers, set the nested triggers option of sp_configure to 0 (off). The default configuration allows nested triggers. If nested triggers is off, recursive triggers is also disabled, regardless of the recursive triggers setting of sp_dboption.

Deferred Name Resolution

SQL Server allows Transact-SQL stored procedures, triggers, and batches to refer to tables that do not exist at compile time. This ability is called deferred name resolution. However, if the Transact-SQL stored procedure, trigger, or batch refers to a table defined in the stored procedure or trigger, a warning is issued at creation time only if the compatibility level setting (set by executing sp_dbcmptlevel) is equal to 65. A warning is issued at compile time if a batch is used. An error message is returned at execution time if the table referenced does not exist.

Permission

CREATE TRIGGER permission defaults to the table owner on which the trigger is defined, or to members of the db_owner and db_ddladmin fixed database roles, and is not transferable.

Examples
A. Use a trigger with a reminder message

This example trigger prints a message to the client when anyone tries to add or change data in the titles table.

Note Message 50009 is a user-defined message in sysmessages. For information about creating user-defined messages, see sp_addmessage.

USE pubs

IF EXISTS (SELECT name FROM sysobjects

        WHERE name = 'reminder' AND type = 'TR')

    DROP TRIGGER reminder

GO

CREATE TRIGGER reminder

ON titles

FOR INSERT, UPDATE

AS RAISERROR (50009, 16, 10)

GO

B. Use a trigger with a reminder e-mail message

This example sends an e-mail message to a specified person (MaryM) when the titles table changes.

USE pubs

IF EXISTS (SELECT name FROM sysobjects

        WHERE name = 'reminder' AND type = 'TR')

    DROP TRIGGER reminder

GO

CREATE TRIGGER reminder

ON titles

FOR INSERT, UPDATE, DELETE

AS

    EXEC master..xp_sendmail 'MaryM',

        'Don''t forget to print a report for the distributors.'

GO

C. Use a trigger business rule between the employee and jobs tables

Because CHECK constraints can reference only the columns on which the column- or table-level constraint has been defined, any cross-table constraints (in this case, business rules) must be defined as triggers.

This example creates a trigger that, when an employee job level is inserted or updated, checks that the specified employee job level (job_lvls), on which salaries are based, is within the range defined for the job. To get the appropriate range, the jobs table must be referenced.

USE pubs

IF EXISTS (SELECT name FROM sysobjects

        WHERE name = 'reminder' AND type = 'TR')

    DROP TRIGGER reminder

GO

CREATE TRIGGER employee_insupd

ON employee

FOR INSERT, UPDATE

AS

/* Get the range of level for this job type from the jobs table. */

DECLARE @min_lvl tinyint,

    @max_lvl tinyint,

    @emp_lvl tinyint,

    @job_id smallint

SELECT @min_lvl = min_lvl,

    @max_lvl = max_lvl,

    @emp_lvl = i.job_lvl,

    @job_id = i.job_id

FROM employee e INNER JOIN inserted i ON e.emp_id = i.emp_id

    JOIN jobs j ON j.job_id = i.job_id

IF (@job_id = 1) and (@emp_lvl <> 10)

BEGIN

    RAISERROR ('Job id 1 expects the default level of 10.', 16, 1)

    ROLLBACK TRANSACTION

END

ELSE

IF NOT (@emp_lvl BETWEEN @min_lvl AND @max_lvl)

BEGIN

    RAISERROR ('The level for job_id:%d should be between %d and %d.',

        16, 1, @job_id, @min_lvl, @max_lvl)

    ROLLBACK TRANSACTION

END

D. Use deferred name resolution

This example creates two triggers to illustrate deferred name resolution.

USE pubs

IF EXISTS (SELECT name FROM sysobjects

        WHERE name = 'trig1' AND type = 'TR')

    DROP TRIGGER trig1

GO

-- Creating a trigger on a nonexistent table.

CREATE TRIGGER trig1

on authors

FOR INSERT, UPDATE, DELETE

AS

    SELECT a.au_lname, a.au_fname, x.info

    FROM authors a INNER JOIN does_not_exist x

        ON a.au_id = x.au_id

GO

-- Here is the statement to actually see the text of the trigger.

SELECT o.id, c.text

FROM sysobjects o INNER JOIN syscomments c

    ON o.id = c.id

WHERE o.type = 'TR' and o.name = 'trig1'

-- Creating a trigger on an existing table, but with a nonexistent

-- column.

USE pubs

IF EXISTS (SELECT name FROM sysobjects

        WHERE name = 'trig2' AND type = 'TR')

    DROP TRIGGER trig2

GO

CREATE TRIGGER trig2

ON authors

FOR INSERT, UPDATE

AS

    DECLARE @fax varchar(12)

    SELECT @fax = phone

    FROM authors

GO

-- Here is the statement to actually see the text of the trigger.

SELECT o.id, c.text

FROM sysobjects o INNER JOIN syscomments c

    ON o.id = c.id

WHERE o.type = 'TR' and o.name = 'trig2'

E. Use COLUMNS_UPDATED

This example creates two tables: an employeeData table and an auditEmployeeData table. The employeeData table, which holds sensitive employee payroll information, can be modified by members of the human resources department. If the employee’s social security number (SSN), yearly salary or bank account number is changed, an audit record is generated and inserted into the auditEmployeeData audit table.

By using the COLUMNS_UPDATED() function, it is possible to test quickly for any changes to these columns that contain sensitive employee information.

USE pubs

IF EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES

        WHERE TABLE_NAME = 'employeeData')

    DROP TABLE employeeData

IF EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES

        WHERE TABLE_NAME = 'auditEmployeeData')

    DROP TABLE auditEmployeeData

GO

CREATE TABLE employeeData (

        emp_id                int NOT NULL,

        emp_bankAccountNumber char (10) NOT NULL,

        emp_salary            int NOT NULL,

        emp_SSN               char (11) NOT NULL,

        emp_lname             nchar (32) NOT NULL,

        emp_fname             nchar (32) NOT NULL,

        emp_manager           int NOT NULL

        )

GO

CREATE TABLE auditEmployeeData (

        audit_log_id                uniqueidentifier DEFAULT NEWID(),

        audit_log_type              char (3) NOT NULL,

        audit_emp_id                int NOT NULL,

        audit_emp_bankAccountNumber char (10) NULL,

        audit_emp_salary            int NULL,

        audit_emp_SSN               char (11) NULL,

        audit_user                  sysname DEFAULT SUSER_SNAME(),

        audit_changed               datetime DEFAULT GETDATE()

        )

GO

CREATE TRIGGER updEmployeeData

ON employeeData

FOR update AS

-- Check whether columns 2, 3 or 4 has been updated. If any or all of

-- columns 2, 3 or 4 have been changed, create an audit record.

-- The bitmask is: power(2,(2-1))+power(2,(3-1))+power(2,(4-1)) = 14

-- To check if all columns 2, 3, and 4 are updated, use = 14 in place of

-- >0 (below).

    IF (COLUMNS_UPDATED() & 14) > 0

-- Use IF (COLUMNS_UPDATED() & 14) = 14 to see if all of columns 2, 3,

-- and 4 are updated.

    BEGIN

    -- Audit OLD record.

    INSERT INTO auditEmployeeData

        (audit_log_type,

        audit_emp_id,

        audit_emp_bankAccountNumber,

        audit_emp_salary,

        audit_emp_SSN)

        SELECT    'OLD',

                del.emp_id,

                del.emp_bankAccountNumber,

                del.emp_salary,

                del.emp_SSN

            FROM deleted del

    -- Audit NEW record.

    INSERT INTO auditEmployeeData

        (audit_log_type,

        audit_emp_id,

        audit_emp_bankAccountNumber,

        audit_emp_salary,

        audit_emp_SSN)

        SELECT    'NEW',

                ins.emp_id,

                ins.emp_bankAccountNumber,

                ins.emp_salary,

                ins.emp_SSN

            FROM inserted ins

    END

GO

--Inserting a new employee does not cause the UPDATE trigger to fire.

INSERT INTO employeeData

    VALUES ( 101, 'USA-987-01', 23000, 'R-M53550M', N'Mendel', N'Roland', 32)

GO

-- Updating the employee record for employee number 101 to change the

-- salary to 51000 causes the UPDATE trigger to fire and an audit trail

-- to be produced.

UPDATE employeeData

    SET emp_salary = 51000

    WHERE emp_id = 101

GO

SELECT * FROM auditEmployeeData

GO

--Updating the employee record for employee number 101 to change both the bank account number and social security number (SSN) causes the UPDATE trigger to fire and an audit trail to be produced.

UPDATE employeeData

    SET emp_bankAccountNumber = '133146A0', emp_SSN = 'R-M53550M'

    WHERE emp_id = 101

GO

SELECT * FROM auditEmployeeData

GO

See Also
ALTER TABLE | sp_help
ALTER TRIGGER | sp_helptext
CREATE TABLE | sp_rename
DROP TRIGGER | sp_spaceused
sp_depends |


CREATE VIEW

Creates a virtual table that represents the data in one or more tables in an alternative way. Views can be used as security mechanisms by granting permission on a view but not on the underlying (base) tables.

Syntax

CREATE VIEW view_name [(column [,…n])]
[WITH ENCRYPTION]
AS
select_statement
[WITH CHECK OPTION]

Arguments
view_name
Is the name of the view. View names must follow the rules for identifiers. Specifying the view owner name is optional.
column
Is the name to be used for a column in a view. Naming a column in CREATE VIEW is necessary only when a column is derived from an arithmetic expression, a function, or a constant, when two or more columns may otherwise have the same name (usually because of a join), or when a column in a view is given a name different from that of the column from which it is derived. Column names can also be assigned in the SELECT statement.

If column is not specified, the view columns acquire the same names as the columns in the SELECT statement.

Note In the columns for the view, the permissions for a column name apply across a CREATE VIEW or ALTER VIEW statement, regardless of the source of the underlying data. For example, if permissions are granted on the title_id column in a CREATE VIEW statement, an ALTER VIEW statement can name the title_id column with a different column name, such as qty, and still have the permissions associated with the view using title_id.

n
Is a placeholder indicating that multiple columns can be specified.
WITH ENCRYPTION
Encrypts the syscomments entries that contain the text of the CREATE VIEW statement.
AS
Are the actions the view is to take.
select_statement
Is the SELECT statement that defines the view. It can use more than one table and other views. To select from the objects referenced in the SELECT clause of a view being created, it is necessary to have the appropriate permissions.

A view does not have to be a simple subset of the rows and columns of one particular table. A view can be created using more than one table or other views with a SELECT clause of any complexity.

There are, however, a few restrictions on the SELECT clauses in a view definition. A CREATE VIEW statement cannot:

  • Include ORDER BY, COMPUTE, or COMPUTE BY clauses.
  • Include the INTO keyword.
  • Reference a temporary table.

Because select_statement uses the SELECT statement, it is valid to use <join_hint> and <table_hint> hints as specified in the FROM clause. For more information, see FROM and SELECT.

Functions can be used in the select_statement.

select_statement can use multiple SELECT statements separated by UNION to create a query using partitioned data.

For partitioned data to be used in ALTER VIEW or CREATE VIEW, constraint values must be able to be verified. If constraint checking has been disabled, reenable constraint checking with either the WITH CHECK option or the CHECK constraint_name options of ALTER TABLE. It is not necessary to have constraints to use partitioned data; however, query optimization generates less optimal plans without constraints.

WITH CHECK OPTION
Forces all data modification statements executed against the view to adhere to the criteria set within select_statement. When a row is modified through a view, the WITH CHECK OPTION guarantees that the data remains visible through the view after the modification has been committed.
Remarks

A view can be created only in the current database. A view can reference a maximum of 1,024 columns.

When querying through a view, Microsoft® SQL Server™ checks to make sure that all the database objects referenced anywhere in the statement exist, that they are valid in the context of the statement, and that data modification statements do not violate any data integrity rules. A check that fails returns an error message. A successful check translates the action into an action against the underlying table(s).

If a view depends on a table (or view) that has been dropped, SQL Server produces an error message if anyone tries to use the view. If a new table (or view) is created, even if the table structure does not change from the previous base table, to replace the one dropped, the view again becomes usable. If the new table (or view) structure changes, then the view must be dropped and re-created.

When a view is created, the name of the view is stored in the sysobjects table. Information about the columns defined in a view is added to the syscolumns table, and information about the view dependencies is added to the sysdepends table. In addition, the text of the CREATE VIEW statement is added to the syscomments table. This is similar to a stored procedure; but when a view is executed for the first time, only its query tree is stored in procedure cache. Each time a view is accessed, its execution plan is recompiled.

A view is updatable if:

  • select_statement has no aggregate functions in the select list and does not contain the TOP, GROUP BY, UNION, or DISTINCT clauses. Aggregate functions can be used in a in a subquery in the FROM clause as long as the values returned by the functions are not modified. For more information, see Aggregate Functions.
  • select_statement has no derived columns in the select list. Derived columns are result set columns formed by anything other than a simple column expression, such as using functions or addition or subtraction operators.
  • The FROM clause in the select_statement references at least one table. select_statement must have more than nontabular expressions, which are expressions that are not derived from a table. For example, this view is not updatable:

    CREATE VIEW NoTable AS

    SELECT GETDATE() AS CurrentDate,

           @@LANGUAGE AS CurrentLanguage,

           CURRENT_USER AS CurrentUser

INSERT, UPDATE, and DELETE statements must also meet certain qualifications before they can reference an updatable view. UPDATE and INSERT statements can reference a view only if the view is updatable and the UPDATE or INSERT statement is written so that it modifies data in only one of the base tables referenced in FROM clause of the view. A DELETE statement can reference only a view that is updatable; the view must also reference exactly one table in its FROM clause.

SQL Server saves the settings of SET QUOTED_IDENTIFIER and SET ANSI_NULLS when a view is created. These original settings are restored when the view is used. Therefore, any client session settings for SET QUOTED_IDENTIFIER and SET ANSI_NULLS is ignored.

Note Whether SQL Server interprets an empty string as a single space or as a true empty string is controlled by the setting of sp_dbcmptlevel. If the compatibility level is less than or equal to 65, SQL Server interprets empty strings as single spaces. If the compatibility level is equal to 70, SQL Server interprets empty strings as empty strings. For more information, see sp_dbcmptlevel.

Permissions

CREATE VIEW permission defaults to the members of the db_owner and db_ddladmin fixed database roles. Members of the sysadmin fixed server role and the db_owner fixed database role can transfer CREATE VIEW permission to other users.

Examples
A. Use a simple CREATE VIEW

This example creates a view with a simple SELECT statement. A simple view is helpful when a combination of columns is queried frequently.

USE pubs

IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS

        WHERE TABLE_NAME = 'titles_view')

    DROP VIEW titles_view

GO

CREATE VIEW titles_view

AS

SELECT title, type, price, pubdate

FROM titles

GO

B. Use WITH ENCRYPTION\

This example uses the WITH ENCRYPTION option and shows computed columns, renamed columns, and multiple columns.

USE pubs

IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS

        WHERE TABLE_NAME = 'accounts')

    DROP VIEW accounts

GO

CREATE VIEW accounts (title, advance, amt_due)

WITH ENCRYPTION

AS

SELECT title, advance, price * royalty * ytd_sales

FROM titles

WHERE price > $5

GO

Here is the result set:

The object's comments have been encrypted.

Here is the query to retrieve the identification number and text of the encrypted stored procedure:

USE pubs

GO

SELECT c.id, c.text

FROM syscomments c, sysobjects o

WHERE c.id = o.id and o.name = 'accounts'

GO

Here is the result set:

Note The text column output is shown on a separate line. When the procedure is executed, this information appears on the same line as the id column information.

id          text

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

1925581898  ??????????????????????????????????????????????_??????????????????????????????????????????????????????????????????????????????????????????????????????????

(1 row(s) affected)

C.Use WITH CHECK OPTION

This example shows a view named CAonly that allows data modifications to apply only to authors within the state of California.

USE pubs

IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS

        WHERE TABLE_NAME = 'CAonly')

    DROP VIEW CAonly

GO

CREATE VIEW CAonly

AS

SELECT au_lname, au_fname, city, state

FROM authors

WHERE state = 'CA'

WITH CHECK OPTION

GO

D. Use built-in functions within a view

This example shows a view definition that includes a built-in function. When you use functions, the derived column must include a column name in the CREATE VIEW statement.

USE pubs

IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS

        WHERE TABLE_NAME = 'categories')

    DROP VIEW categories

GO

CREATE VIEW categories (category, average_price)

AS

SELECT type, AVG(price)

FROM titles

GROUP BY type

GO

E. Use @@ROWCOUNT function in a view

    This example uses the @@ROWCOUNT function as part of the view definition.

    USE pubs

    IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS

            WHERE TABLE_NAME = 'myview')

        DROP VIEW myview

    GO

    CREATE VIEW myview

    AS

        SELECT au_lname, au_fname, @@ROWCOUNT AS bar

        FROM authors

        WHERE state = 'UT'

    GO

    SELECT *

    FROM myview

    F. Use partitioned data

    This example uses tables named SUPPLY1, SUPPLY2, SUPPLY3, and SUPPLY4, which correspond to the supplier tables from four offices, located in different countries.

    CREATE VIEW all_supplier_view

    AS

    SELECT *

    FROM SUPPLY1

    UNION

    SELECT *

    FROM SUPPLY2

    UNION

    SELECT *

    FROM SUPPLY3

    UNION

    SELECT *

    FROM SUPPLY4

    See Also
    ALTER TABLE | sp_help
ALTER VIEW | sp_helptext
DELETE | sp_rename
DROP VIEW | System Tables
INSERT | UPDATE
sp_depends |


CURRENT_TIMESTAMP

Returns the current date and time. This function is equivalent to GETDATE().

Syntax

CURRENT_TIMESTAMP

Return Types

datetime

Examples
A. Use CURRENT_TIMESTAMP to return the current date and time

    This example returns the value of CURRENT_TIMESTAMP and a text description.

    SELECT 'The current time is: '+ CONVERT(char(30), CURRENT_TIMESTAMP)

    Here is the result set:

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

    The current time is: Feb 24 1998  3:45PM

    (1 row(s) affected)

    B. Use CURRENT_TIMESTAMP as a DEFAULT constraint

    This example creates a table that uses CURRENT_TIMESTAMP as a DEFAULT constraint for the sales_date column of a sales row.

    USE pubs

    GO

    CREATE TABLE sales2

    (

     sales_id int IDENTITY(10000, 1) NOT NULL,

     cust_id  int NOT NULL,

     sales_date datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,

     sales_amt money NOT NULL,

     delivery_date datetime NOT NULL DEFAULT DATEADD(dd, 10, GETDATE())

    )

    GO

    INSERT sales2 (cust_id, sales_amt)

        VALUES (20000, 550)

    This query selects all information from the sales2 table.

    USE pubs

    GO

    SELECT *

    FROM sales2

    GO

    Here is the result set:

    sales_id    cust_id    sales_date          sales_amt delivery_date

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

    10000       20000      Mar 4 1998 10:06AM  550.00    Mar 14 1998 10:06AM

    (1 row(s) affected)

    See Also
    ALTER TABLE | System Functions
CREATE TABLE |


CURRENT_USER

Returns the current user. This function is equivalent to USER_NAME().

Syntax

CURRENT_USER

Return Types

sysname

Examples
A. Use CURRENT_USER to return the current username

This example declares a variable as char, assigns the current value of CURRENT_USER to it, and then returns the variable with a text description.

SELECT 'The current user is: '+ convert(char(30), CURRENT_USER)

Here is the result set:

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

The current user is: dbo

(1 row(s) affected)

B. Use CURRENT_USER as a DEFAULT constraint

    This example creates a table that uses CURRENT_USER as a DEFAULT constraint for the order_person column on a sales row.

    USE pubs

    IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES

            WHERE TABLE_NAME = 'orders2')

        DROP TABLE orders2

    GO

    SET NOCOUNT ON

    CREATE TABLE orders2

    (

     order_id int IDENTITY(1000, 1) NOT NULL,

     cust_id  int NOT NULL,

     order_date datetime NOT NULL DEFAULT GETDATE(),

     order_amt money NOT NULL,

     order_person char(30) NOT NULL DEFAULT CURRENT_USER

    )

    GO

    INSERT orders2 (cust_id, order_amt)

    VALUES (5105, 577.95)

    GO

    SET NOCOUNT OFF

    This query selects all information from the orders2 table.

    SELECT *

    FROM orders2

    Here is the result set:

    order_id    cust_id     order_date             order_amt    order_person

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

    1000        5105        Mar 4 1998 10:13AM      577.95           dbo

    (1 row(s) affected)

    See Also
    ALTER TABLE | System Functions
CREATE TABLE |


cursor

A data type for variables or stored procedure OUTPUT parameters that contain a reference to a cursor. Any variables created with the cursor data type are nullable.

The operations that can reference variables and parameters having a cursor data type are:

  • The DECLARE @local_variable and SET @local_variable statements.
  • The OPEN, FETCH, CLOSE, and DEALLOCATE cursor statements.
  • Stored procedure output parameters.
  • The CURSOR_STATUS function.
  • The sp_cursor_list, sp_describe_cursor, sp_describe_cursor_tables, and sp_describe_cursor_columns system stored procedures.

Important The cursor data type cannot be used for a column in a CREATE TABLE statement.

See Also
CAST and CONVERT | DECLARE @local_variable
CURSOR_STATUS | DECLARE CURSOR
Data Types | SET @local_variable


CURSOR_STATUS

A scalar function that allows the caller of a stored procedure to determine whether or not the procedure has returned a cursor and result set for a given parameter.

Syntax

CURSOR_STATUS
(
{'local', 'cursor_name'}
| {'global', 'cursor_name'}
| {'variable', 'cursor_variable'}
)

Arguments
'local'
Specifies a constant that indicates the source of the cursor is a local cursor name.
'cursor_name'
Is the name of the cursor. A cursor name must conform to the rules for identifiers.
'global'
Specifies a constant that indicates the source of the cursor is a global cursor name.
'variable'
Specifies a constant that indicates the source of the cursor is a local variable.
'cursor_variable'
Is the name of the cursor variable. A cursor variable must be defined using the cursor data type.
Return Types

smallint

Return value | Cursor name | Cursor variable
1 | The result set of the cursor has at least one row and: For insensitive and keyset cursors, the result set has at least one row. For dynamic cursors, the result set can have zero, one, or more rows. | The cursor allocated to this variable is open and: For insensitive and keyset cursors, the result set has at least one row. For dynamic cursors, the result set can have zero, one, or more rows.
0 | The result set of the cursor is empty.* | The cursor allocated to this variable is open, but the result set is definitely empty.*
-1 | The cursor is closed. | The cursor allocated to this variable is closed.
-2 | Not applicable. | Can be: No cursor was assigned to this OUTPUT variable by the previously called procedure. A cursor was assigned to this OUTPUT variable by the previously called procedure, but it was in a closed state upon completion of the procedure. Therefore, the cursor is deallocated and not returned to the calling procedure. There is no cursor assigned to a declared cursor variable.
-3 | A cursor with the specified name does not exist. | A cursor variable with the specified name does not exist, or if one exists it has not yet had a cursor allocated to it.
* Dynamic cursors never return this result.

Examples

This example creates a procedure named lake_list and uses the output from executing lake_list as a check for CURSOR_STATUS.

Note This example depends on a procedure named check_authority, which has not been created.

USE pubs

IF EXISTS (SELECT name FROM sysobjects

        WHERE name = 'lake_list' AND type = 'P')

    DROP PROCEDURE lake_list

GO

CREATE PROCEDURE lake_list

    ( @region varchar(30),

     @size integer,

     @lake_list_cursor CURSOR VARYING OUTPUT )

AS

BEGIN

    DECLARE @ok SMALLINT

    EXECUTE check_authority @region, username, @ok OUTPUT

    IF @ok = 1

        BEGIN

        SET @lake_list_cursor =CURSOR LOCAL SCROLL FOR

            SELECT name, lat, long, size, boat_launch, cost

            FROM lake_inventory

            WHERE locale = @region AND area >= @size

            ORDER BY name

        OPEN @lake_list_cursor

        END

END

DECLARE @my_lakes_cursor CURSOR

DECLARE @my_region char(30)

SET @my_region = 'Northern Ontario'

EXECUTE lake_list @my_region, 500, @my_lakes_cursor OUTPUT

IF Cursor_Status('variable', '@my_lakes_cursor') <= 0

    BEGIN

    /* Some code to tell the user that there is no list of

    lakes for him/her */

    END

ELSE

    BEGIN

        FETCH @my_lakes_cursor INTO -- Destination here

        -- Continue with other code here.

END

See Also
Data Types Cursor Functions


DATABASEPROPERTY

Returns the named database property value for the given database and property name.

Syntax

DATABASEPROPERTY(database, property)

Arguments
database
Is an expression containing the name of the database for which to return the named property information. database is nvarchar(128).
property
Is an expression containing the name of the database property to return. property is varchar(128), and can be one of these values.

Value Description Value returned
IsAnsiNullDefault Database follows SQL-92 rules for allowing null values. 1 = True
0 = False
NULL = Invalid input
IsAnsiNullsEnabled All comparisons to a null evaluate to unknown. 1 = True
0 = False
NULL = Invalid input
IsAnsiWarningsEnabled Error or warning messages are issued when standard error conditions occur. 1 = True
0 = False
NULL = Invalid input
IsAutoClose Database shuts down cleanly and frees resources after the last user exits. 1 = True
0 = False
NULL = Invalid input
IsAutoShrink Database files are candidates for automatic periodic shrinking. 1 = True
0 = False
NULL = Invalid input
IsAutoUpdateStatistics Auto update statistics database option is enabled. 1 = True
0 = False
NULL = Invalid input
IsBulkCopy Database allows nonlogged operations. 1 = True
0 = False
NULL = Invalid input
IsCloseCursorsOnCommitEnabled Cursors that are open when a transaction is committed are closed. 1 = True
0 = False
NULL = Invalid input
IsDboOnly Database is in DBO-only access mode. 1 = True
0 = False
NULL = Invalid input
IsDetached Database was detached by a detach operation. 1 = True
0 = False
NULL = Invalid input
IsEmergencyMode Emergency mode is enabled to allow suspect database to be usable. 1 = True
0 = False
NULL = Invalid input
IsFulltextEnabled Database is full-text enabled. 1 = True
0 = False
NULL = Invalid input
IsInLoad Database is going through the loading process. 1 = True
0 = False
NULL = Invalid input
IsInRecovery Database is recovering. 1 = True
0 = False
NULL = Invalid input
IsInStandBy Database is online as read-only, with restore log allowed. 1 = True
0 = False
NULL = Invalid input
IsLocalCursorsDefault Cursor declarations default to LOCAL. 1 = True
0 = False
NULL = Invalid input
IsNotRecovered Database failed to recover. 1 = True
0 = False
NULL = Invalid input
IsNullConcat Null concatenation operand yields NULL. 1 = True
0 = False
NULL = Invalid input
IsOffline Database is offline. 1 = True
0 = False
NULL = Invalid input
IsQuotedIdentifiersEnabled Double quotation marks can be used on identifiers. 1 = True
0 = False
NULL = Invalid input
IsReadOnly Database is in a read-only access mode. 1 = True
0 = False
NULL = Invalid input
IsRecursiveTriggersEnabled Recursive firing of triggers is enabled. 1 = True
0 = False
NULL = Invalid input
IsShutDown Database encountered a problem at startup. 1 = True
0 = False
NULL = Invalid input
IsSingleUser Database is in single-user access mode. 1 = True
0 = False
NULL = Invalid input
IsSuspect Database is suspect. 1 = True
0 = False
NULL = Invalid input
IsTruncLog Database truncates its log on checkpoints. 1 = True
0 = False
NULL = Invalid input
Version Version number of the specified database if the database is open. Version number = Database is open
NULL = Database is closed.

Return Types

integer

Examples

This example returns the setting for the IsTruncLog property for the master database.

USE master

SELECT DATABASEPROPERTY('master', 'IsTruncLog')

Here is the result:

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

1

See Also
Control-of-Flow Language | sp_dboption
DELETE | UPDATE
INSERT | WHERE
SELECT | Metadata Functions


Data Types

In Microsoft® SQL Server™, each column, local variable, expression, and parameter has a data type. The set of system-supplied data types is shown below. User-defined data types, which are aliases for system-supplied data types, can also be defined. For more information about user-defined data types, see sp_addtype.

Integers
bit
Integer data with either a 1 or 0 value.
int
Integer (whole number) data from -2^31 (-2,147,483,648) through 2^31 - 1 (2,147,483,647).
smallint
Integer data from 2^15 (-32,768) through 2^15 - 1 (32,767).
tinyint
Integer data from 0 through 255.
decimal and numeric
decimal
Fixed precision and scale numeric data from -10^38 -1 through 10^38 -1.
numeric
A synonym for decimal.
money and smallmoney
money
Monetary data values from -2^63 (-922,337,203,685,477.5808) through 2^63 - 1 (+922,337,203,685,477.5807), with accuracy to a ten-thousandth of a monetary unit.
smallmoney
Monetary data values from -214,748.3648 through +214,748.3647, with accuracy to a ten-thousandth of a monetary unit.
Approximate Numerics
float
Floating precision number data from -1.79E + 308 through 1.79E + 308.
real
Floating precision number data from -3.40E + 38 through 3.40E + 38.
datetime and smalldatetime
datetime
Date and time data from January 1, 1753, to December 31, 9999, with an accuracy of three-hundredths of a second, or 3.33 milliseconds.
smalldatetime
Date and time data from January 1, 1900, through June 6, 2079, with an accuracy of one minute.
Numerics
cursor
A reference to a cursor.
timestamp
A database-wide unique number.
uniqueidentifier
A globally unique identifier (GUID).
Character Strings
char
Fixed-length non-Unicode character data with a maximum length of 8,000 characters.
varchar
Variable-length non-Unicode data with a maximum of 8,000 characters.
text
Variable-length non-Unicode data with a maximum length of 2^31 - 1 (2,147,483,647) characters.
Unicode Character Strings
nchar
Fixed-length Unicode data with a maximum length of 4,000 characters.
nvarchar
Variable-length Unicode data with a maximum length of 4,000 characters. sysname is a system-supplied user-defined data type that is a synonym for nvarchar(128) and is used to reference database object names.
ntext
Variable-length Unicode data with a maximum length of 2^30 - 1 (1,073,741,823) characters.
Binary Strings
binary
Fixed-length binary data with a maximum length of 8,000 bytes.
varbinary
Variable-length binary data with a maximum length of 8,000 bytes.
image
Variable-length binary data with a maximum length of 2^31 - 1 (2,147,483,647) bytes.
Synonyms

Data type synonyms are included for SQL-92 compatibility.

Synonym | Mapped to system data type
binary varying | varbinary
char varying | varchar
character | char
character | char(1)
character(n) | char(n)
character varying(n) | varchar(n)
dec | decimal
double precision | float
float[(n)] for n = 1-7 | real
float[(n)] for n = 8-15 | float
integer | int
national character(n) | nchar(n)
national char(n) | nchar(n)
national character varying(n) | nvarchar(n)
national char varying(n) | nvarchar(n)
national text | ntext
numeric | decimal

See Also
CREATE PROCEDURE | sp_bindefault
CREATE TABLE | sp_droptype
DECLARE @local_variable | sp_bindrule
EXECUTE | sp_help
Expressions | sp_rename
Functions | sp_unbindefault
LIKE | sp_unbindrule
SET |


Data Type Precedence

When two expressions of different data types are combined by an operator, the data type precedence rules specify which data type is converted to the other. The data type with the lower precedence is converted to the data type with the higher precedence. If the conversion is not a supported implicit conversion, an error is returned. When both operand expressions have the same data type, the result of the operation has that data type.

This is the precedence order for the Microsoft® SQL Server™ data types:

  • datetime (highest)
  • smalldatetime
  • float
  • real
  • decimal
  • money
  • smallmoney
  • int
  • smallint
  • tinyint
  • bit
  • ntext
  • text
  • image
  • timestamp
  • nvarchar
  • nchar
  • varchar
  • char
  • varbinary
  • binary
  • uniqueidentifier (lowest)
Data Type Precedence and Comparison Operators

These data type precedence rules are modified by the comparison operators. Comparison operators always return a Boolean data type. When a comparison operator is applied to expressions of two different data types, one of the expressions must be converted to the data type of the other before the comparison can be made. The data type precedence rules control this internal conversion, with the following exceptions:

  • If one of the expressions is an aggregate function that is not in a subquery, and the other expression is not an aggregate, then the data type of the aggregate function is used regardless of the precedence rules.
  • If one of the expressions is a column, and the other is not a column or aggregate function, the data type of the column is used regardless of the precedence rules.


Precision, Scale, and Length

Precision is the number of digits in a number. Scale is the number of digits to the right of the decimal point in a number. For example, the number 123.45 has a precision of 5 and a scale of 2.

Length for a numeric data type is the number of bytes used to store the number. Length for a character string or Unicode data type is the number of characters. The length for binary, varbinary, and image data types is the number of bytes. For example, an int data type can hold 10 digits, is stored in 4 bytes, and does not accept decimal points. The int data type has a precision of 10, a length of 4, and a scale of 0.

When two char, varchar, binary, or varbinary expressions are concatenated, the length of the resulting expression is the sum of the lengths of the two source expressions or 8,000 characters, whichever is less.

When two nchar or nvarchar expressions are concatenated, the length of the resulting expression is the sum of the lengths of the two source expressions or 4,000 characters, whichever is less.

The precision and scale of the numeric data types besides decimal are fixed. If an arithmetic operator has two expressions of the same type, then the result has the same data type with the precision and scale defined for that type. If an operator has two expressions with different numeric data types, then the rules of data type precedence define the data type of the result. The result has the precision and scale defined for its data type.

This table defines how the precision and scale of the result are calculated when the result of an operation is of type decimal. The result is decimal when:

  • Both expressions are decimal.
  • One expression is decimal and the other is a data type with a lower precedence than decimal.

The operand expressions are denoted as expression e1, with precision p1 and scale s1, and expression e2, with precision p2 and scale s2. The precision and scale for any expression that is not decimal is the precision and scale defined for the data type of the expression.

Operation | Result precision | Result scale *
e1 + e2 | max(s1, s2) + max(p1-s1, p2-s2) + 1 | max(s1, s2)
e1 - e2 | max(s1, s2) + max(p1-s1, p2-s2) | max(s1, s2)
e1 * e2 | p1 + p2 + 1 | s1 + s2
e1 / e2 | p1 + s1 + s2 + max(6, s1 + p2 + 1) | max(6, s1 + p2 + 1)
* The result precision and scale have an absolute maximum of 38. When a result precision is greater than 38, the corresponding scale is reduced to prevent the integral part of a result from being truncated.


DATALENGTH

Returns the number of bytes used to represent any expression.

Syntax

DATALENGTH(expression)

Arguments
expression
Is an expression of any type.
Return Types

int

Remarks

DATALENGTH is especially useful with varchar, varbinary, text, image, nvarchar, and ntext data types because these data types can store variable-length data.

The DATALENGTH of NULL is NULL.

Note Compatibility levels can affect return values. For more information about compatibility levels, see sp_dbcmptlevel.

Examples

This example finds the length of the pub_name column in the publishers table.

USE pubs

GO

SELECT length = DATALENGTH(pub_name), pub_name

FROM publishers

ORDER BY pub_name

GO

Here is the result set:

length      pub_name

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

20          Algodata Infosystems

16          Binnet & Hardley

21          Five Lakes Publishing

5           GGG&G

18          Lucerne Publishing

14          New Moon Books

17          Ramona Publishers

14          Scootney Books

(8 row(s) affected)

See Also
CAST and CONVERT | System Functions
Data Types |


DATEADD

Returns a new datetime value based on adding an interval to the specified date.

Syntax

DATEADD(datepart, number, date)

Arguments
datepart
Is the parameter that specifies on which part of the date to return a new value. The table lists the dateparts and abbreviations recognized by Microsoft® SQL Server™.

Datepart | Abbreviations
year | yy, yyyy
quarter | qq, q
month | mm, m
dayofyear | dy, y
day | dd, d
week | wk, ww
hour | hh
minute | mi, n
second | ss, s
millisecond | ms

number
Is the value used to increment datepart.
date
Is an expression that returns a datetime or smalldatetime value, or a character string in a date format. For information about specifying dates, see datetime and smalldatetime.

If the year is given with two digits, values less than 50 are interpreted as the next century (20xx) and values greater than or equal to 50 are interpreted as this century (19xx). Therefore, 25 is 2025 and 50 is 1950.

Return Types

Returns datetime, but smalldatetime if the date argument is smalldatetime.

Examples

This example prints a listing of a time frame for titles in the pubs database. This time frame represents the existing publication date plus 21 days.

USE pubs

GO

SELECT DATEADD(day, 21, pubdate) AS timeframe

FROM titles

GO

Here is the result set:

timeframe

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

Jul 3 1991 12:00AM

Jun 30 1991 12:00AM

Jul 21 1991 12:00AM

Jul 13 1991 12:00AM

Jun 30 1991 12:00AM

Jul 9 1991 12:00AM

Mar 14 1997  5:09PM

Jul 21 1991 12:00AM

Jul 3 1994 12:00AM

Mar 14 1997  5:09PM

Nov 11 1991 12:00AM

Jul 6 1991 12:00AM

Oct 26 1991 12:00AM

Jul 3 1991 12:00AM

Jul 3 1991 12:00AM

Nov 11 1991 12:00AM

Jul 3 1991 12:00AM

Jul 3 1991 12:00AM

(18 row(s) affected)

See Also
CAST and CONVERT | Date and Time Functions
Data Types |


DATEDIFF

Returns the number of date and time boundaries crossed between two specified dates.

Syntax

DATEDIFF(datepart, startdate, enddate)

Arguments
datepart
Is the parameter that specifies on which part of the date to calculate the difference. The table lists dateparts and abbreviations recognized by Microsoft® SQL Server™.

Datepart | Abbreviations
year | yy, yyyy
quarter | qq, q
month | mm, m
dayofyear | dy, y
day | dd, d
week | wk, ww
hour | hh
minute | mi, n
second | ss, s
millisecond | ms

startdate
Is the beginning date for the calculation. startdate is an expression that returns a datetime or smalldatetime value, or a character string in a date format.

Because smalldatetime is accurate only to the minute, when a smalldatetime value is used, seconds and milliseconds are always 0.

If the year is given with two digits, values less than 50 are interpreted as the next century (20xx) and values greater than or equal to 50 are interpreted as this century (19xx). Therefore, 25 is 2025 and 50 is 1950.

For information about specifying dates, see datetime and smalldatetime.

enddate
Is the ending date for the calculation. enddate is an expression that returns a datetime or smalldatetime value, or a character string in a date format.
Return Types

integer

Remarks

startdate is subtracted from enddate. If startdate is later than enddate, a negative value is returned.

DATEDIFF produces an error if the result is out of range for integer values. For milliseconds, the maximum number that can be represented is 24 days, 20 hours, 31 minutes and 23.647 seconds. For seconds, the maximum number that can be represented is approximately 68 years.

The method of counting crossed boundaries such as minutes, seconds, and milliseconds makes the result given by DATEDIFF consistent across all data types. The result is a signed integer value equal to the number of datepart boundaries crossed between the first and second date. For example, the number of weeks between Sunday, January 4 and Sunday, January 11, is 1.

Examples

This example determines the difference in days between the current date and the publication date for titles in the pubs database.

USE pubs

GO

SELECT DATEDIFF(day, pubdate, getdate()) AS no_of_days

FROM titles

GO

See Also
CAST and CONVERT | Date and Time Functions
Data Types |


DATENAME

Returns a character string representing the specified datepart of the specified date.

Syntax

DATENAME(datepart, date)

Arguments
datepart
Is the parameter that specifies the part of the date to return. The table lists dateparts and abbreviations recognized by Microsoft® SQL Server™.

Datepart | Abbreviations
year | yy, yyyy
quarter | qq, q
month | mm, m
dayofyear | dy, y
day | dd, d
week | wk, ww
weekday | dw
hour | hh
minute | mi, n
second | ss, s
millisecond | ms

The weekday (dw) datepart returns the day of the week (Sunday, Monday, and so on).

Is an expression that returns a datetime or smalldatetime value, or a character string in a date format. Use the datetime data type for dates after January 1, 1753. Store as character data for earlier dates. When entering datetime values, always enclose them in quotation marks. Because smalldatetime is accurate only to the minute, when a smalldatetime value is used, seconds and milliseconds are always 0. For information about specifying dates, see datetime and smalldatetime.

If the year is given with two digits, values less than 50 are interpreted as the next century (20xx) and values greater than 50 are interpreted as this century (19xx). Therefore, 25 is 2025 and 50 is 1950.

Return Types

nvarchar

Remarks

SQL Server automatically converts between character and datetime values as necessary, for example, when you compare a character value with a datetime value.

Examples

This example extracts the month name from the date returned by GETDATE.

SELECT DATENAME(month, getdate()) AS 'Month Name'

Here is the result set:

Month Name
------------------------------
February

See Also
CAST and CONVERT | Date and Time Functions
Data Types |


DATEPART

Returns an integer representing the specified datepart of the specified date.

Syntax

DATEPART(datepart, date)

Arguments
datepart
Is the parameter that specifies the part of the date to return. The table lists dateparts and abbreviations recognized by Microsoft® SQL Server™.

Datepart | Abbreviations
year | yy, yyyy
quarter | qq, q
month | mm, m
dayofyear | dy, y
day | dd, d
week | wk, ww
weekday | dw
hour | hh
minute | mi, n
second | ss, s
millisecond | ms

The week (wk, ww) datepart reflects changes made to SET DATEFIRST. January 1 of any year defines the starting number for the week datepart, for example: DATEPART(wk, ‘Jan 1, xxxx’) = 1, where xxxx is any year.

The weekday (dw) datepart returns a number that corresponds to the day of the week, for example: Sunday = 1, Saturday = 7. The number produced by the weekday datepart depends on the value set by SET DATEFIRST, which sets the first day of the week.

date
Is an expression that returns a datetime or smalldatetime value, or a character string in a date format. Use the datetime data type only for dates after January 1, 1753. Store dates as character data for earlier dates. When entering datetime values, always enclose them in quotation marks. Because smalldatetime is accurate only to the minute, when a smalldatetime value is used, seconds and milliseconds are always 0.

If the year is given with two digits, values less than 50 are interpreted as the next century (20xx) and values greater than 50 are interpreted as this century (19xx). Therefore, 25 is 2025 and 50 is 1950.

For information about specifying dates, see datetime and smalldatetime.

Return Types

int

Remarks

The DAY, MONTH, and YEAR functions are synonyms for DATEPART(dd, date), DATEPART(mm, date), and DATEPART(yy, date), respectively.

Examples

The GETDATE function returns the current date; however, the complete date is not always the information needed for comparison (often only a portion of the date is compared). This example shows the output of GETDATE as well as DATEPART.

SELECT GETDATE() AS 'Current Date'

GO

Here is the result set:

Current Date
---------------------------
Feb 18 1998 11:46PM

SELECT DATEPART(month, GETDATE()) AS 'Month Number'

GO

Here is the result set:

Month Number
------------
2

This example assumes the date May 29.

SELECT DATEPART(month, GETDATE())

GO

Here is the result set:

-----------

5

(1 row(s) affected)

In this example, the date is specified as a number. Notice that SQL Server interprets 0 as January 1, 1900.

SELECT DATEPART(m, 0), DATEPART(d, 0), DATEPART(yy, 0)

Here is the result set:

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

1     1      1900

See Also
CAST and CONVERT | Date and Time Functions
Data Types |


datetime and smalldatetime

Date and time data types for representing date and time of day.

datetime
Date and time data from January 1, 1753, to December 31, 9999, to an accuracy of one three-hundredth second, or 3.33 milliseconds. Values are rounded to increments of .000, .003, or .007 milliseconds, as shown in the table.

Example | Rounded example
01/01/98 23:59:59.999 | 1998-01-02 12:00:00.000
01/01/98 23:59:59.995,
01/01/98 23:59:59.996,
01/01/98 23:59:59.997, or
01/01/98 23:59:59.998 		1998-01-01 23:59:59.997
01/01/98 23:59:59.992,
01/01/98 23:59:59.993,
01/01/98 23:59:59.994 		1998-01-01 23:59:59.993
01/01/98 23:59:59.990 or
01/01/98 23:59:59.991 		1998-01-01 23:59:59.990

SQL Server rejects all values it cannot recognize as dates between 1753 and 9999.

smalldatetime
Date and time data from January 1, 1900, through June 6, 2079, with accuracy to the minute.
Remarks

Values with the datetime data type are stored internally by Microsoft® SQL Server™ as two 4-byte integers. The first 4 bytes store the number of days before or after the base date, January 1, 1900. The base date is the system’s reference date. Values for datetime earlier than January 1, 1753, are not permitted. The other 4 bytes store the time of day represented as the number of milliseconds after midnight.

The smalldatetime data type stores dates and times of day with less precision than datetime. SQL Server stores smalldatetime values as two 2-byte integers. The first 2 bytes store the number of days after January 1, 1900. The other 2 bytes store the number of minutes since midnight. Dates range from January 1, 1900, through June 6, 2079, with accuracy to the minute.

See Also
ALTER TABLE | DELETE
CAST and CONVERT | INSERT
CREATE TABLE | SET @local_variable
Data Types | UPDATE
DECLARE @local_variable |


DAY

Returns an integer representing the day datepart of the specified date.

Syntax

DAY(date)

Arguments
date
Is an expression of type datetime or smalldatetime.
Return Type

int

Remarks

This function is equivalent to DATEPART(dd, date).

Examples

This example returns the number of the day from the date 03/12/1998.

SELECT DAY('03/12/1998') AS 'Day Number'

GO

Here is the result set:

Day Number
------------
12

In this example, the date is specified as a number. Notice that Microsoft® SQL Server™ interprets 0 as January 1, 1900.

SELECT MONTH(0), DAY(0), YEAR(0)

Here is the result set.

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

1     1      1900

See Also
datetime and smalldatetime | Date and Time Functions
Expressions |


DB_ID

Returns the database identification number.

Syntax

DB_ID(['database_name'])

Arguments
'database_name'
Is the database name used to return the corresponding database identification number. database_name is nvarchar. If database_name is omitted, the ID of the current database is returned.
Return Types

smallint

Examples

This example examines each database in sysdatabases using the database name to determine the database identification number.

USE master

SELECT name, DB_ID(name) AS DB_ID

FROM sysdatabases

ORDER BY dbid

Here is the result set:

name                           DB_ID

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

master                         1

tempdb                         2

model                          3

msdb                           4

pubs                           5

(5 row(s) affected)

See Also

Metadata Functions


DB_NAME

Returns the database name.

Syntax

DB_NAME(database_id)

Arguments
database_id
Is the ID of the database to be returned. database_id is smallint, with no default. If no ID is specified, the name of the current database is returned.
Return Types

nvarchar(128)

Examples

This example examines each database in sysdatabases using the database identification number to determine the database name.

USE master

SELECT dbid, DB_NAME(dbid) AS DB_NAME

FROM sysdatabases

ORDER BY dbid

GO

Here is the result set:

dbid   DB_NAME

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

1      master

2      tempdb

3      model

4      msdb

5      pubs

(5 row(s) affected)

See Also

Metadata Functions


DBCC

The Transact-SQL programming language provides DBCC statements that act as the “database consistency checker” for Microsoft® SQL Server™. These statements check the physical and logical consistency of a database. Many DBCC statements can fix detected problems.

These database consistency checking statements are grouped into these categories.

Statement category | Perform
Maintenance statements | Maintenance tasks on a database, index, or filegroup.
Miscellaneous statements | Miscellaneous tasks such as enabling row-level locking or removing a dynamic-link library (DLL) from memory.
Status statements | Status checks.
Validation statements | Validation operations on a database, table, index, catalog, filegroup, system tables, or allocation of database pages.

SQL Server’s DBCC statements take input parameters and return values. All DBCC statement parameters can accept both Unicode and DBCS literals.

Maintenance Statements
DBCC DBREPAIR | DBCC SHRINKFILE
DBCC DBREINDEX | DBCC UPDATEUSAGE
DBCC SHRINKDATABASE |

Miscellaneous Statements
DBCC dllname (FREE) | DBCC TRACEOFF
DBCC HELP | DBCC TRACEON
DBCC PINTABLE | DBCC UNPINTABLE
DBCC ROWLOCK |

Status Statements
DBCC INPUTBUFFER | DBCC SHOW_STATISTICS
DBCC OPENTRAN | DBCC SQLPERF
DBCC OUTPUTBUFFER | DBCC TRACESTATUS
DBCC PROCCACHE | DBCC USEROPTIONS
DBCC SHOWCONTIG |

Validation Statements
DBCC CHECKALLOC | DBCC CHECKTABLE
DBCC CHECKCATALOG | DBCC NEWALLOC
DBCC CHECKDB | DBCC TEXTALL
DBCC CHECKFILEGROUP | DBCC TEXTALLOC
DBCC CHECKIDENT |


DBCC CHECKALLOC

Checks the allocation and use of all pages in the specified database.

Syntax

DBCC CHECKALLOC
( 'database_name'
[, NOINDEX
|
{ REPAIR_ALLOW_DATA_LOSS
| REPAIR_FAST
| REPAIR_REBUILD
}]
) [WITH {ALL_ERRORMSGS | NO_INFOMSGS}]

Arguments
'database_name'
Is the database for which to check allocation and page usage. If not specified, the default is the current database. Database names must conform to the rules for identifiers.
NOINDEX
Specifies that nonclustered indexes for nonsystem tables should not be checked.

Note NOINDEX is maintained for backward compatibility only. All indexes are checked when executing DBCC CHECKALLOC.

REPAIR_ALLOW_DATA_LOSS | REPAIR_FAST | REPAIR_REBUILD
Specifies that DBCC CHECKALLOC repair the found errors. The given database_name must be in single-user mode to use one of these repair options and can be one of the following.

Value | Description
REPAIR_ALLOW_DATA_LOSS | Performs all repairs done by REPAIR_REBUILD and includes allocation and deallocation of rows and pages for correcting allocation errors, structural row or page errors, and deletion of corrupted text objects. These repairs can result in some data loss. The repair can be done under a user transaction to allow the user to rollback the changes made. If repairs are rolled back, the database will still contain errors and should be restored from a backup. If a repair for an error has been skipped due to the provided repair level, any repairs that depend on the repair are also skipped. After repairs are completed, back up the database.
REPAIR_FAST | Performs minor, nontime-consuming repair actions such as repairing extra keys in nonclustered indexes. These repairs can be done quickly and without risk of data loss.
REPAIR_REBUILD | Performs all repairs done by REPAIR_FAST and includes time-consuming repairs such as rebuilding indexes. These repairs can be done without risk of data loss.

WITH
Specifies an option for the number of error messages to be returned. If neither ALL_ERRORMSGS nor NO_INFOMSGS is specified, Microsoft® SQL Server™ returns all error messages.
ALL_ERRORMSGS
Displays all error messages. If not specified, SQL Server displays a maximum of 200 error messages per object.
NO_INFOMSGS
Suppresses all informational messages and the report of space used.
Remarks

It is not necessary to execute DBCC CHECKALLOC if DBCC CHECKDB has already been executed. DBCC CHECKDB is a superset of DBCC CHECKALLOC and includes allocation checks in addition to checks of index structure and data integrity.

DBCC CHECKDB is the safest repair statement because it catches and repairs the widest possible range of errors. If only allocation errors are reported for a database, execute DBCC CHECKALLOC with a repair option to correct them. However, to ensure that all errors (including allocation errors) are repaired properly, execute DBCC CHECKDB with a repair option. DBCC CHECKALLOC messages are sorted by object ID, except for those messages generated from tempdb. DBCC CHECKALLOC validates the allocation of all data pages in the database while DBCC CHECKDB validates the page information used in the storage of data in addition to validating the allocation information.

DBCC CHECKALLOC acquires a schema lock to prevent schema modifications while the DBCC CHECKALLOC is in progress. DBCC CHECKALLOC may report errors for tempdb work tables that are created or dropped for user queries while the DBCC CHECKALLOC is running; these can be ignored.

Result Sets

Whether or not any options (except WITH NO_INFOMSGS) are specified, DBCC CHECKALLOC returns this result set (values may vary):

DBCC results for 'master'.

***************************************************************

Table sysobjects                Object ID 1.

Index ID 1         FirstIAM (1:4)   Root (1:6)    Dpages 13     Sort 0.

    Data level 1. 15 data pages in 1 extents.

Index ID 2         FirstIAM (1:841)   Root (1:856)    Dpages 8     Sort 0.

    Index ID 2. 10 index pages in 2 extents.

Index ID 3         FirstIAM (1:844)   Root (1:846)    Dpages 3     Sort 0.

    Index ID 3. 5 index pages in 0 extents.

Total number of extents is 3.

***************************************************************

Table sysindexes                Object ID 2.

Index ID 1         FirstIAM (1:25)   Root (1:26)    Dpages 3     Sort 0.

    Data level 1. 5 data pages in 0 extents.

Index ID 255         FirstIAM (1:35)   Root (1:16)    Dpages 0     Sort 0.

    Index ID 255. 5 index pages in 1 extents.

Total number of extents is 1.

***************************************************************

Table syscolumns                Object ID 3.

Index ID 1         FirstIAM (1:30)   Root (1:31)    Dpages 41     Sort 0.

    Data level 1. 43 data pages in 5 extents.

Index ID 2         FirstIAM (1:847)   Root (1:888)    Dpages 17     Sort 0.

    Index ID 2. 19 index pages in 3 extents.

Total number of extents is 8.

***************************************************************

Table systypes                Object ID 4.

Index ID 1         FirstIAM (1:913)   Root (1:914)    Dpages 1     Sort 0.

    Data level 1. 3 data pages in 0 extents.

Index ID 2         FirstIAM (1:916)   Root (1:915)    Dpages 1     Sort 0.

    Index ID 2. 2 index pages in 0 extents.

Total number of extents is 0.

***************************************************************

Table syscomments                Object ID 6.

Index ID 1         FirstIAM (1:272)   Root (1:273)    Dpages 390     Sort 0.

    Data level 1. 394 data pages in 50 extents.

Total number of extents is 50.

***************************************************************

Table sysfiles1                Object ID 8.

Index ID 0         FirstIAM (1:7)   Root (1:32)    Dpages 2     Sort 0.

    Data level 1. 2 data pages in 0 extents.

Total number of extents is 0.

***************************************************************

Table syspermissions                Object ID 9.

Index ID 1         FirstIAM (1:275)   Root (1:276)    Dpages 2     Sort 0.

    Data level 1. 4 data pages in 0 extents.

Total number of extents is 0.

***************************************************************

Table sysusers                Object ID 10.

Index ID 1         FirstIAM (1:278)   Root (1:279)    Dpages 1     Sort 0.

    Data level 1. 3 data pages in 0 extents.

Index ID 2         FirstIAM (1:918)   Root (1:917)    Dpages 1     Sort 0.

    Index ID 2. 2 index pages in 0 extents.

Index ID 3         FirstIAM (1:281)   Root (1:280)    Dpages 1     Sort 0.

    Index ID 3. 2 index pages in 0 extents.

Total number of extents is 0.

***************************************************************

Table sysdepends                Object ID 12.

Index ID 1         FirstIAM (1:286)   Root (1:287)    Dpages 16     Sort 0.

    Data level 1. 18 data pages in 2 extents.

Total number of extents is 2.

***************************************************************

Table sysreferences                Object ID 14.

Index ID 1         FirstIAM (1:289)   Root (1:290)    Dpages 1     Sort 0.

    Data level 1. 3 data pages in 0 extents.

Index ID 2         FirstIAM (1:284)   Root (1:283)    Dpages 1     Sort 0.

    Index ID 2. 2 index pages in 0 extents.

Index ID 3         FirstIAM (1:292)   Root (1:291)    Dpages 1     Sort 0.

    Index ID 3. 2 index pages in 0 extents.

Total number of extents is 0.

***************************************************************

Table sysfulltextcatalogs                Object ID 19.

Index ID 1         FirstIAM (1:296)   Root (1:297)    Dpages 1     Sort 0.

    Data level 1. 3 data pages in 0 extents.

Index ID 2         FirstIAM (1:920)   Root (1:919)    Dpages 1     Sort 0.

    Index ID 2. 2 index pages in 0 extents.

Total number of extents is 0.

***************************************************************

Table sysdatabases                Object ID 30.

Index ID 1         FirstIAM (1:605)   Root (1:606)    Dpages 1     Sort 0.

    Data level 1. 3 data pages in 0 extents.

Index ID 2         FirstIAM (1:840)   Root (1:607)    Dpages 1     Sort 0.

    Index ID 2. 2 index pages in 0 extents.

Total number of extents is 0.

***************************************************************

Table sysxlogins                Object ID 33.

Index ID 1         FirstIAM (1:922)   Root (1:923)    Dpages 1     Sort 0.

    Data level 1. 3 data pages in 0 extents.

Index ID 2         FirstIAM (1:925)   Root (1:924)    Dpages 1     Sort 0.

    Index ID 2. 2 index pages in 0 extents.

Total number of extents is 0.

***************************************************************

Table sysdevices                Object ID 35.

Index ID 1         FirstIAM (1:927)   Root (1:928)    Dpages 1     Sort 0.

    Data level 1. 3 data pages in 0 extents.

Total number of extents is 0.

***************************************************************

Table sysmessages                Object ID 36.

Index ID 1         FirstIAM (1:309)   Root (1:310)    Dpages 109     Sort 0.

    Data level 1. 111 data pages in 13 extents.

Total number of extents is 13.

***************************************************************

Table sysconfigures                Object ID 37.

Index ID 1         FirstIAM (1:312)   Root (1:313)    Dpages 1     Sort 0.

    Data level 1. 3 data pages in 0 extents.

Total number of extents is 0.

***************************************************************

Table sysservers                Object ID 40.

Index ID 1         FirstIAM (1:315)   Root (1:316)    Dpages 1     Sort 0.

    Data level 1. 3 data pages in 0 extents.

Index ID 2         FirstIAM (1:930)   Root (1:929)    Dpages 1     Sort 0.

    Index ID 2. 2 index pages in 0 extents.

Total number of extents is 0.

***************************************************************

Table syslanguages                Object ID 44.

Index ID 1         FirstIAM (1:320)   Root (1:321)    Dpages 2     Sort 0.

    Data level 1. 4 data pages in 0 extents.

Index ID 2         FirstIAM (1:932)   Root (1:931)    Dpages 1     Sort 0.

    Index ID 2. 2 index pages in 0 extents.

Index ID 3         FirstIAM (1:934)   Root (1:933)    Dpages 1     Sort 0.

    Index ID 3. 2 index pages in 0 extents.

Total number of extents is 0.

***************************************************************

Table syscharsets                Object ID 45.

Index ID 1         FirstIAM (1:328)   Root (1:329)    Dpages 30     Sort 0.

    Data level 1. 32 data pages in 3 extents.

Index ID 2         FirstIAM (1:936)   Root (1:935)    Dpages 1     Sort 0.

    Index ID 2. 2 index pages in 0 extents.

Total number of extents is 3.

***************************************************************

Table sysaltfiles                Object ID 94.

Index ID 1         FirstIAM (1:13)   Root (1:14)    Dpages 1     Sort 0.

    Data level 1. 3 data pages in 0 extents.

Total number of extents is 0.

***************************************************************

Table sysfilegroups                Object ID 96.

Index ID 1         FirstIAM (1:267)   Root (1:268)    Dpages 1     Sort 0.

    Data level 1. 3 data pages in 0 extents.

Index ID 2         FirstIAM (1:938)   Root (1:937)    Dpages 1     Sort 0.

    Index ID 2. 2 index pages in 0 extents.

Total number of extents is 0.

***************************************************************

Table sysallocations                Object ID 98.

Index ID 1         FirstIAM (1:33)   Root (1:34)    Dpages 1     Sort 0.

    Data level 1. 3 data pages in 0 extents.

Total number of extents is 0.

***************************************************************

Table spt_committab                Object ID 85575343.

Index ID 1         FirstIAM (1:359)   Root (1:360)    Dpages 1     Sort 0.

    Data level 1. 3 data pages in 0 extents.

Total number of extents is 0.

***************************************************************

Table spt_monitor                Object ID 101575400.

Index ID 0         FirstIAM (1:357)   Root (1:356)    Dpages 1     Sort 0.

    Data level 1. 2 data pages in 0 extents.

Total number of extents is 0.

***************************************************************

Table spt_values                Object ID 117575457.

Index ID 1         FirstIAM (1:939)   Root (1:952)    Dpages 5     Sort 0.

    Data level 1. 7 data pages in 2 extents.

Index ID 2         FirstIAM (1:941)   Root (1:943)    Dpages 4     Sort 0.

    Index ID 2. 6 index pages in 0 extents.

Total number of extents is 2.

***************************************************************

Table spt_fallback_db                Object ID 149575571.

Index ID 0         FirstIAM (1:368)   Root (1:367)    Dpages 1     Sort 0.

    Data level 1. 2 data pages in 0 extents.

Total number of extents is 0.

***************************************************************

Table spt_fallback_dev                Object ID 165575628.

Index ID 0         FirstIAM (1:370)   Root (1:369)    Dpages 1     Sort 0.

    Data level 1. 2 data pages in 0 extents.

Total number of extents is 0.

***************************************************************

Table spt_fallback_usg                Object ID 181575685.

Index ID 0         FirstIAM (1:372)   Root (1:371)    Dpages 1     Sort 0.

    Data level 1. 2 data pages in 0 extents.

Total number of extents is 0.

***************************************************************

Table tbl1                Object ID 672721449.

Index ID 0         FirstIAM (1:27)   Root (1:11)    Dpages 1     Sort 0.

    Data level 1. 2 data pages in 0 extents.

Total number of extents is 0.

***************************************************************

Table FulltextTest                Object ID 912722304.

Index ID 1         FirstIAM (1:269)   Root (1:293)    Dpages 1     Sort 0.

    Data level 1. 3 data pages in 0 extents.

Total number of extents is 0.

***************************************************************

Table MSreplication_options                Object ID 1163151189.

Index ID 0         FirstIAM (1:461)   Root (1:460)    Dpages 1     Sort 0.

    Data level 1. 2 data pages in 0 extents.

Total number of extents is 0.

***************************************************************

Table spt_datatype_info_ext                Object ID 1410104064.

Index ID 1         FirstIAM (1:406)   Root (1:407)    Dpages 1     Sort 0.

    Data level 1. 3 data pages in 0 extents.

Total number of extents is 0.

***************************************************************

Table spt_datatype_info                Object ID 1426104121.

Index ID 1         FirstIAM (1:417)   Root (1:418)    Dpages 1     Sort 0.

    Data level 1. 3 data pages in 0 extents.

Total number of extents is 0.

***************************************************************

Table spt_server_info                Object ID 1442104178.

Index ID 1         FirstIAM (1:420)   Root (1:421)    Dpages 1     Sort 0.

    Data level 1. 3 data pages in 0 extents.

Total number of extents is 0.

***************************************************************

Table spt_provider_types                Object ID 2034106287.

Index ID 1         FirstIAM (1:456)   Root (1:457)    Dpages 1     Sort 0.

    Data level 1. 3 data pages in 0 extents.

Total number of extents is 0.

***************************************************************

Processed 53 entries in sysindexes for database ID 1.

Allocation page (1:2). Number of extents = 113, used pages = 778, referenced pages = 719.

           (1:2) (number of mixed extents = 31, mixed pages = 185).

    Object ID 1, Index ID 1, data extents 1, pages 15, mixed extent pages 9.

    Object ID 1, Index ID 2, index extents 2, pages 10, mixed extent pages 3.

    Object ID 1, Index ID 3, index extents 0, pages 5, mixed extent pages 5.

    Object ID 2, Index ID 1, data extents 0, pages 5, mixed extent pages 5.

    Object ID 2, Index ID 255, index extents 1, pages 5, mixed extent pages 4.

    Object ID 3, Index ID 1, data extents 5, pages 43, mixed extent pages 9.

    Object ID 3, Index ID 2, index extents 3, pages 19, mixed extent pages 3.

    Object ID 4, Index ID 1, data extents 0, pages 3, mixed extent pages 3.

    Object ID 4, Index ID 2, index extents 0, pages 2, mixed extent pages 2.

    Object ID 6, Index ID 1, data extents 50, pages 394, mixed extent pages 9.

    Object ID 8, Index ID 0, data extents 0, pages 2, mixed extent pages 2.

    Object ID 9, Index ID 1, data extents 0, pages 4, mixed extent pages 4.

    Object ID 10, Index ID 1, data extents 0, pages 3, mixed extent pages 3.

    Object ID 10, Index ID 2, index extents 0, pages 2, mixed extent pages 2.

    Object ID 10, Index ID 3, index extents 0, pages 2, mixed extent pages 2.

    Object ID 12, Index ID 1, data extents 2, pages 18, mixed extent pages 9.

    Object ID 14, Index ID 1, data extents 0, pages 3, mixed extent pages 3.

    Object ID 14, Index ID 2, index extents 0, pages 2, mixed extent pages 2.

    Object ID 14, Index ID 3, index extents 0, pages 2, mixed extent pages 2.

    Object ID 19, Index ID 1, data extents 0, pages 3, mixed extent pages 3.

    Object ID 19, Index ID 2, index extents 0, pages 2, mixed extent pages 2.

    Object ID 30, Index ID 1, data extents 0, pages 3, mixed extent pages 3.

    Object ID 30, Index ID 2, index extents 0, pages 2, mixed extent pages 2.

    Object ID 33, Index ID 1, data extents 0, pages 3, mixed extent pages 3.

    Object ID 33, Index ID 2, index extents 0, pages 2, mixed extent pages 2.

    Object ID 35, Index ID 1, data extents 0, pages 3, mixed extent pages 3.

    Object ID 36, Index ID 1, data extents 13, pages 111, mixed extent pages 9.

    Object ID 37, Index ID 1, data extents 0, pages 3, mixed extent pages 3.

    Object ID 40, Index ID 1, data extents 0, pages 3, mixed extent pages 3.

    Object ID 40, Index ID 2, index extents 0, pages 2, mixed extent pages 2.

    Object ID 44, Index ID 1, data extents 0, pages 4, mixed extent pages 4.

    Object ID 44, Index ID 2, index extents 0, pages 2, mixed extent pages 2.

    Object ID 44, Index ID 3, index extents 0, pages 2, mixed extent pages 2.

    Object ID 45, Index ID 1, data extents 3, pages 32, mixed extent pages 9.

    Object ID 45, Index ID 2, index extents 0, pages 2, mixed extent pages 2.

    Object ID 94, Index ID 1, data extents 0, pages 3, mixed extent pages 3.

    Object ID 96, Index ID 1, data extents 0, pages 3, mixed extent pages 3.

    Object ID 96, Index ID 2, index extents 0, pages 2, mixed extent pages 2.

    Object ID 98, Index ID 1, data extents 0, pages 3, mixed extent pages 3.

    Object ID 85575343, Index ID 1, data extents 0, pages 3, mixed extent pages 3.

    Object ID 101575400, Index ID 0, data extents 0, pages 2, mixed extent pages 2.

    Object ID 117575457, Index ID 1, data extents 2, pages 7, mixed extent pages 1.

    Object ID 117575457, Index ID 2, index extents 0, pages 6, mixed extent pages 6.

    Object ID 149575571, Index ID 0, data extents 0, pages 2, mixed extent pages 2.

    Object ID 165575628, Index ID 0, data extents 0, pages 2, mixed extent pages 2.

    Object ID 181575685, Index ID 0, data extents 0, pages 2, mixed extent pages 2.

    Object ID 672721449, Index ID 0, data extents 0, pages 2, mixed extent pages 2.

    Object ID 912722304, Index ID 1, data extents 0, pages 3, mixed extent pages 3.

    Object ID 1163151189, Index ID 0, data extents 0, pages 2, mixed extent pages 2.

    Object ID 1410104064, Index ID 1, data extents 0, pages 3, mixed extent pages 3.

    Object ID 1426104121, Index ID 1, data extents 0, pages 3, mixed extent pages 3.

    Object ID 1442104178, Index ID 1, data extents 0, pages 3, mixed extent pages 3.

    Object ID 2034106287, Index ID 1, data extents 0, pages 3, mixed extent pages 3.

Total number of extents = 113, used pages = 778, referenced pages = 719 in this database.

       (number of mixed extents = 31, mixed pages = 185) in this database.

CHECKALLOC found 0 allocation errors and 0 consistency errors in database 'master'.

DBCC execution completed. If DBCC printed error messages, contact your system administrator.

Permissions

DBCC CHECKALLOC permissions default to members of the sysadmin fixed server role or the db_owner fixed database role, and are not transferable.

Examples

This example executes DBCC CHECKALLOC for the current database and for the pubs database.

-- Check the current database.

DBCC CHECKALLOC

GO

-- Check the pubs database.

DBCC CHECKALLOC ('pubs')

GO

See Also
DBCC NEWALLOC | DBCC
sp_dboption |


DBCC CHECKCATALOG

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

Syntax

DBCC CHECKCATALOG
( 'database_name'
) [WITH NO_INFOMSGS]

Arguments
'database_name'
Is the database for which to check system table consistency. If not specified, the default is the current database. Database names must conform to the rules for identifiers.
WITH NO_INFOMSGS
Suppresses all informational messages and the report of space used when there are less than 200 error messages. If not specified, DBCC CHECKCATALOG displays all error messages. DBCC CHECKCATALOG messages are sorted by object ID, except for those messages generated from tempdb.
Remarks

DBCC CHECKCATALOG checks that every data type in syscolumns has a matching entry in systypes and that every table and view in sysobjects have at least one column in syscolumns.

Result Sets

If no database is specified, DBCC CHECKCATALOG returns this result set (message):

DBCC results for 'current database'.

DBCC execution completed. If DBCC printed error messages, contact your system administrator.

If Northwind is provided as a database name, DBCC CHECKCATALOG returns this result set (message):

DBCC results for 'Northwind'.

DBCC execution completed. If DBCC printed error messages, contact your system administrator.

Permissions

DBCC CHECKCATALOG permissions default to members of the sysadmin fixed server role or the db_owner fixed database role, and are not transferable.

Examples

This example checks the allocation and structural integrity of objects in both the current database and in the pubs database.

-- Check the current database.

DBCC CHECKCATALOG

GO

-- Check the pubs database.

DBCC CHECKCATALOG ('pubs')

GO

See Also
System Tables DBCC


DBCC CHECKDB

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

Syntax

DBCC CHECKDB
( 'database_name'
[, NOINDEX
| { REPAIR_ALLOW_DATA_LOSS
| REPAIR_FAST
| REPAIR_REBUILD
}]
) [WITH {ALL_ERRORMSGS | NO_INFOMSGS}]

Arguments
'database_name'
Is the database for which to check all object allocation and structural integrity. If not specified, the default is the current database. Database names must conform to the rules for identifiers.
NOINDEX
Specifies that nonclustered indexes for nonsystem tables should not be checked. The NOINDEX option decreases the overall execution time because it does not check nonclustered indexes for user-defined tables. NOINDEX has no effect on system tables, because DBCC CHECKDB always checks all system table indexes.
REPAIR_ALLOW_DATA_LOSS | REPAIR_FAST| REPAIR_REBUILD
Specifies that DBCC CHECKDB repair the found errors. The given database_name must be in single-user mode to use a repair option and can be one of the following.

Value | Description
REPAIR_ALLOW_DATA_LOSS | Performs all repairs done by REPAIR_REBUILD and includes allocation and deallocation of rows and pages for correcting allocation errors, structural row or page errors, and deletion of corrupted text objects. These repairs can result in some data loss. The repair may be done under a user transaction to allow the user to rollback the changes made. If repairs are rolled back, the database will still contain errors and should be restored from a backup. If a repair for an error has been skipped due to the provided repair level, any repairs that depend on the repair are also skipped. After repairs are completed, back up the database.
REPAIR_FAST | Performs minor, nontime-consuming repair actions such as repairing extra keys in nonclustered indexes. These repairs can be done quickly and without risk of data loss.
REPAIR_REBUILD | Performs all repairs done by REPAIR_FAST and includes time-consuming repairs such as rebuilding indexes. These repairs can be done without risk of data loss.

WITH
Specifies an option for the number of error messages to be returned. If neither ALL_ERRORMSGS nor NO_INFOMSGS is specified, Microsoft® SQL Server™ returns all error messages.
ALL_ERRORMSGS
Displays all error messages. If not specified, SQL Server displays a maximum of 200 error messages per table. Error messages are sorted by object ID, except for those messages generated from tempdb.
NO_INFOMSGS
Suppresses all informational messages and the report of space used.
Remarks

DBCC CHECKDB is the safest repair statement because it catches and repairs the widest possible errors. If only allocation errors are reported for a database, execute DBCC CHECKALLOC with a repair option to repair these errors. However, to ensure that all errors (including allocation errors) are properly repaired, execute DBCC CHECKDB with a repair option rather than DBCC CHECKALLOC with a repair option.

DBCC CHECKDB validates the integrity of everything in a database. There is no need to run DBCC CHECKALLOC or DBCC CHECKTABLE if DBCC CHECKDB either is currently or has been recently executed.

DBCC CHECKDB performs the same checking as if both a DBCC CHECKALLOC statement and a DBCC CHECKTABLE statement were executed for each table in the database.

DBCC CHECKDB requires a shared lock on all tables and indexes in the database for the duration of the operation. While DBCC CHECKDB is running, it is not possible to create, alter, or drop tables.

DBCC CHECKDB checks the linkages and sizes of text, ntext, and image pages for each table, and the allocation of all the pages in the database.

For each table in the database, DBCC CHECKDB checks that:

  • Index and data pages are correctly linked.
  • Indexes are in their proper sorted order.
  • Pointers are consistent.
  • The data on each page is reasonable.
  • Page offsets are reasonable.

Errors indicate potential problems in the database and should be corrected immediately.

Result Sets

Whether or not any options (except for the NO_INFOMSGS or NOINDEX options) are specified, DBCC CHECKDB returns this result set for the current database, if no database is specified (values may vary):

DBCC results for 'master'.

DBCC results for 'sysobjects'.

There are 862 rows in 13 pages for object 'sysobjects'.

DBCC results for 'sysindexes'.

There are 80 rows in 3 pages for object 'sysindexes'.

DBCC results for 'syscolumns'.

There are 2902 rows in 41 pages for object 'syscolumns'.

DBCC results for 'systypes'.

There are 24 rows in 1 pages for object 'systypes'.

DBCC results for 'syscomments'.

There are 1184 rows in 390 pages for object 'syscomments'.

DBCC results for 'sysfiles1'.

There are 2 rows in 1 pages for object 'sysfiles1'.

DBCC results for 'syspermissions'.

There are 492 rows in 2 pages for object 'syspermissions'.

DBCC results for 'sysusers'.

There are 13 rows in 1 pages for object 'sysusers'.

DBCC results for 'sysdepends'.

There are 3433 rows in 16 pages for object 'sysdepends'.

DBCC results for 'sysreferences'.

There are 0 rows in 1 pages for object 'sysreferences'.

DBCC results for 'sysfulltextcatalogs'.

There are 1 rows in 1 pages for object 'sysfulltextcatalogs'.

DBCC results for 'sysdatabases'.

There are 6 rows in 1 pages for object 'sysdatabases'.

DBCC results for 'sysxlogins'.

There are 3 rows in 1 pages for object 'sysxlogins'.

DBCC results for 'sysdevices'.

There are 6 rows in 1 pages for object 'sysdevices'.

DBCC results for 'sysmessages'.

There are 2768 rows in 109 pages for object 'sysmessages'.

DBCC results for 'sysconfigures'.

There are 41 rows in 1 pages for object 'sysconfigures'.

DBCC results for 'sysservers'.

There are 1 rows in 1 pages for object 'sysservers'.

DBCC results for 'syslanguages'.

There are 23 rows in 2 pages for object 'syslanguages'.

DBCC results for 'syscharsets'.

There are 103 rows in 30 pages for object 'syscharsets'.

DBCC results for 'sysaltfiles'.

There are 2 rows in 1 pages for object 'sysaltfiles'.

DBCC results for 'sysfilegroups'.

There are 1 rows in 1 pages for object 'sysfilegroups'.

DBCC results for 'sysallocations'.

There are 1 rows in 1 pages for object 'sysallocations'.

DBCC results for 'spt_committab'.

There are 0 rows in 1 pages for object 'spt_committab'.

DBCC results for 'spt_monitor'.

There are 1 rows in 1 pages for object 'spt_monitor'.

DBCC results for 'spt_values'.

There are 679 rows in 5 pages for object 'spt_values'.

DBCC results for 'spt_fallback_db'.

There are 0 rows in 1 pages for object 'spt_fallback_db'.

DBCC results for 'spt_fallback_dev'.

There are 0 rows in 1 pages for object 'spt_fallback_dev'.

DBCC results for 'spt_fallback_usg'.

There are 0 rows in 1 pages for object 'spt_fallback_usg'.

DBCC results for 'tbl1'.

There are 5 rows in 1 pages for object 'tbl1'.

DBCC results for 'FulltextTest'.

There are 4 rows in 1 pages for object 'FulltextTest'.

DBCC results for 'MSreplication_options'.

There are 2 rows in 1 pages for object 'MSreplication_options'.

DBCC results for 'spt_datatype_info_ext'.

There are 10 rows in 1 pages for object 'spt_datatype_info_ext'.

DBCC results for 'spt_datatype_info'.

There are 33 rows in 1 pages for object 'spt_datatype_info'.

DBCC results for 'spt_server_info'.

There are 29 rows in 1 pages for object 'spt_server_info'.

DBCC results for 'spt_provider_types'.

There are 23 rows in 1 pages for object 'spt_provider_types'.

CHECKDB found 0 allocation errors and 0 consistency errors in database 'master'.

DBCC execution completed. If DBCC printed error messages, contact your system administrator.

DBCC CHECKDB returns this result set if the NOINDEX option is specified (values may vary):

DBCC results for 'Northwind'.

Warning: NO_INDEX option of CHECKDB being used. Checks on non-system indexes will be skipped.

DBCC results for 'sysobjects'.

There are 104 rows in 2 pages for object 'sysobjects'.

DBCC results for 'sysindexes'.

There are 65 rows in 2 pages for object 'sysindexes'.

DBCC results for 'syscolumns'.

There are 610 rows in 9 pages for object 'syscolumns'.

DBCC results for 'systypes'.

There are 24 rows in 1 pages for object 'systypes'.

DBCC results for 'syscomments'.

There are 151 rows in 11 pages for object 'syscomments'.

DBCC results for 'sysfiles1'.

There are 2 rows in 1 pages for object 'sysfiles1'.

DBCC results for 'syspermissions'.

There are 68 rows in 1 pages for object 'syspermissions'.

DBCC results for 'sysusers'.

There are 13 rows in 1 pages for object 'sysusers'.

DBCC results for 'sysdepends'.

There are 383 rows in 2 pages for object 'sysdepends'.

DBCC results for 'sysreferences'.

There are 2 rows in 1 pages for object 'sysreferences'.

DBCC results for 'sysfulltextcatalogs'.

There are 0 rows in 1 pages for object 'sysfulltextcatalogs'.

DBCC results for 'sysfilegroups'.

There are 1 rows in 1 pages for object 'sysfilegroups'.

DBCC results for 'sysallocations'.

There are 1 rows in 1 pages for object 'sysallocations'.

DBCC results for 'Categories'.

There are 8 rows in 1 pages for object 'Categories'.

DBCC results for 'Customers'.

There are 91 rows in 3 pages for object 'Customers'.

DBCC results for 'Employees'.

There are 9 rows in 1 pages for object 'Employees'.

DBCC results for 'Suppliers'.

There are 29 rows in 1 pages for object 'Suppliers'.

DBCC results for 'Products'.

There are 77 rows in 2 pages for object 'Products'.

DBCC results for 'Shippers'.

There are 3 rows in 1 pages for object 'Shippers'.

DBCC results for 'Orders'.

There are 830 rows in 21 pages for object 'Orders'.

DBCC results for 'Order Details'.

There are 2155 rows in 10 pages for object 'Order Details'.

DBCC results for 'SouthAmericanCustomers'.

There are 16 rows in 2 pages for object 'SouthAmericanCustomers'.

DBCC results for 'CustomerResults'.

There are 16 rows in 2 pages for object 'CustomerResults'.

DBCC results for 'CustomersOne'.

There are 5 rows in 2 pages for object 'CustomersOne'.

DBCC results for 'CustomersTwo'.

There are 5 rows in 2 pages for object 'CustomersTwo'.

DBCC results for 'CustomersThree'.

There are 5 rows in 2 pages for object 'CustomersThree'.

DBCC results for 'tbl1'.

There are 5 rows in 1 pages for object 'tbl1'.

CHECKDB found 0 allocation errors and 0 consistency errors in database 'Northwind'.

DBCC execution completed. If DBCC printed error messages, contact your system administrator.

IF the NO_INFOMSGS option is specified, DBCC CHECKDB returns this result set (message):

DBCC execution completed. If DBCC printed error messages, contact your system administrator.

Permissions

DBCC CHECKDB permissions default to members of the sysadmin fixed server role or the db_owner fixed database role, and are not transferable.

Examples
A. Check both the current and the pubs database

    This example executes DBCC CHECKDB for the current database and for the pubs database.

    -- Check the current database.

    DBCC CHECKDB

    GO

    -- Check the pubs database without nonclustered indexes.

    DBCC CHECKDB ('pubs', NOINDEX)

    GO

    B. Check the current database, suppressing informational messages

    This example checks the current database and suppresses all informational messages.

    DBCC CHECKDB WITH NO_INFOMSGS

    GO

    See Also
    sp_helpdb | DBCC
System Tables |


DBCC CHECKFILEGROUP

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

Syntax

DBCC CHECKFILEGROUP
( [{'filegroup' | filegroup_id}] [, NOINDEX]
) [WITH {ALL_ERRORMSGS | NO_INFOMSGS}]

Arguments
'filegroup'
Is the name of the filegroup for which to check table allocation and structural integrity. If not specified, the default is the primary filegroup. Filegroup names must conform to the rules for identifiers.
filegroup_id
Is the filegroup identification number (ID) for which to check table allocation and structural integrity. Obtain filegroup_id from either the FILEGROUP_ID function or the sysfilegroups system table in the database containing the filegroup.
NOINDEX
Specifies that nonclustered indexes for nonsystem tables should not be checked. This decreases execution time. NOINDEX has no effect on system tables. DBCC CHECKFILEGROUP always checks all system table indexes when run on the default filegroup.
WITH
Specifies an option for the number of error messages to be returned. If neither ALL_ERRORMSGS nor NO_INFOMSGS is specified, Microsoft® SQL Server™ returns all error messages.
ALL_ERRORMSGS
Displays all error messages. If not specified, SQL Server displays a maximum of 200 error messages per table. Error messages are sorted by object ID, except for those messages generated from tempdb.
NO_INFOMSGS
Suppresses all informational messages and the report of space used.
Remarks

Executing DBCC CHECKFILEGROUP statements on all filegroups in a database is the same as running a single DBCC CHECKDB statement. The only difference is that any table with indexes on different filegroups has the table and indexes checked multiple times (one time for each filegroup holding the table or any of its indexes).

DBCC CHECKFILEGROUP prevents modification of all tables and indexes in the filegroup (as well as tables in other filegroups whose indexes are in the filegroup currently checked) for the duration of the operation.

During DBCC CHECKFILEGROUP execution, table creation and deletion actions are not allowed.

DBCC CHECKFILEGROUP checks the linkages and sizes of text, ntext, and image pages for each filegroup, and the allocation of all the pages in the filegroup.

For each table in the filegroup, DBCC CHECKFILEGROUP checks that:

  • Index and data pages are correctly linked.
  • Indexes are in their proper sorted order.
  • Pointers are consistent.
  • The data on each page is reasonable.
  • Page offsets are reasonable.

If a nonclustered index in the filegroup being explicitly checked is associated with a table in another filegroup, the table in the other filegroup (not originally explicitly checked) is also checked because verifying the index also requires verification of the base table structure. If a table in the filegroup being checked has a nonclustered index in another filegroup, however, the index is not checked because:

  • The base table structure is not dependent on the structure of a nonclustered index.
  • The DBCC CHECKFILEGROUP statement is focused on validating only objects in the filegroup. Nonclustered indexes do not have to be scanned to validate the base table.
  • Only checking the index when the filegroup holding it is specifically checked reduces duplicate processing when DBCC CHECKFILEGROUP is run on multiple filegroups in a database.

It is not possible to have a clustered index and a table on different filegroups, so these considerations only apply to nonclustered indexes.

The references to filegroup and filegroup_id are only relevant in the current database. Be sure to switch context to the proper database before executing DBCC CHECKFILEGROUP. For more information about changing the current database, see USE.

Result Sets

Whether or not any options (except NOINDEX) are specified, DBCC CHECKFILEGROUP returns this result set for the current database, if no database is specified (values may vary):

DBCC results for 'master'.

DBCC results for 'sysobjects'.

There are 862 rows in 13 pages for object 'sysobjects'.

DBCC results for 'sysindexes'.

There are 80 rows in 3 pages for object 'sysindexes'.

DBCC results for 'syscolumns'.

There are 2902 rows in 41 pages for object 'syscolumns'.

DBCC results for 'systypes'.

There are 24 rows in 1 pages for object 'systypes'.

DBCC results for 'syscomments'.

There are 1184 rows in 390 pages for object 'syscomments'.

DBCC results for 'sysfiles1'.

There are 2 rows in 1 pages for object 'sysfiles1'.

DBCC results for 'syspermissions'.

There are 492 rows in 2 pages for object 'syspermissions'.

DBCC results for 'sysusers'.

There are 13 rows in 1 pages for object 'sysusers'.

DBCC results for 'sysdepends'.

There are 3433 rows in 16 pages for object 'sysdepends'.

DBCC results for 'sysreferences'.

There are 0 rows in 1 pages for object 'sysreferences'.

DBCC results for 'sysfulltextcatalogs'.

There are 1 rows in 1 pages for object 'sysfulltextcatalogs'.

DBCC results for 'sysdatabases'.

There are 6 rows in 1 pages for object 'sysdatabases'.

DBCC results for 'sysxlogins'.

There are 3 rows in 1 pages for object 'sysxlogins'.

DBCC results for 'sysdevices'.

There are 6 rows in 1 pages for object 'sysdevices'.

DBCC results for 'sysmessages'.

There are 2768 rows in 109 pages for object 'sysmessages'.

DBCC results for 'sysconfigures'.

There are 41 rows in 1 pages for object 'sysconfigures'.

DBCC results for 'sysservers'.

There are 1 rows in 1 pages for object 'sysservers'.

DBCC results for 'syslanguages'.

There are 23 rows in 2 pages for object 'syslanguages'.

DBCC results for 'syscharsets'.

There are 103 rows in 30 pages for object 'syscharsets'.

DBCC results for 'sysaltfiles'.

There are 2 rows in 1 pages for object 'sysaltfiles'.

DBCC results for 'sysfilegroups'.

There are 1 rows in 1 pages for object 'sysfilegroups'.

DBCC results for 'sysallocations'.

There are 1 rows in 1 pages for object 'sysallocations'.

DBCC results for 'spt_committab'.

There are 0 rows in 1 pages for object 'spt_committab'.

DBCC results for 'spt_monitor'.

There are 1 rows in 1 pages for object 'spt_monitor'.

DBCC results for 'spt_values'.

There are 679 rows in 5 pages for object 'spt_values'.

DBCC results for 'spt_fallback_db'.

There are 0 rows in 1 pages for object 'spt_fallback_db'.

DBCC results for 'spt_fallback_dev'.

There are 0 rows in 1 pages for object 'spt_fallback_dev'.

DBCC results for 'spt_fallback_usg'.

There are 0 rows in 1 pages for object 'spt_fallback_usg'.

DBCC results for 'tbl1'.

There are 5 rows in 1 pages for object 'tbl1'.

DBCC results for 'FulltextTest'.

There are 4 rows in 1 pages for object 'FulltextTest'.

DBCC results for 'MSreplication_options'.

There are 2 rows in 1 pages for object 'MSreplication_options'.

DBCC results for 'spt_datatype_info_ext'.

There are 10 rows in 1 pages for object 'spt_datatype_info_ext'.

DBCC results for 'spt_datatype_info'.

There are 33 rows in 1 pages for object 'spt_datatype_info'.

DBCC results for 'spt_server_info'.

There are 29 rows in 1 pages for object 'spt_server_info'.

DBCC results for 'spt_provider_types'.

There are 23 rows in 1 pages for object 'spt_provider_types'.

CHECKFILEGROUP found 0 allocation errors and 0 consistency errors in database 'master'.

DBCC execution completed. If DBCC printed error messages, contact your system administrator.

DBCC CHECKFILEGROUP returns this result set if the NOINDEX option is specified:

DBCC results for 'pubs'.

Warning: NO_INDEX option of CHECKFILEGROUP being used. Checks on non-system indexes will be skipped.

DBCC results for 'sysobjects'.

There are 89 rows in 1 pages for object 'sysobjects'.

DBCC results for 'sysindexes'.

There are 48 rows in 2 pages for object 'sysindexes'.

DBCC results for 'syscolumns'.

There are 465 rows in 6 pages for object 'syscolumns'.

DBCC results for 'systypes'.

There are 27 rows in 1 pages for object 'systypes'.

DBCC results for 'syscomments'.

There are 129 rows in 9 pages for object 'syscomments'.

DBCC results for 'sysfiles1'.

There are 2 rows in 1 pages for object 'sysfiles1'.

DBCC results for 'syspermissions'.

There are 55 rows in 1 pages for object 'syspermissions'.

DBCC results for 'sysusers'.

There are 13 rows in 1 pages for object 'sysusers'.

DBCC results for 'sysdepends'.

There are 214 rows in 1 pages for object 'sysdepends'.

DBCC results for 'sysreferences'.

There are 10 rows in 1 pages for object 'sysreferences'.

DBCC results for 'sysfulltextcatalogs'.

There are 0 rows in 1 pages for object 'sysfulltextcatalogs'.

DBCC results for 'sysfilegroups'.

There are 1 rows in 1 pages for object 'sysfilegroups'.

DBCC results for 'sysallocations'.

There are 1 rows in 1 pages for object 'sysallocations'.

DBCC results for 'authors'.

There are 23 rows in 1 pages for object 'authors'.

DBCC results for 'publishers'.

There are 8 rows in 1 pages for object 'publishers'.

DBCC results for 'titles'.

There are 18 rows in 1 pages for object 'titles'.

DBCC results for 'titleauthor'.

There are 25 rows in 1 pages for object 'titleauthor'.

DBCC results for 'stores'.

There are 6 rows in 1 pages for object 'stores'.

DBCC results for 'sales'.

There are 21 rows in 1 pages for object 'sales'.

DBCC results for 'roysched'.

There are 86 rows in 1 pages for object 'roysched'.

DBCC results for 'discounts'.

There are 3 rows in 1 pages for object 'discounts'.

DBCC results for 'jobs'.

There are 14 rows in 1 pages for object 'jobs'.

DBCC results for 'pub_info'.

There are 8 rows in 1 pages for object 'pub_info'.

DBCC results for 'employee'.

There are 43 rows in 1 pages for object 'employee'.

CHECKFILEGROUP found 0 allocation errors and 0 consistency errors in database 'pubs'.

DBCC execution completed. If DBCC printed error messages, contact your system administrator.

DBCC CHECKFILEGROUP returns this result set if the NO_INFOMSGS option is specified:

DBCC execution completed. If DBCC printed error messages, contact your system administrator.

Permissions

DBCC CHECKFILEGROUP permissions default to members of the sysadmin fixed server role or the db_owner fixed database role, and are not transferable.

Examples
A. Check the PRIMARY filegroup in the pubs database

This example checks the pubs database primary filegroup.

USE pubs

GO

DBCC CHECKFILEGROUP

GO

B. Check the pubs PRIMARY filegroup without nonclustered indexes

    This example checks the pubs database primary filegroup (excluding nonclustered indexes) by specifying the primary filegroup’s identification number and by specifying the NOINDEX option.

    USE pubs

    GO

    DBCC CHECKFILEGROUP (1, NOINDEX)

    GO

    See Also
    FILEGROUP_ID | sysfilegroups
sp_helpfile | DBCC
sp_helpfilegroup |


DBCC CHECKIDENT

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

Syntax

DBCC CHECKIDENT
( 'table_name' [, { NORESEED | {RESEED [, new_reseed_value]} }]
)

Arguments
'table_name'
Is the name of the table for which to check the current identity value. Table names must conform to the rules for identifiers. The table specified must contain an identity column.
NORESEED
Specifies that the current identity value should not be corrected.
RESEED
Specifies that the current identity value should be corrected.
new_reseed_value
Is the value to use in reseeding the identity column.
Remarks

If necessary, DBCC CHECKIDENT corrects the current identity value for a column. The current identity value is not corrected, however, if the identity column was created with the NOT FOR REPLICATION clause (in either the CREATE TABLE or ALTER TABLE statement).

Invalid identity information can cause message 2627 when a primary key or unique key constraint exists on the identity column.

The specific corrections made to the current identity value depend on the parameter specifications.

DBCC CHECKIDENT statement | Identity correction(s) made
DBCC CHECKIDENT ('table_name', NORESEED) | The current identity value is not reset. DBCC CHECKIDENT returns a report indicating the current identity value and what it should be.
DBCC CHECKIDENT ('table_name') or DBCC CHECKIDENT ('table_name', RESEED) | If the current identity value for a table is lower than the maximum identity value stored in the column, it is reset using the maximum value in the identity column.
DBCC CHECKIDENT ('table_name', RESEED, new_reseed_value) | The current identity value is set to the new_reseed_value. Use care with this method because it forces the current identity value to be whatever is specified for new_reseed_value. If the value of new_reseed_value is less than the maximum value in the column, error 2627 is generated on subsequent references to the table.

The current identity value can be larger than the maximum value in the table. DBCC CHECKIDENT does not reset the current identity value automatically in this case. To reset the current identity value when it is larger than the maximum value in the column, use either of two methods:

  • Execute DBCC CHECKIDENT ('table_name', NORESEED) to determine the current maximum value in the column, and then specify that as the new_reseed_value in a DBCC CHECKIDENT ('table_name', RESEED, new_reseed_value) statement.
  • Execute DBCC CHECKIDENT ('table_name', RESEED, new_reseed_value) with new_reseed_value set to a very low value, and then run DBCC CHECKIDENT ('table_name', RESEED).
Result Sets

Whether or not any of the options are specified (for a table containing an identity column; this example uses the jobs table of the pubs database), DBCC CHECKIDENT returns this result set (values may vary):

Checking identity information: current identity value '14', current column value '14'.

DBCC execution completed. If DBCC printed error messages, contact your system administrator.

Permissions

DBCC CHECKIDENT permissions default to members of the sysadmin fixed server role or the db_owner fixed database role, and are not transferable.

Examples
A. Reset the current identity value, if needed

This example resets the current identity value, if needed, of the jobs table.

USE pubs

GO

DBCC CHECKIDENT (jobs)

GO

B. Report the current identity value

This example reports the current identity value in the jobs table, and does not correct the identity value, if incorrect.

USE pubs

GO

DBCC CHECKIDENT (jobs, NORESEED)

GO

C. Force the current identity value to 30

This example forces the current identity value in the jobs table to a value of 30.

USE pubs

GO

DBCC CHECKIDENT (jobs, RESEED, 30)

GO

See Also
ALTER TABLE | USE
CREATE TABLE | DBCC
IDENTITY (Property) |


DBCC CHECKTABLE

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

Syntax

DBCC CHECKTABLE
( 'table_name'
[, NOINDEX
| index_id
| { REPAIR_ALLOW_DATA_LOSS
| REPAIR_FAST
| REPAIR_REBUILD
}]
) [WITH {ALL_ERRORMSGS | NO_INFOMSGS}]

Arguments
'table_name'
Is the table for which to check data page integrity. Table names must conform to the rules for identifiers.
NOINDEX

Specifies that nonclustered indexes for nonsystem tables should not be checked.

REPAIR_ALLOW_DATA_LOSS | REPAIR_FAST| REPAIR_REBUILD
Specifies that DBCC CHECKTABLE repair the found errors. The database must be in single-user mode to use a repair option and can be one of the following.

Value | Description
REPAIR_ALLOW_DATA_LOSS | Performs all repairs done by REPAIR_REBUILD and includes allocation and deallocation of rows and pages for correcting allocation errors, structural row or page errors, and deletion of corrupted text objects. These repairs can result in some data loss. The repair may be done under a user transaction to allow the user to rollback the changes made. If repairs are rolled back, the database will still contain errors and should be restored from a backup. If a repair for an error has been skipped due to the provided repair level, any repairs that depend on the repair are also skipped. After repairs are completed, back up the database.
REPAIR_FAST | Performs minor, nontime-consuming repair actions such as repairing extra keys in nonclustered indexes. These repairs can be done quickly and without risk of data loss.
REPAIR_REBUILD | Performs all repairs done by REPAIR_FAST and includes time-consuming repairs such as rebuilding indexes. These repairs can be done without risk of data loss.

index_id

Is the index identification number (ID) for which to check data page integrity. If an index_id is specified, DBCC CHECKTABLE checks only that index.

WITH
Specifies an option for the number of error messages to be returned. If neither ALL_ERRORMSGS nor NO_INFOMSGS is specified, Microsoft® SQL Server™ returns all error messages.
ALL_ERRORMSGS
Displays all error messages. If not specified, SQL Server displays a maximum of 200 error messages per table. Error messages are sorted by object ID.
NO_INFOMSGS
Suppresses all informational messages and the report of space used.
Remarks
  • For the specified table, DBCC CHECKTABLE checks that:
  • Index and data pages are correctly linked.
  • Indexes are in their proper sorted order.
  • Pointers are consistent.
  • The data on each page is reasonable.
  • Page offsets are reasonable.

DBCC CHECKTABLE checks the linkages and sizes of text, ntext and image pages for the specified table. However, DBCC CHECKTABLE does not check the allocations of pages in the specified table. Use DBCC CHECKALLOC to check page allocations.

DBCC CHECKTABLE requires a shared lock on all tables and indexes in the database for the duration of the operation.

To perform DBCC CHECKTABLE on every table in the database, use DBCC CHECKDB.

Result Sets

DBCC CHECKTABLE returns this result set (same result set is returned if you specify only the table name or if you provide any of the options); this example specifies the authors table in the pubs database (values may vary):

DBCC results for 'authors'.

There are 23 rows in 1 pages for object 'authors'.

DBCC execution completed. If DBCC printed error messages, contact your system administrator.

Permissions

DBCC CHECKTABLE permissions default to members of the sysadmin fixed server role or the db_owner fixed database role, or the table owner, and are not transferable.

Examples
A. Check a specific table

This example checks the data page integrity of the authors table.

DBCC CHECKTABLE ('authors')

GO

B. Check the table without checking nonclustered indexes

This example checks the data page integrity of the authors table without checking nonclustered indexes.

DBCC CHECKTABLE ('authors', NOINDEX)

GO

C. Check a specific index

This example checks a specific index, which is obtained by accessing sysindexes.

USE pubs

DECLARE @indid int

SELECT @indid = indid

FROM sysindexes

WHERE id = OBJECT_ID('authors') AND name = 'aunmind'

DBCC CHECKTABLE ('authors', @indid)

GO

See Also
DBCC


DBCC DBREPAIR

Drops a damaged database.

Important DBCC DBREPAIR is included in Microsoft® SQL Server™ version 7.0 for backward compatibility only. It is recommended that DROP DATABASE be used to drop damaged databases. In a future version of SQL Server, DBCC DBREPAIR may not be supported.

See Also
DROP DATABASE DBCC


DBCC DBREINDEX

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

Syntax

DBCC DBREINDEX
( [ 'database.owner.table_name' [, index_name [, fillfactor ] ] ]
) [WITH NO_INFOMSGS]

Arguments
'database.owner.table_name'
Is the name of the table for which to rebuild the specified index(es). Database, owner, and table names must conform to the rules for identifiers. The entire database.owner.table_name must be enclosed in single quotation marks (‘) if either the database or owner parts are supplied. The single quotation marks are not necessary if only table_name is specified.
index_name
Is the name of the index to rebuild. Index names must conform to the rules for identifiers. If index_name is not specified or is specified as ‘ ‘, all indexes for the table are rebuilt.
fillfactor
Is the percentage of space on each index page to be used for storing data when the index is created. fillfactor replaces the original fillfactor as the new default for the index and for any other nonclustered indexes that are rebuilt because a clustered index is rebuilt. When fillfactor is 0, DBCC DBREINDEX uses the original fillfactor specified when the index was created.
WITH NO_INFOMSGS
Suppresses all informational messages (with severity levels from 0 through 10).
Remarks

DBCC DBREINDEX rebuilds an index for a table or all indexes defined for a table. By allowing an index to be rebuilt dynamically, indexes enforcing either PRIMARY KEY or UNIQUE constraints can be rebuilt without having to drop and re-create those constraints. This means an index can be rebuilt without knowing the table’s structure or constraints, which could occur after a bulk copy of data into the table.

If either index_name or fillfactor is specified, all preceding parameters must also be specified.

DBCC DBREINDEX can rebuild all of the indexes for a table in one statement, which is easier than coding multiple DROP INDEX and CREATE INDEX statements. Because the work is done by one statement, DBCC DBREINDEX is automatically atomic, while individual DROP INDEX and CREATE INDEX statements would have to be put in a transaction to be atomic. Also, DBCC DBREINDEX can take advantage of more optimizations with DBCC DBREINDEX than it can with individual DROP INDEX and CREATE INDEX statements.

DBCC DBREINDEX is not supported for use on system tables.

Result Sets

Whether or not any of the options (except NO_INFOMSGS) are specified (the table name must be specified), DBCC DBREINDEX returns this result set; this example uses the authors table of the pubs database (values will vary):

Index (ID = 1) is being rebuilt.

Index (ID = 2) is being rebuilt.

DBCC execution completed. If DBCC printed error messages, contact your system administrator.

DBCC DBREINDEX returns this result set (message) if the NO_INFOMSGS option is specified:

DBCC execution completed. If DBCC printed error messages, contact your system administrator.

Permissions

DBCC DBREINDEX permissions default to members of the sysadmin fixed server role or the db_owner fixed database role, or the table owner, and are not transferable.

Examples
A. Rebuild an index

This example rebuilds the au_nmind clustered index with a fillfactor of 80 on the authors table in the pubs database.

DBCC DBREINDEX ('pubs.dbo.authors', UPKCL_auidind, 80)

B. Rebuild all indexes

This example rebuilds all indexes on the authors table using a fillfactor value of 70.

DBCC DBREINDEX (authors, '', 70)

See Also
ALTER TABLE | DBCC
CREATE TABLE |


DBCC dllname (FREE)

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

Syntax

DBCC dllname (FREE)

Arguments
dllname
Is the name of the .dll to release from memory.
Remarks

When an extended stored procedure is executed, the .dll remains loaded by Microsoft® SQL Server™ until the server is shut down. This statement allows a .dll to be unloaded from memory without shutting down SQL Server. Execute sp_helpextendedproc to display the .dll files currently loaded by SQL Server.

Result Sets

DBCC (FREE) returns this result set (message) when a valid .dll is specified:

DBCC execution completed. If DBCC printed error messages, contact your system administrator.

Permissions

DBCC dllname (FREE) permissions default to members of the sysadmin fixed server role or the db_owner fixed database role, and are not transferable.

Examples

This example assumes an extended procedure xp_sample is implemented as Xp_sample.dll and has been executed. It uses the DBCC dllname (FREE) statement to unload the Xp_sample.dll file associated with the xp_sample extended procedure.

DBCC xp_sample (FREE)

See Also
sp_addextendedproc | sp_helpextendedproc
sp_dropextendedproc | DBCC


DBCC HELP

Returns syntax information for the specified DBCC statement.

Syntax

DBCC HELP ('dbcc_statement' | @dbcc_statement_var | '?')

Arguments
dbcc_statement | @dbcc_statement_var
Is the name of the DBCC statement for which to receive syntax information. Provide only the portion of the DBCC statement following the DBCC part of the statement. For example, CHECKDB rather than DBCC CHECKDB.
?
Specifies that Microsoft® SQL Server™ return all DBCC statements (minus the 'DBCC' portion of the statement) for which help information can be obtained.
Result Sets

DBCC HELP returns a result set displaying the syntax for the specified DBCC statement. Syntax varies between the DBCC statements.

Permissions

DBCC HELP permissions default to members of the sysadmin fixed server role only, and are not transferable.

Examples
A. Use DBCC HELP with a variable

This example returns syntax information for DBCC CHECKDB.

DECLARE @dbcc_stmt sysname

SET @dbcc_stmt = 'CHECKDB'

DBCC HELP (@dbcc_stmt)

GO

B. Use DBCC HELP with the ? option

This example returns all DBCC statements for which help is available.

DBCC HELP ('?')

GO

See Also
DBCC


DBCC INPUTBUFFER

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

Syntax

DBCC INPUTBUFFER (spid)

Arguments
spid
Is the system process ID (SPID) for the user connection as displayed in the output of the sp_who system stored procedure.
Result Sets

DBCC INPUTBUFFER returns this result set (the last event in the buffer was DBCC INPUTBUFFER(11)):

EventType      Parameters EventInfo

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

Language Event 0          DBCC INPUTBUFFER (11)

(1 row(s) affected)

DBCC execution completed. If DBCC printed error messages, contact your system administrator.

This table provides more information about the columns returned in the result set.

Column name | Data type | Description
EventType | nvarchar(30) | Event type, for example: RPC, language, or event.
Parameters | int | 0 = text 1- n = parameters
EventInfo | nvarchar(255) | For EventType of RPC, EventInfo is the procedure name, and the parameters that fit are shown. For EventType of language or event and Parameters = 0, EventInfo is the first 255 characters of the event.

Permissions

DBCC INPUTBUFFER permissions default to members of the sysadmin fixed server role only, who can see any SPID. Other users can see any SPID they own. Permissions are not transferable.

Examples

This example assumes a valid system process ID of 10.

DBCC INPUTBUFFER (10)

See Also
sp_who | DBCC
Trace Flags |


DBCC NEWALLOC

Checks the allocation of data and index pages for each table within the extent structures of the database.

Important DBCC NEWALLOC is identical to DBCC CHECKALLOC and is included in this Microsoft® SQL Server™ version 7.0 for backward compatibility only. It is recommended that DBCC CHECKALLOC be used to check the allocation and use of all pages in the specified database. In a future version of Microsoft SQL Server, DBCC NEWALLOC may not be supported.

See Also
DBCC CHECKALLOC | DBCC
DBCC CHECKDB |


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.

Syntax

DBCC OPENTRAN
( {'database_name' | database_id}
) [ WITH TABLERESULTS [, NO_INFOMSGS]
]

Arguments
'database_name'
Is the name of the database for which to display the oldest transaction information. Database names must conform to the rules for identifiers.
database_id
Is the database identification number (ID) for which to display the oldest transaction information. Obtain the database ID by using the DB_ID function.
WITH TABLERESULTS
Specifies results in a tabular format that can be loaded into a table. Use this option to create a table of results that can be inserted into a table for comparisons. When this option is not specified, results are formatted for readability.
NO_INFOMSGS
Suppresses all informational messages.
Remarks

If neither database_name nor database_id is specified, the default is the current database.

Use DBCC OPENTRAN to determine whether an open transaction exists within the log. When using the BACKUP LOG statement, only the inactive portion of the log can be truncated; an open transaction can cause the log to not truncate completely. In earlier versions of Microsoft® SQL Server™, either all users had to log off or the server had to be shut down and restarted to clear uncommitted transactions from the log. With DBCC OPENTRAN, an open transaction can be identified (by obtaining the system process ID from the sp_who output) and terminated, if necessary.

Result Sets

DBCC OPENTRAN returns this result set when there are no open transactions:

No active open transactions.

DBCC execution completed. If DBCC printed error messages, contact your system administrator.

Permissions

DBCC OPENTRAN permissions default to members of the sysadmin fixed server role or the db_owner fixed database role, and are not transferable.

Examples
A. Show open transactions both in the current database and in the pubs database

This example obtains transaction information for the current database and for the pubs database.

-- Display transaction information only for the current database.

DBCC OPENTRAN

GO

-- Display transaction information for the pubs database.

DBCC OPENTRAN('pubs')

GO

B. Show open transactions in a tabular format and load into a table

This example obtains the transaction information in a table form, and then loads the information into a SQL Server table.

-- Generate the output in table form.

DBCC OPENTRAN('pubs') WITH TABLERESULTS

GO

-- Put transaction information into the table

DECLARE @string VARCHAR (255)

SELECT @string   = "DBCC OPENTRAN('pubs') WITH TABLERESULTS"

SELECT @string

-- Create the table.

CREATE TABLE #opentran_output

(trantag varchar(30), tranvalue varchar(46))

-- Use INSERT INTO…EXEC to load into the table.

INSERT INTO #opentran_output

EXEC (@string)

GO

--Display the results.

SELECT *

FROM #opentran_output

GO

See Also
BEGIN TRANSACTION | ROLLBACK TRANSACTION
COMMIT TRANSACTION | DBCC
DB_ID |


DBCC OUTPUTBUFFER

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

Syntax

DBCC OUTPUTBUFFER (spid)

Arguments
spid
Is the system process ID for the user connection as displayed in the output of the sp_who system stored procedure.
Remarks

When you use DBCC OUTPUTBUFFER, DBCC OUTPUTBUFFER displays the results sent to the specified client (spid). For processes that do not contain output streams, an error message is returned.

To show the statement executed that returned the results displayed by DBCC OUTPUTBUFFER, execute DBCC INPUTBUFFER.

Result Sets

DBCC OUTPUTBUFFER returns this result set (values may vary):

Output Buffer

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

01fb8028:  04 00 01 5f 00 00 00 00 e3 1b 00 01 06 6d 00 61  ..._.........m.a

01fb8038:  00 73 00 74 00 65 00 72 00 06 6d 00 61 00 73 00  .s.t.e.r..m.a.s.

01fb8048:  74 00 65 00 72 00 ab 60 00 45 16 00 00 01 00 25  t.e.r..`.E.....%

01fb8058:  00 43 00 68 00 61 00 6e 00 67 00 65 00 64 00 20  .C.h.a.n.g.e.d.

01fb8068:  00 64 00 61 00 74 00 61 00 62 00 61 00 73 00 65  .d.a.t.a.b.a.s.e

01fb8078:  00 20 00 63 00 6f 00 6e 00 74 00 65 00 78 00 74  . .c.o.n.t.e.x.t

01fb8088:  00 20 00 74 00 6f 00 20 00 27 00 6d 00 61 00 73  . .t.o. .'.m.a.s

01fb8098:  00 74 00 65 00 72 00 27 00 2e 00 05 42 00 55 00  .t.e.r.'....B.U.

01fb80a8:  47 00 53 00 59 00 00 02 00 fd 01 00 e2 00 00 00  G.S.Y...........

01fb80b8:  00 00 fd 11 00 c1 00 01 00 00 00 79 00 00 00 00  ...........y....

01fb80c8:  ac 0d 00 00 01 00 00 00 00 26 04 04 1c 00 00 00  .........&......

01fb80d8:  fe 01 00 e0 00 00 00 00 00 81 06 00 00 00 01 00  ................

01fb80e8:  6a 11 00 00 0a 45 00 76 00 65 00 6e 00 74 00 43  j....E.v.e.n.t.C

01fb80f8:  00 6c 00 61 00 73 00 73 00 00 00 01 00 6a 11 00  .l.a.s.s.....j..

01fb8108:  00 0c 43 00 6f 00 6e 00 6e 00 65 00 63 00 74 00  ..C.o.n.n.e.c.t.

01fb8118:  69 00 6f 00 6e 00 49 00 64 00 00 00 01 00 e7 1e  i.o.n.I.d.......

01fb8128:  00 06 4e 00 54 00 55 00 73 00 65 00 72 00 00 00  ..N.T.U.s.e.r...

01fb8138:  01 00 e7 40 00 04 48 00 6f 00 73 00 74 00 00 00  ...@..H.o.s.t...

01fb8148:  01 00 e7 40 00 0b 41 00 70 00 70 00 6c 00 69 00  ...@..A.p.p.l.i.

01fb8158:  63 00 61 00 74 00 69 00 6f 00 6e 00 00 00 01 00  c.a.t.i.o.n.....

01fb8168:  6f 08 09 53 00 74 00 61 00 72 00 74 00 54 00 69  o..S.t.a.r.t.T.i

01fb8178:  00 6d 00 65 00 d1 00 00 ff ff ff ff ff ff 00 d1  .m.e............

01fb8188:  04 44 00 00 00 00 00 d1 04 45 00 00 00 00 00 d1  .D.......E......

01fb8198:  04 46 00 00 00 00 00 d1 04 47 00 00 00 00 00 d1  .F.......G......

01fb81a8:  04 48 00 00 00 00 00 d1 04 49 00 00 00 00 00 d1  .H.......I......

01fb81b8:  04 4a 00 00 00 00 00 ff 11 00 00 00 4b 00 00 00  .J..........K...

01fb81c8:  79 00 00 00 00 fe 00 00 e0 00 00 00 00 00 00 d1  y...............

01fb81d8:  04 0f 00 00 00 00 00 d1 04 10 00 00 00 00 00 d1  ................

01fb81e8:  04 11 00 00 00 00 00 d1 04 12 00 00 00 00 00 d1  ................

01fb81f8:  04 13 00 00 00 00 00 d1 04 14 00 00 00 00 00 d1  ................

01fb8208:  04 15 00 00 00 00 00 d1 04 16 00 00 00 00 00 d1  ................

01fb8218:  04 17 00 00 00 00 00 d1 04 18 00 00 00 00 00 d1  ................

01fb8228:   .

(33 row(s) affected)

DBCC execution completed. If DBCC printed error messages, contact your system administrator.

Permissions

DBCC OUTPUTBUFFER permissions default to members of the sysadmin fixed server role only, who can see any SPID. Other users can see any SPID they own. Permissions are not transferable.

Examples

This example returns current output buffer information for an assumed SPID of 13.

DBCC OUTPUTBUFFER (13)

See Also
sp_who | DBCC
Trace Flags |


DBCC PINTABLE

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

Syntax

DBCC PINTABLE (database_id, table_id)

Arguments
database_id
Is the database identification number (ID) of the table to be pinned. To determine the database ID, use the DB_ID function.
table_id
Is the object identification number (ID) of the table to be pinned. To determine the table ID, use the OBJECT_ID function.
Remarks

DBCC PINTABLE does not cause the table to be read into memory. As the pages from the table are read into the buffer cache by normal Transact-SQL statements, they are marked as pinned pages. SQL Server does not flush pinned pages when it needs space to read in a new page. SQL Server still logs updates to the page and, if necessary, writes the updated page back to disk. SQL Server does, however, keep a copy of the page available in the buffer cache until the table is unpinned with the DBCC UNPINTABLE statement.

DBCC PINTABLE is best used to keep small, frequently referenced tables in memory. The pages for the small table are read into memory one time, then all future references to their data do not require a disk read.

Caution Although DBCC PINTABLE can provide performance improvements, it must be used with care. If a large table is pinned, it can start using a large portion of the buffer cache and not leave enough cache to service the other tables in the system adequately. If a table larger than the buffer cache is pinned, it can fill the entire buffer cache. A member of the sysadmin fixed server role must shut down SQL Server, restart SQL Server, and then unpin the table. Pinning too many tables can cause the same problems as pinning a table larger than the buffer cache.

Result Sets

DBCC PINTABLE returns this result set:

Warning: Pinning tables should be carefully considered. If a pinned table is larger, or grows larger, than the available data cache, the server may need to be restarted and the table unpinned.

DBCC execution completed. If DBCC printed error messages, contact your system administrator.

Permissions

DBCC PINTABLE permissions default to members of the sysadmin fixed server role, the db_owner fixed database role, or the table owner, and are not transferable.

Examples

This example pins the authors table in the pubs database.

DECLARE @db_id int, @tbl_id int

USE pubs

SET @db_id = DB_ID('pubs')

SET @tbl_id = OBJECT_ID('pubs..authors')

DBCC PINTABLE (@db_id, @tbl_id)

See Also
DBCC UNPINTABLE | DBCC
sp_tableoption |


DBCC PROCCACHE

Displays information in a table format about the procedure cache.

Syntax

DBCC PROCCACHE

Remarks

SQL Server Performance Monitor uses DBCC PROCCACHE to obtain information about the procedure cache.

Result Sets

DBCC PROCCACHE returns this result set (values may vary):

num proc buffs num proc buffs used num proc buffs active proc cache size

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

70             70                  23                    73

proc cache used proc cache active

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

73              26

(1 row(s) affected)

DBCC execution completed. If DBCC printed error messages, contact your system administrator.

This table describes the columns of the result set.

Column name | Description
num proc buffs | Number of possible stored procedures that could be in the procedure cache
num proc buffs used | Number of cache slots holding stored procedures
num proc buffs active | Number of cache slots holding stored procedures that are currently executing
proc cache size | Total size of the procedure cache
proc cache used | Amount of the procedure cache holding stored procedures
proc cache active | Amount of the procedure cache holding stored procedures that are currently executing

Permissions

DBCC PROCCACHE permissions default to members of the sysadmin fixed server role or the db_owner fixed database role, and are not transferable.

See Also
DBCC


DBCC ROWLOCK

Used for Microsoft® SQL Server™ version 6.5, enabled Insert Row Locking (IRL) operations on tables.

Important Row-level locking is enabled by default in SQL Server. The locking strategy of SQL Server is row locking with possible promotion to page or table locking. DBCC ROWLOCK does not alter the locking behavior of SQL Server (it has no effect) and is included in Microsoft SQL Server version 7.0 for backward compatibility of existing scripts and procedures only. In a future version of SQL Server, DBCC ROWLOCK may not be supported.

See Also
DBCC


DBCC SHOWCONTIG

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

Syntax

DBCC SHOWCONTIG
[
( table_id [, index_id]
)
]

Arguments
table_id
Is the table identification number (ID) for which to check fragmentation information. If not specified, all tables in the current database are checked. To obtain the table ID, use the OBJECT_ID function.
index_id
Is the index identification number (ID) for which to check fragmentation information. If not specified, the statement processes all indexes for the specified table. To obtain the index ID, use sysindexes.
Remarks

This statement traverses the page chain at the leaf level of the specified index when index_id is specified. If only table_id is specified, or if index_id is 0, the data pages of the specified table are scanned. DBCC SHOWCONTIG determines whether the table is heavily fragmented. Table fragmentation occurs through the process of data modifications (INSERT, UPDATE, and DELETE statements) made against the table. Because these modifications are not usually distributed equally among the rows of the table, the “fullness” of each page can vary over time. For queries that scan part or all of a table, this can cause additional page reads.

When a table is heavily fragmented, reduce fragmentation and improve read-ahead (parallel data scan) performance by dropping and re-creating a clustered index (without using the SORTED_DATA option). Re-creating a clustered index reorganizes the data, resulting in full data pages. The level of “fullness” can be configured using the FILLFACTOR option.

Result Sets

DBCC SHOWCONTIG returns this result set when a table ID is specified; the output is for the authors table of the pubs database (values may vary):

DBCC SHOWCONTIG scanning 'authors' table...

[SHOW_CONTIG - SCAN ANALYSIS]

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

Table: 'authors' (117575457)  Indid: 1  dbid:5

TABLE level scan performed.

- Pages Scanned................................: 2

- Extents Scanned..............................: 2

- Extent Switches..............................: 1

- Avg. Pages per Extent........................: 1.0

- Scan Density [Best Count:Actual Count].......: 50.00% [1:2]

- Logical Scan Fragmentation ..................: 0.00%

- Extent Scan Fragmentation ...................: 50.00%

- Avg. Bytes free per page.....................: 7051.0

- Avg. Page density (full).....................: 12.89%

(11 row(s) affected)

DBCC execution completed. If DBCC printed error messages, contact your system administrator.

This table describes the information in the result set.

Statistic | Description
Pages Scanned | Number of pages in the table or index.
Extents Scanned | Number of extents in the table or index.
Extent Switches | Number of times the DBCC statement moved from one extent to another while it traversed the pages of the table or index.
Avg. Pages per Extent | Number of pages per extent in the page chain.
Scan Density [Best Count: Actual Count] | Best count is the ideal number of extent changes if everything is contiguously linked. Actual count is the actual number of extent changes. The number in scan density is 100 if everything is contiguous; if it is less than 100, some fragmentation exists. Scan density is a percentage.
Logical Scan Fragmentation | Percentage of out-of-order pages returned from scanning the leaf pages of an index. This number is not relevant to heaps and text indexes. An out of order page is one for which the next page indicated in an IAM is a different page than the page pointed to by the next page pointer in the leaf page.
Extent Scan Fragmentation | Percentage of out-of-order pages in scanning the leaf pages of an index. This number is not relevant to heaps. An out-of-order extent is one for which the extent containing the current page for an index is not physically the next extent after the extent containing the previous page for an index.
Avg. Bytes free per page | Average number of free bytes on the pages scanned. The higher the number, the less full the pages are. Lower numbers are better. This number is also affected by row size; a large row size can result in a higher number.
Avg. Page density (full) | Average page density (as a percentage). This value takes into account row size, so it is a more accurate indication of how full your pages are. The higher the percentage, the better.

Permissions

DBCC SHOWCONTIG permissions default to members of the sysadmin fixed server role or the db_owner fixed database role, and are not transferable.

Examples
A. Display fragmentation information for a table

This example displays fragmentation information for the table with the specified table ID number.

DBCC SHOWCONTIG (16003088)

GO

B. Use OBJECT_ID to obtain the table ID and sysindexes to obtain the index ID

This example uses OBJECT_ID and sysindexes to obtain the table ID and index ID for the aunmind index of the authors table.

USE pubs

GO

DECLARE @id int, @indid int

SET @id = OBJECT_ID('authors')

SELECT @indid = indid

FROM sysindexes

WHERE id = @id

    AND name = 'aunmind'

DBCC SHOWCONTIG (@id, @indid)

GO

See Also
CREATE INDEX | OBJECT_ID
DBCC DBREINDEX | sysindexes
DROP INDEX | DBCC


DBCC SHOW_STATISTICS

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

Syntax

DBCC SHOW_STATISTICS (table, target)

Arguments
table
Is the name of the table for which to display statistics information. Table names must conform to the rules for identifiers.
target
Is the name of the object (index name or collection) for which to display statistics information. Target names must conform to the rules for identifiers. If target is both an index name and a statistics collection name, both index and column statistics are returned. If no index or statistics collection is found with the specified name, an error is returned.
Remarks

The results returned indicate the selectivity of an index (the lower the density returned, the higher the selectivity) and provide the basis for determining whether or not an index is useful to the optimizer. The results returned are based on distribution steps of the index.

To see the last date the statistics were updated, use STATS_DATE.

Result Sets

DBCC SHOW_STATISTICS returns this result set; the result set shown is for authors table and aunmind index (values may vary):

Statistics for INDEX 'aunmind'.

Updated              Rows        Rows Sampled Steps       Density

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

May 13 1998  4:35PM  23          23           23          3.9697543E-2

Average key length

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

22.173912

(1 row(s) affected)

All density              Columns

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

4.5454547E-2             au_lname

4.3478262E-2             au_lname, au_fname

(2 row(s) affected)

Steps

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

Bennet

Blotchet-Halls

Carson

DeFrance

del Castillo

Dull

Green

Greene

Gringlesby

Hunter

Karsen

Locksley

MacFeather

McBadden

O'Leary

Panteley

Ringer

Ringer

Smith

Straight

Stringer

White

Yokomoto

(23 row(s) affected)

DBCC execution completed. If DBCC printed error messages, contact your system administrator.

This table describes the columns in the result set.

Column name | Description
Updated | Date and time the statistics were last updated
Rows | Number of rows in the table
Rows Sampled | Number of rows sampled for statistics information
Steps | Number of distribution steps
Density | Selectivity of the index
Average key length | Average length of a row
All density | Selectivity of the specified column prefix in the index
Columns | Name of the index column prefix for which the all density is displayed
Steps | Number of histogram values in the current distribution statistics for the specified target on the specified table

Permissions

DBCC SHOW_STATISTICS permissions default to members of the sysadmin fixed server role or the db_owner fixed database role, or the table owner, and are not transferable.

Examples

This example displays statistics information for the UPKCL_auidind index of the authors table.

USE pubs

DBCC SHOW_STATISTICS (authors, UPKCL_auidind)

GO

Here is the result set:

Statistics for INDEX 'UPKCL_auidind'.

Updated              Rows        Rows Sampled Steps       Density

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

Feb 23 1998  9:04AM  23          23           23          4.3478262E-2

Average row length

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

88.695663

(1 row(s) affected)

All density              Columns

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

4.3478262E-2             au_id

(1 row(s) affected)

Steps

-----------

172-32-1176

213-46-8915

238-95-7766

267-41-2394

274-80-9391

341-22-1782

409-56-7008

427-17-2319

472-27-2349

486-29-1786

527-72-3246

648-92-1872

672-71-3249

712-45-1867

722-51-5454

724-08-9931

724-80-9391

756-30-7391

807-91-6654

846-92-7186

893-72-1158

899-46-2035

998-72-3567

(23 row(s) affected)

See Also
CREATE INDEX | sp_dboption
CREATE STATISTICS | STATS_DATE
DROP STATISTICS | UPDATE STATISTICS
sp_autostats | USE
sp_createstats | DBCC


DBCC SHRINKDATABASE

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

Syntax

DBCC SHRINKDATABASE
( database_name [, target_percent]
[, {NOTRUNCATE | TRUNCATEONLY}]
)

Arguments
database_name
Is the name of the database to be shrunk. Database names must conform to the rules for identifiers.
target_percent
Is the desired percentage of free space left in the database file after the database has been shrunk.
NOTRUNCATE
Causes the freed file space to be retained in the database files. If not specified, the freed file space is released to the operating system.
TRUNCATEONLY
Causes any unused space in the data files to be released to the operating system and shrinks the file to the last allocated extent, reducing the file size without moving any data. No attempt is made to relocate rows to unallocated pages. target_percent is ignored when TRUNCATEONLY is used.
Remarks

Microsoft® SQL Server™ can shrink:

  • All data and log files for a specific database. Execute DBCC SHRINKDATABASE.
  • One data or log file at a time for a specific database. Execute DBCC SHRINKFILE.

DBCC SHRINKDATABASE shrinks data files on a per-file basis. However, DBCC SHRINKDATABASE shrinks log files as if all the log files existed in one contiguous log pool.

Assume a database named mydb with two data files and two log files. Both data and log files are 10 MB in size. The first data file contains 6 MB of data.

For each file, SQL Server calculates a target size, which is the size to which the file is to be shrunk. When DBCC SHRINKDATABASE is specified with target_percent, SQL Server calculates target size to be the target_percent amount of space free in the file after shrinking. For example, if you specify a target_percent of 25 for shrinking mydb. SQL Server calculates the target size for this file to be 8 MB (6 MB of data plus 2 MB of free space). Therefore, SQL Server moves any data from the last 2 MB of the data file to any free space in the first 8 MB of the data file and then shrinks the file.

Assume the first data file of mydb contains 7 MB of data. Specifying target_percent of 30 allows this data file to be shrunk to the desired free percentage of 30. However, specifying a target_percent of 40 does not shrink the data file because SQL Server will not shrink a file to a size smaller than the data currently occupies. You can also think of this issue another way: 40 percent desired free space + 70 percent full data file (7 MB out of 10 MB) is greater than 100 percent. Because the desired percentage free plus the current percentage that the data file occupies is over 100 percent (by 10 percent), any target_size greater than 30 will not shrink the data file.

For log files, SQL Server uses target_percent to calculate the target size for the entire log; therefore, target_percent is the amount of free space in the log after the shrink operation. Target size for the entire log is then translated to target size for each log file. Unlike data files, the shrinking of log files is not immediate. Each log file is marked with the target size of the shrink operation. Each subsequent log backup or log truncation attempts to shrink the file and bring its size as close to the target size as possible. Because a log file can only be shrunk to a virtual log file boundary, it may not be possible to shrink a log file to a size smaller than the size of a virtual log file, even if it is not being used. For example, a database with a log file of 1 GB can have the log file shrunk to only 128 MB.

The target size for data and log files as calculated by DBCC SHRINKDATABASE can never be smaller than the minimum size of a file. The minimum size of a file is the size specified when the file was originally created, or the last explicit size set with a file size changing operation such as ALTER DATABASE with the MODIFY FILE option or DBCC SHRINKFILE. For example, if all the data and log files of mydb were specified to be 10 MB at the time CREATE DATABASE was executed, the minimum size of each file is 10 MB. DBCC SHRINKDATABASE cannot shrink any of the files smaller than 10 MB. If one of the files is explicitly grown to a size of 20 MB by using ALTER DATABASE with the MODIFY FILE option, the new minimum size of the file is 20 MB. To shrink a file to a size smaller than its minimum size, use DBCC SHRINKFILE and specify the new size. Executing DBCC SHRINKFILE changes the minimum file size to the new size specified.

When using data files, DBCC SHRINKDATABASE has the NOTRUNCATE and TRUNCATEONLY options. Both options are ignored if specified for log files. DBCC SHRINKDATABASE with neither option is equivalent to a DBCC SHRINKDATABASE with the NOTRUNCATE option followed by a DBCC SHRINKDATABASE with the TRUNCATEONLY option.

The NOTRUNCATE option, with or without specifying target_percent, performs the actual data movement operations of DBCC SHRINKDATABASE including the movement of allocated pages from the end of a file to unallocated pages in the front of the file. However, the free space at the end of the file is not returned to the operating system and the physical size of the file does not change. Therefore, data files appear not to shrink when the NOTRUNCATE option is specified. For example, assume you are using the mydb database again. mydb has two data files and two log files. The second data file and second log file are both 10 MB in size. When DBCC SHRINKDATABASE mydb NOTRUNCATE is executed, Microsoft SQL Server moves the data from the later pages to the front pages of the data file. However, the file still remains 10 MB in size.

The TRUNCATEONLY option reclaims all free space at the end of the file to the operating system. However, TRUNCATEONLY does not perform any page movement inside the file or files. The specified file is shrunk only to the last allocated extent. target_percent is ignored if specified with the TRUNCATEONLY option.

The database cannot be made smaller than the size of the model database.

The database being shrunk does not have to be in single user mode, other users can be working in the database when it is shrunk. This includes system databases.

Result Sets

DBCC SHRINKDATABASE returns this result set when only the database name is specified (result set used pubs); values may vary:

DbId   FileId CurrentSize MinimumSize UsedPages   EstimatedPages

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

5      1      176         96          168         168

5      2      96          63          96          56

(2 row(s) affected)

DBCC execution completed. If DBCC printed error messages, contact your system administrator.

Note SQL Server does not display rows for those files not shrunk.

DBCC SHRINKDATABASE returns this result set when the database name and a target percentage (with or without the NOTRUNCATE or TRUNCATEONLY options) are specified; this result set used a target percentage of 5 (values may vary):

DbId   FileId CurrentSize MinimumSize UsedPages   EstimatedPages

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

5      2      96          63          96          56

(1 row(s) affected)

DBCC execution completed. If DBCC printed error messages, contact your system administrator.

This table describes the columns in the result set.

Column name | Description
DbId | Database identification number of the file SQL Server attempted to shrink.
FileId | The file identification number of the file SQL Server attempted to shrink.
CurrentSize | The number of 8-KB pages the file currently occupies.
MinimumSize | The number of 8 -B pages the file could occupy, at minimum. This corresponds to the minimum size or originally created size of a file.
UsedPages | The number of 8 -B pages currently used by the file.
EstimatedPages | The number of 8-KB pages that SQL Server estimates the file could be shrunk down to.

Permissions

DBCC SHRINKDATABASE permissions default to members of the sysadmin fixed server role or the db_owner fixed database role, and are not transferable.

Examples

This example decreases the size of the files in the UserDB user database to allow 10 percent free space in the files of UserDB.

DBCC SHRINKDATABASE (UserDB, 10)

GO

See Also
ALTER DATABASE DBCC


DBCC SHRINKFILE

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

Syntax

DBCC SHRINKFILE
( {file_name | file_id }
{ [, target_size]
| [, {EMPTYFILE | NOTRUNCATE | TRUNCATEONLY}]
}
)

Arguments
file_name
Is the logical name of the file being shrunk. File names must conform to the rules for identifiers.
file_id
Is the identification number (ID) of the file to be shrunk. To obtain a file ID, use the FILE_ID function or search sysfiles in the current database.
target_size
Is the desired size for the file in megabytes, expressed as an integer. If not specified, DBCC SHRINKFILE reduces the size as much as possible.

If target_size is specified, DBCC SHRINKFILE attempts to shrink the file to the specified size. Used pages in the part of the file to be freed are relocated to available free space in the part of the file retained. For example, if there is a 10-MB data file, a DBCC SHRINKFILE with a target_size of 8 causes all used pages in the last 2 MB of the file to be reallocated into any available free slots in the first 8 MB of the file. DBCC SHRINKFILE does not shrink a file past the size needed to store the data in the file. For example, if 7 MB of a 10-MB data file is used, a DBCC SHRINKFILE statement with a target_size of 6 shrinks the file to only 7 MB, not 6 MB.

EMPTYFILE
Migrates all data from the specified file to other files in the same filegroup. Microsoft® SQL Server™ no longer allows data to be placed on the file used with the EMPTY_FILE option. This option allows the file to be dropped using the ALTER DATABASE statement.
NOTRUNCATE
Causes the freed file space to be retained in the files.

When NOTRUNCATE is specified along with target_size, the space freed is not released to the operating system. The only effect of the DBCC SHRINKFILE is to relocate used pages from above the target_size line to the front of the file. When NOTRUNCATE is not specified, all freed file space is returned to the operating system.

TRUNCATEONLY
Causes any unused space in the files to be released to the operating system and shrinks the file to the last allocated extent, reducing the file size without moving any data. No attempt is made to relocate rows to unallocated pages. target_size is ignored when TRUNCATEONLY is used.
Remarks

DBCC SHRINKFILE applies to the files in the current database. Switch context to the database to issue a DBCC SHRINKFILE statement referencing a file in that particular database. For more information about changing the current database, see USE.

The database cannot be made smaller than the size of the model database.

Use DBCC SHRINKFILE to reduce the size of a file to smaller than its originally created size. The minimum file size for the file is then reset to the newly specified size.

To remove any data that may be in a file, execute DBCC SHRINKFILE(‘file_name’, EMPTYFILE) before executing ALTER DATABASE.

The database being shrunk does not have to be in single-user mode; other users can be working in the database when the file is shrunk. You do not have to run SQL Server in single-user mode to shrink the system databases.

For log files, SQL Server uses target_size to calculate the target size for the entire log; therefore, target_size is the amount of free space in the log after the shrink operation. Target size for the entire log is then translated to target size for each log file. Unlike data files, the shrinking of log files is not immediate. Each log file is marked with the target size of the shrink operation. Each subsequent log backup or log truncation attempts to shrink the file and bring its size as close to the target size as possible. Because a log file can only be shrunk to a virtual log file boundary, it may not be possible to shrink a log file to a size smaller than the size of a virtual log file, even if it is not being used. For example, a database with a log file of 1 GB can have the log file shrunk to only 128 MB.

Result Sets

DBCC SHRINKFILE returns this result set (values may vary):

DbId   FileId CurrentSize MinimumSize UsedPages   EstimatedPages

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

5      1      176         96          168         168

(1 row(s) affected)

DBCC execution completed. If DBCC printed error messages, contact your system administrator.

This table describes the columns in the result set.

Column name | Description
DbId | Database identification number of the file SQL Server attempted to shrink.
FileId | The file identification number of the file SQL Server attempted to shrink.
CurrentSize | The number of 8-KB pages the file currently occupies.
MinimumSize | The number of 8-KB pages the file could occupy, at minimum. This corresponds to the minimum size or originally created size of a file.
UsedPages | The number of 8-KB pages currently used by the file.
EstimatedPages | The number of 8-KB pages that SQL Server estimates the file could be shrunk down to.

Permissions

DBCC SHRINKFILE permissions default to members of the sysadmin fixed server role or the db_owner fixed database role, and are not transferable.

Examples

This example shrinks the size of a file named DataFil1 in the UserDB user database to 7 MB.

USE UserDB

GO

DBCC SHRINKFILE (DataFil1, 7)

GO

See Also
ALTER DATABASE | sysfiles
FILE_ID | DBCC


DBCC SQLPERF

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

Syntax

DBCC SQLPERF (LOGSPACE)

Remarks

The transaction log accumulates information about changes to data in each database. The information returned by DBCC SQLPERF(LOGSPACE) can be used to monitor the amount of space used and indicates when to back up or truncate the transaction log.

Result Sets

DBCC SQLPERF(LOGSPACE) returns this result set (values and entries may vary):

Database Name       Log Size (MB)            Log Space Used (%)   Status

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

Northwind           0.9921875                36.614174            0

pubs                0.7421875                45.394737            0

msdb                1.4921875                44.535339            0

tempdb              0.4921875                40.874954            0

model               0.7421875                39.86842             0

master              0.9921875                42.962597            0

(6 row(s) affected)

DBCC execution completed. If DBCC printed error messages, contact your system administrator.

This table describes the columns in the result set.

Column name | Definition
Database Name | Name of the database for the log statistics displayed.
Log Size (MB) | The actual amount of space available for the log. This amount is smaller than the amount originally allocated for log space because Microsoft® SQL Server™ reserves a small amount of disk space for internal header information.
Log Space Used (%) | Percentage of the log file currently occupied with transaction log information.
Status | Status of the log file (always contains 0).

Permissions

DBCC SQLPERF permissions default to any user.

Examples

This example displays LOGSPACE information for all databases currently installed.

DBCC SQLPERF(LOGSPACE)

GO

Here is the result set:

Database Name Log Size (MB) Log Space Used (%) Status

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

pubs                1.99219            4.26471           0

msdb                3.99219            17.0132           0

tempdb              1.99219            1.64216           0

model                   1.0            12.7953           0

master              3.99219            14.3469           0

See Also
sp_spaceused DBCC


DBCC TEXTALL

Selects tables in the database that have text, ntext, or image columns and runs TEXTALLOC on them.

Important DBCC TEXTALL is included in Microsoft® SQL Server™ version 7.0 for backward compatibility only. It is recommended that DBCC CHECKDB be used to check the allocation and structural integrity of all the objects in the database. In a future version of SQL Server, DBCC TEXTALL may not be supported.

See Also
DBCC


DBCC TEXTALLOC

Checks the allocation of text, ntext, or image columns for a table.

Important DBCC TEXTALLOC is included in Microsoft® SQL Server™ version 7.0 for backward compatibility only. It is recommended that DBCC CHECKTABLE be used to check the integrity of the data, index, text, ntext, and image pages for the specified table. In a future version of SQL Server, DBCC TEXTALLOC may not be supported.

See Also
DBCC


DBCC TRACEOFF

Turns off (disables) the specified trace flag(s).

Syntax

DBCC TRACEOFF (trace# [,…n])

Arguments
trace#
Is the number of the trace flag to turn off.
n
Is a placeholder indicating that multiple trace flags can be specified.
Remarks

Trace flags are used to customize certain characteristics controlling how Microsoft® SQL Server™ operates.

Result Sets

DBCC TRACEOFF returns this result set (message):

DBCC execution completed. If DBCC printed error messages, contact your system administrator.

Permissions

DBCC TRACEOFF permissions default to members of the sysadmin fixed server role only, and are not transferable.

Examples

This example disables the display of line numbers in syntax errors.

DBCC TRACEOFF (106)

GO

See Also
Trace Flags DBCC


DBCC TRACEON

Turns on (enables) the specified trace flag.

Syntax

DBCC TRACEON (trace# [,…n])

Arguments
trace#
Is the number of the trace flag to turn on.
n
Is a placeholder indicating that multiple trace flags can be specified.
Remarks

Trace flags are used to customize certain characteristics controlling how Microsoft® SQL Server™ operates. Trace flags remain enabled in the server until disabled by executing a DBCC TRACEOFF statement. New connections into the server do not see any trace flags until a DBCC TRACEON statement is issued. Then, the connection will see all trace flags currently enabled in the server, even those that have been enabled by another connection.

Result Sets

DBCC TRACEON returns this result set (message):

DBCC execution completed. If DBCC printed error messages, contact your system administrator.

Permissions

DBCC TRACEON permissions default to members of the sysadmin fixed server role only, and are not transferable.

Examples

This example enables the display of line numbers in syntax errors.

DBCC TRACEON (106)

GO

See Also
Trace Flags DBCC


DBCC TRACESTATUS

Displays the status of trace flags.

Syntax

DBCC TRACESTATUS (trace# [,…n])

Arguments
trace#
Is the number of the trace flag to display the status of.
n
Is a placeholder indicating that multiple trace flags can be specified.
Result Sets

DBCC TRACESTATUS returns this result set; trace flags 106 and 107 were specified (values may vary):

TraceFlag   Status

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

106         0

107         0

(2 row(s) affected)

DBCC execution completed. If DBCC printed error messages, contact your system administrator.

DBCC TRACESTATUS returns a column for the trace flag number and a column for the status, indicating whether the trace flag is on (1) or off (0). To get status information for all trace flags currently turned on, specify - 1 for trace#.

Permissions

DBCC TRACESTATUS permissions default to members of the sysadmin fixed server role only, and are not transferable.

Examples
A. Display the status of all trace flags currently enabled

This example displays the status of all currently enabled trace flags by specifying a value of -1.

DBCC TRACESTATUS(-1)

GO

B. Display the status of multiple trace flags

This example displays the status of trace flags 204 and 107.

DBCC TRACESTATUS (204,107)

GO

See Also
Trace Flags DBCC


DBCC UNPINTABLE

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

Syntax

DBCC UNPINTABLE (database_id, table_id)

Arguments
database_id
Is the database identification number (ID) of the database containing the table to be pinned. To obtain the database ID, use DB_ID.
table_id
Is the object identification number (ID) of the table to be pinned. To determine the object ID, use OBJECT_ID.
Remarks

DBCC UNPINTABLE does not cause the table to be immediately flushed from the data cache. It specifies that all of the pages for the table in the buffer cache can be flushed if space is needed to read in a new page from disk.

Result Sets

DBCC UNPINTABLE returns this result set (message):

DBCC execution completed. If DBCC printed error messages, contact your system administrator.

Permissions

DBCC UNPINTABLE DBCC SHRINKFILE permissions default to members of the sysadmin fixed server role or the db_owner fixed database role, or the table owner, and are not transferable.

Examples

This example unpins the authors table in the pubs database.

DECLARE @db_id int, @tbl_id int

USE pubs

SET @db_id = DB_ID('pubs')

SET @tbl_id = OBJECT_ID('pubs..authors')

DBCC UNPINTABLE (@db_id, @tbl_id)

See Also
DB_ID | sp_tableoption
DBCC PINTABLE | DBCC
OBJECT_ID |


DBCC UPDATEUSAGE

Reports and corrects inaccuracies in the sysindexes table, which may result in incorrect space usage reports by the sp_spaceused system stored procedure.

Syntax

DBCC UPDATEUSAGE
( {'database_name' | 0}
[, 'table_name' [, index_id]
]
) [ WITH [COUNT_ROWS] [, NO_INFOMSGS ]
]

Arguments
'database_name' | 0
Is the name of the database for which to report and correct space usage statistics. Database names must conform to the rules for identifiers. If 0 is specified, then the current database is used.
'table_name'
Is the name of the table for which to report and correct space usage statistics. Table names must conform to the rules for identifiers.
index_id
Is the identification number (ID) of the index to use. If not specified, the statement processes all indexes for the specified table.
COUNT_ROWS
Specifies that the rows column of sysindexes is updated with the current count of the number of rows in the table. This applies only to sysindexes rows that have an indid of 0 or 1. This option can affect performance on large tables.
NO_INFOMSGS
Suppresses all informational messages.
Remarks

DBCC UPDATEUSAGE corrects the rows, used, reserved, and dpages columns of the sysindexes table for tables and clustered indexes. Size information is not maintained for nonclustered indexes.

If there are no inaccuracies in sysindexes, DBCC UPDATEUSAGE returns no data. If inaccuracies are found and corrected and the WITH NO_INFOMSGS option is not used, UPDATEUSAGE returns the rows and columns being updated in sysindexes.

Use UPDATEUSAGE to synchronize space-usage counters. DBCC UPDATEUSAGE can take some time to run on large tables or databases, so it should typically be used only when you suspect incorrect values returned by sp_spaceused. sp_spaceused accepts an optional parameter to run DBCC UPDATEUSAGE before returning space information for the table or index.

Result Sets

DBCC UPDATEUSAGE returns this result set for the Northwind database (values may vary):

DBCC UPDATEUSAGE: Sysindexes row for Table 'sysobjects' (IndexId=2) updated:

RSVD Pages: Changed from (2) to (1) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'sysobjects' (IndexId=3) updated:

RSVD Pages: Changed from (2) to (1) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'syscolumns' (IndexId=2) updated:

USED Pages: Changed from (5) to (6) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'syscolumns' (IndexId=1) updated:

USED Pages: Changed from (18) to (17) pages

RSVD Pages: Changed from (22) to (21) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'systypes' (IndexId=2) updated:

RSVD Pages: Changed from (2) to (1) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'systypes' (IndexId=1) updated:

RSVD Pages: Changed from (6) to (3) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'sysusers' (IndexId=2) updated:

RSVD Pages: Changed from (2) to (1) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'sysfulltextcatalogs' (IndexId=2) updated:

RSVD Pages: Changed from (2) to (1) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'sysfilegroups' (IndexId=2) updated:

RSVD Pages: Changed from (2) to (1) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'Categories' (IndexId=2) updated:

RSVD Pages: Changed from (2) to (1) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'Categories' (IndexId=255) updated:

USED Pages: Changed from (13) to (18) pages

RSVD Pages: Changed from (18) to (17) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'Categories' (IndexId=1) updated:

USED Pages: Changed from (6) to (5) pages

RSVD Pages: Changed from (6) to (3) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'Customers' (IndexId=2) updated:

RSVD Pages: Changed from (2) to (1) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'Customers' (IndexId=3) updated:

RSVD Pages: Changed from (2) to (1) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'Customers' (IndexId=4) updated:

RSVD Pages: Changed from (2) to (1) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'Customers' (IndexId=5) updated:

RSVD Pages: Changed from (2) to (1) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'Customers' (IndexId=1) updated:

USED Pages: Changed from (14) to (13) pages

RSVD Pages: Changed from (14) to (8) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'Employees' (IndexId=2) updated:

RSVD Pages: Changed from (2) to (1) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'Employees' (IndexId=3) updated:

RSVD Pages: Changed from (2) to (1) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'Employees' (IndexId=255) updated:

USED Pages: Changed from (28) to (34) pages

RSVD Pages: Changed from (34) to (33) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'Employees' (IndexId=1) updated:

USED Pages: Changed from (8) to (7) pages

RSVD Pages: Changed from (8) to (4) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'Suppliers' (IndexId=2) updated:

RSVD Pages: Changed from (2) to (1) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'Suppliers' (IndexId=3) updated:

RSVD Pages: Changed from (2) to (1) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'Suppliers' (IndexId=255) updated:

USED Pages: Changed from (1) to (2) pages

RSVD Pages: Changed from (2) to (1) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'Suppliers' (IndexId=1) updated:

USED Pages: Changed from (8) to (7) pages

RSVD Pages: Changed from (8) to (4) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'Products' (IndexId=2) updated:

RSVD Pages: Changed from (2) to (1) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'Products' (IndexId=3) updated:

RSVD Pages: Changed from (2) to (1) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'Products' (IndexId=1) updated:

USED Pages: Changed from (9) to (8) pages

RSVD Pages: Changed from (9) to (5) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'Shippers' (IndexId=1) updated:

USED Pages: Changed from (4) to (3) pages

RSVD Pages: Changed from (4) to (2) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'Orders' (IndexId=2) updated:

USED Pages: Changed from (6) to (5) pages

RSVD Pages: Changed from (6) to (4) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'Orders' (IndexId=3) updated:

USED Pages: Changed from (5) to (4) pages

RSVD Pages: Changed from (5) to (3) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'Orders' (IndexId=4) updated:

USED Pages: Changed from (6) to (5) pages

RSVD Pages: Changed from (6) to (4) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'Orders' (IndexId=5) updated:

USED Pages: Changed from (6) to (5) pages

RSVD Pages: Changed from (6) to (4) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'Orders' (IndexId=6) updated:

USED Pages: Changed from (5) to (4) pages

RSVD Pages: Changed from (5) to (3) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'Orders' (IndexId=7) updated:

USED Pages: Changed from (6) to (5) pages

RSVD Pages: Changed from (6) to (4) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'Orders' (IndexId=0) updated:

DATA Pages: Changed from (21) to (22) pages

USED Pages: Changed from (55) to (50) pages

RSVD Pages: Changed from (59) to (46) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'Order Details' (IndexId=2) updated:

USED Pages: Changed from (7) to (6) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'Order Details' (IndexId=3) updated:

USED Pages: Changed from (7) to (6) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'Order Details' (IndexId=1) updated:

USED Pages: Changed from (27) to (24) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'SouthAmericanCustomers' (IndexId=0) updated:

DATA Pages: Changed from (2) to (3) pages

RSVD Pages: Changed from (10) to (9) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'CustomerResults' (IndexId=0) updated:

DATA Pages: Changed from (2) to (3) pages

RSVD Pages: Changed from (10) to (9) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'CustomersOne' (IndexId=0) updated:

DATA Pages: Changed from (2) to (3) pages

RSVD Pages: Changed from (10) to (9) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'CustomersTwo' (IndexId=0) updated:

DATA Pages: Changed from (2) to (3) pages

RSVD Pages: Changed from (10) to (9) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'CustomersThree' (IndexId=0) updated:

DATA Pages: Changed from (2) to (3) pages

RSVD Pages: Changed from (10) to (9) pages

DBCC UPDATEUSAGE: Sysindexes row for Table 'tbl1' (IndexId=0) updated:

DATA Pages: Changed from (1) to (2) pages

USED Pages: Changed from (1) to (2) pages

RSVD Pages: Changed from (2) to (1) pages

DBCC execution completed. If DBCC printed error messages, contact your system administrator.

Permissions

DBCC UPDATEUSAGE permissions default to members of the sysadmin fixed server role or the db_owner fixed database role, and are not transferable.

Examples
A. Update sysindexes by specifying 0 for the current database

This example specifies 0 for the database name and Microsoft® SQL Server™ reports information for the current database.

DBCC UPDATEUSAGE (0)

GO

B. Update sysindexes for pubs, suppressing informational messages

    This example specifies pubs as the database name, and suppresses all informational messages.

    DBCC UPDATEUSAGE ('pubs') WITH NO_INFOMSGS

    GO

    C. Update sysindexes for the authors table

      This example reports information on the authors table.

      DBCC UPDATEUSAGE ('pubs','authors')

      GO

      D. Update sysindexes for a specified index

      This example obtains the index ID for the UPKCL_auidind index of the authors table and uses that index ID in the DBCC UPDATEUSAGE example.

      -- Get the index ID.

      DECLARE @indid int

      SELECT @indid = indid

      FROM sysindexes

      WHERE id = object_id('authors')

          AND name = 'UPKCL_auidind'

      DBCC UPDATEUSAGE ('pubs', 'authors', @indid)

      GO

      See Also
      sp_spaceused | DBCC
sysindexes |


DBCC USEROPTIONS

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

Syntax

DBCC USEROPTIONS

Result Sets

DBCC USEROPTIONS returns this result set (values and entries may vary):

Set Option                   Value

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

textsize                     64512

language                     us_english

dateformat                   mdy

datefirst                    7

ansi_null_dflt_on            SET

ansi_warnings                SET

ansi_padding                 SET

ansi_nulls                   SET

concat_null_yields_null      SET

(9 row(s) affected)

DBCC execution completed. If DBCC printed error messages, contact your system administrator.

DBCC USEROPTIONS returns a column for the name of the SET option and a column for the setting of the option.

Permissions

DBCC USEROPTIONS permissions default to any user.

Examples

This example returns the active SET options for the current connection.

DBCC USEROPTIONS

See Also
SET | DBCC
SET TRANSACTION ISOLATION LEVEL |


DEALLOCATE

Removes a cursor reference. When the last cursor reference is deallocated, the data structures comprising the cursor are released by Microsoft® SQL Server™.

Syntax

DEALLOCATE { { [GLOBAL] cursor_name } | @cursor_variable_name}

Arguments
cursor_name
Is the name of an already-declared cursor. If both a global and a local cursor exist with cursor_name as their name, cursor_name refers to the global cursor if GLOBAL is specified and to the local cursor if GLOBAL is not specified .
@cursor_variable_name
Is the name of a cursor variable. @cursor_variable_name must be of type cursor.
Remarks

Statements that operate on cursors use either a cursor name or a cursor variable to refer to the cursor. DEALLOCATE removes the association between a cursor and the cursor name or cursor variable. If a name or variable is the last one referencing the cursor, the cursor is deallocated and any resources used by the cursor are freed. Scroll locks used to protect the isolation of fetches are freed at DEALLOCATE. Transaction locks used to protect updates, including positioned updates made through the cursor, are held until the end of the transaction.

The DECLARE CURSOR statement allocates and associates a cursor with a cursor name:

DECLARE abc SCROLL CURSOR FOR

SELECT * FROM authors

After a cursor name is associated with a cursor, the name cannot be used for another cursor of the same scope (GLOBAL or LOCAL) until this cursor has been deallocated.

A cursor variable is associated with a cursor using one of two methods:

  • By name using a SET statement that sets a cursor to a cursor variable:

    DECLARE @MyCrsrRef CURSOR

    SET @MyCrsrRef = abc

  • A cursor can also be created and associated with a variable without having a cursor name defined:

    DECLARE @MyCursor CURSOR

    SET @MyCursor = CURSOR LOCAL SCROLL FOR

    SELECT * FROM titles

A DEALLOCATE @cursor_variable_name statement removes only the reference of the named variable to the cursor. The variable is not deallocated until it goes out of scope at the end of the batch, stored procedure, or trigger. After a DEALLOCATE @cursor_variable_name statement, the variable can be associated with another cursor using the SET statement.

USE pubs

GO
DECLARE @MyCursor CURSOR

SET @MyCursor = CURSOR LOCAL SCROLL FOR

SELECT * FROM titles

DEALLOCATE @MyCursor

SET @MyCursor = CURSOR LOCAL SCROLL FOR

SELECT * FROM sales

GO

A cursor variable does not have to be explicitly deallocated. The variable is implicitly deallocated when it goes out of scope.

Permissions

DEALLOCATE permissions default to any valid user.

Examples

This script shows how cursors persist until the last name or until the variable referencing them has been deallocated.

USE pubs

GO

-- Create and open a global named cursor that

-- is visible outside the batch.

DECLARE abc CURSOR GLOBAL SCROLL FOR

SELECT * FROM authors

OPEN abc

GO

-- Reference the named cursor with a cursor variable.

DECLARE @MyCrsrRef1 CURSOR

SET @MyCrsrRef1 = abc

-- Now deallocate the cursor reference.

DEALLOCATE @MyCrsrRef1

-- Cursor abc still exists.

FETCH NEXT FROM abc

GO

-- Reference the named cursor again.

DECLARE @MyCrsrRef2 CURSOR

SET @MyCrsrRef2 = abc

-- Now deallocate cursor name abc.

DEALLOCATE abc

-- Cursor still exists, referenced by @MyCrsrRef2.

FETCH NEXT FROM @MyCrsrRef2

-- Cursor finally is deallocated when last referencing

-- variable goes out of scope at the end of the batch.

GO

-- Create an unnamed cursor.

DECLARE @MyCursor CURSOR

SET @MyCursor = CURSOR LOCAL SCROLL FOR

SELECT * FROM titles

-- The following statement deallocates the cursor

-- because no other variables reference it.

DEALLOCATE @MyCursor

GO

See Also
CLOSE | FETCH
DECLARE @local_variable | OPEN


decimal and numeric

Numeric data types with fixed precision and scale.

decimal[(p[, s])] and numeric[(p[, s])]
Fixed precision and scale numbers. When maximum precision is used, valid values are from - 10^38 -1 through 10^38 - 1. The SQL-92 synonyms for decimal are dec and dec(p, s).
p (precision)
Specifies the maximum total number of decimal digits that can be stored, both to the left and to the right of the decimal point. The precision must be a value from 1 through the maximum precision. The maximum precision is 28 unless the server is started with the /p parameter of sqlservr. If the /p parameter is specified, the maximum precision is 38; therefore, 0 < p <=38.
s (scale)
Specifies the maximum number of decimal digits that can be stored to the right of the decimal point. Scale must be a value from 0 through p. The default scale is 0; therefore, 0 <= s <= p. Maximum storage sizes vary, based on the precision.

Precision | Storage bytes
1 - 9 | 5
10-19 | 9
20-28 | 13
29-38 | 17

See Also
ALTER TABLE | DELETE
CAST and CONVERT | INSERT
CREATE TABLE | SET @local_variable
Data Types | UPDATE
DECLARE @local_variable |


DECLARE @local_variable

Variables are declared in the body of a batch or procedure with the DECLARE statement and are assigned values with either a SET or SELECT statement. Cursor variables can be declared with this statement and used with other cursor-related statements. After declaration, all variables are initialized as NULL.

Syntax

DECLARE
{
{@local_variable data_type}
| {@cursor_variable_name CURSOR}
} [,…n]

Arguments
@local_variable
Is the name of a variable. Variable names must begin with an at sign (@). Local variable names must conform to the rules for identifiers.
data_type
Is any system-supplied or user-defined data type. A variable cannot be of text, ntext, or image data type. For more information about system data types, see Data Types. For more information about user-defined data types, see sp_addtype.
@cursor_variable_name
Is the name of a cursor variable. Cursor variable names must begin with an at sign (@) and conform to the rules for identifiers.
CURSOR
Specifies that the variable is a local, cursor variable.
n
Is a placeholder indicating that multiple variables can be specified and assigned values.
Remarks

Variables are often used in a batch or procedure as counters for WHILE, LOOP, or for an IF…ELSE block.

Variables can be used only in expressions, not in place of object names or keywords. To construct dynamic SQL statements, use EXECUTE.

The scope of a local variable is the batch, stored procedure, or statement block in which it is declared.

A cursor variable that currently has a cursor assigned to it can be referenced as a source in a:

  • CLOSE statement.
  • DEALLOCATE statement.
  • FETCH statement.
  • OPEN statement.
  • Positioned DELETE or UPDATE statement.
  • SET CURSOR variable statement (on the right side).

In all these statements, Microsoft® SQL Server™ raises an error if a referenced cursor variable exists but does not have a cursor currently allocated to it. If a referenced cursor variable does not exist, SQL Server raises the same error raised for an undeclared variable of another type.

A cursor variable:

  • Can be the target of either a cursor type or another cursor variable. For more information, see SET @local_variable.
  • Can be referenced as the target of an output cursor parameter in an EXECUTE statement if the cursor variable does not have a cursor currently assigned to it.
  • Should be regarded as a pointer to the cursor.
Examples
A. Use DECLARE

This example uses a local variable named @find to retrieve author information for all authors with last names beginning with Ring.

USE pubs

DECLARE @find varchar(30)

SET @find = 'Ring%'

SELECT au_lname, au_fname, phone

FROM authors

WHERE au_lname LIKE @find

Here is the result set:

au_lname                               au_fname             phone

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

Ringer                                 Anne                 801 826-0752

Ringer                                 Albert               801 826-0752

(2 row(s) affected)

B. Use DECLARE with two variables

This example retrieves employee names from employees of Binnet & Hardley (pub_id = 0877) who were hired on or after January 1, 1993.

USE pubs

SET NOCOUNT ON

GO

DECLARE @pub_id char(4), @hire_date datetime

SET @pub_id = '0877'

SET @hire_date = '1/01/93'

-- Here is the SELECT statement syntax to assign values to two local

-- variables.

-- SELECT @pub_id = '0877', @hire_date = '1/01/93'

SET NOCOUNT OFF

SELECT fname, lname

FROM employee

WHERE pub_id = @pub_id and hire_date >= @hire_date

Here is the result set:

fname                lname

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

Anabela              Domingues

Paul                 Henriot

(2 row(s) affected)

See Also
SELECT EXECUTE


DECLARE CURSOR

Defines the attributes of a Transact-SQL server cursor, such as its scrolling behavior and the query used to build the result set on which the cursor operates. DECLARE CURSOR accepts both a syntax based on the SQL-92 standard and a syntax using a set of Transact-SQL extensions.

SQL-92 Syntax

DECLARE cursor_name [INSENSITIVE] [SCROLL] CURSOR
FOR select_statement
[FOR {READ ONLY | UPDATE [OF column_name [,…n]]}]

Transact-SQL Extended Syntax

DECLARE cursor_name CURSOR
[LOCAL | GLOBAL]
[FORWARD_ONLY | SCROLL]
[STATIC | KEYSET | DYNAMIC | FAST_FORWARD]
[READ_ONLY | SCROLL_LOCKS | OPTIMISTIC]
[TYPE_WARNING]
FOR select_statement
[FOR UPDATE [OF column_name [,…n]]]

SQL-92 Arguments
cursor_name
Is the name of the Transact-SQL server cursor being defined. cursor_name must conform to the rules for identifiers.
INSENSITIVE
Defines a cursor that makes a temporary copy of the data to be used by the cursor. All requests to the cursor are answered from this temporary table in tempdb; therefore, modifications made to base tables are not reflected in the data returned by fetches made to this cursor, and this cursor does not allow modifications. When SQL-92 syntax is used, if INSENSITIVE is omitted, committed deletes and updates made to the underlying tables (by any user) are reflected in subsequent fetches.
SCROLL
Specifies that all fetch options (FIRST, LAST, PRIOR, NEXT, RELATIVE, ABSOLUTE) are available. If SCROLL is not specified in an SQL-92 DECLARE CURSOR, NEXT is the only fetch option supported. SCROLL cannot be specified if FAST_FORWARD is also specified.
select_statement
Is a standard SELECT statement that defines the result set of the cursor. The keywords COMPUTE, COMPUTE BY, FOR BROWSE, and INTO are not allowed within select_statement of a cursor declaration.

Microsoft® SQL Server™ implicitly converts the cursor to another type if clauses in select_statement conflict with the functionality of the requested cursor type.

READ ONLY
Prevents updates from being made through this cursor. The cursor cannot be referenced in a WHERE CURRENT OF clause in an UPDATE or DELETE statement. This option overrides the default capability of a cursor to be updated.
UPDATE [OF column_name [,…n]]
Defines updatable columns within the cursor. If OF column_name [,…n] is specified, only the columns listed allow modifications. If UPDATE is specified without a column list, all columns can be updated.
Transact-SQL Extended Arguments
cursor_name
Is the name of the Transact-SQL server cursor being defined. cursor_name must conform to the rules for identifiers.
LOCAL
Specifies that the scope of the cursor is local to the batch, stored procedure, or trigger in which the cursor was created. The cursor name is only valid within this scope. The cursor can be referenced by local cursor variables in the batch, stored procedure, or trigger, or a stored procedure OUTPUT parameter. An OUTPUT parameter is used to pass the local cursor back to the calling batch, stored procedure, or trigger, which can assign the parameter to a cursor variable to reference the cursor after the stored procedure terminates. The cursor is implicitly deallocated when the batch, stored procedure, or trigger terminates, unless the cursor was passed back in an OUTPUT parameter. If it is passed back in an OUTPUT parameter, the cursor is deallocated when the last variable referencing it is deallocated or goes out of scope.
GLOBAL
Specifies that the scope of the cursor is global to the connection. The cursor name can be referenced in any stored procedure or batch executed by the connection. The cursor is only implicitly deallocated at disconnect.

Note If neither GLOBAL or LOCAL is specified, the default is controlled by the setting of the default to local cursor database option. In SQL Server version 7.0, this option defaults to FALSE to match earlier versions of SQL Server, in which all cursors were global. The default of this option may change in future versions of SQL Server.

FORWARD_ONLY
Specifies that the cursor can only be scrolled from the first to the last row. FETCH NEXT is the only supported fetch option. If FORWARD_ONLY is specified without the STATIC, KEYSET, or DYNAMIC keywords, the cursor operates as a DYNAMIC cursor. When neither FORWARD_ONLY nor SCROLL is specified, FORWARD_ONLY is the default, unless the keywords STATIC, KEYSET, or DYNAMIC are specified. STATIC, KEYSET, and DYNAMIC cursors default to SCROLL. Unlike database APIs such as ODBC and ADO, FORWARD_ONLY is supported with STATIC, KEYSET, and DYNAMIC Transact-SQL cursors. FAST_FORWARD and FORWARD_ONLY are mutually exclusive, if one is specified the other cannot be specified.
STATIC
Defines a cursor that makes a temporary copy of the data to be used by the cursor. All requests to the cursor are answered from this temporary table in tempdb; therefore, modifications made to base tables are not reflected in the data returned by fetches made to this cursor, and this cursor does not allow modifications.
KEYSET
Specifies that the membership and order of rows in the cursor are fixed when the cursor is opened. The set of keys that uniquely identify the rows is built into a table in tempdb known as the keyset. Changes to nonkey values in the base tables, either made by the cursor owner or committed by other users, are visible as the owner scrolls around the cursor. Inserts made by other users are not visible (inserts cannot be made through a Transact-SQL server cursor). If a row is deleted, an attempt to fetch the row returns an @@FETCH_STATUS of -2. Updates of key values from outside the cursor resemble a delete of the old row followed by an insert of the new row. The row with the new values is not visible, and attempts to fetch the row with the old values return an @@FETCH_STATUS of -2. The new values are visible if the update is done through the cursor by specifying the WHERE CURRENT OF clause.
DYNAMIC
Defines a cursor that reflects all data changes made to the rows in its result set as you scroll around the cursor. The data values, order, and membership of the rows can change on each fetch. The ABSOLUTE fetch option is not supported with dynamic cursors.
FAST_FORWARD
Specifies a FORWARD_ONLY, READ_ONLY cursor with performance optimizations enabled. FAST_FORWARD cannot be specified if SCROLL or FOR_UPDATE is also specified. FAST_FORWARD and FORWARD_ONLY are mutually exclusive, if one is specified the other cannot be specified.
READ_ONLY
Prevents updates from being made through this cursor. The cursor cannot be referenced in a WHERE CURRENT OF clause in an UPDATE or DELETE statement. This option overrides the default capability of a cursor to be updated.
SCROLL_LOCKS
Specifies that positioned updates or deletes made through the cursor are guaranteed to succeed. Microsoft® SQL Server™ locks the rows as they are read into the cursor to ensure their availability for later modifications. SCROLL_LOCKS cannot be specified if FAST_FORWARD is also specified.
OPTIMISTIC
Specifies that positioned updates or deletes made through the cursor do not succeed if the row has been updated since it was read into the cursor. SQL Server does not lock rows as they are read into the cursor. It instead uses comparisons of timestamp column values, or a checksum value if the table has no timestamp column, to determine whether the row was modified after it was read into the cursor. If the row was modified, the attempted positioned update or delete fails. OPTIMISTIC cannot be specified if FAST_FORWARD is also specified.
TYPE_WARNING
Specifies that a warning message is sent to the client if the cursor is implicitly converted from the requested type to another.
select_statement
Is a standard SELECT statement that defines the result set of the cursor. The keywords COMPUTE, COMPUTE BY, FOR BROWSE, and INTO are not allowed within select_statement of a cursor declaration.

SQL Server implicitly converts the cursor to another type if clauses in select_statement conflict with the functionality of the requested cursor type.

UPDATE [OF column_name [,…n]]
Defines updatable columns within the cursor. If OF column_name [,…n] is supplied, only the columns listed allow modifications. If UPDATE is specified without a column list, all columns can be updated, unless the READ_ONLY concurrency option was specified.
Remarks

DECLARE CURSOR defines the attributes of a Transact-SQL server cursor, such as its scrolling behavior and the query used to build the result set on which the cursor operates. The OPEN statement populates the result set, and FETCH returns a row from the result set. The CLOSE statement releases the current result set associated with the cursor. The DEALLOCATE statement releases the resources used by the cursor.

The first form of the DECLARE CURSOR statement uses the SQL-92 syntax for declaring cursor behaviors. The second form of DECLARE CURSOR uses Transact-SQL extensions that allow you to define cursors using the same cursor types used in the database API cursor functions of ODBC, ADO, and DB-Library.

You cannot mix the two forms. If you specify the SCROLL or INSENSITIVE keywords before the CURSOR keyword, you cannot use any keywords between the CURSOR and FOR select_statement keywords. If you specify any keywords between the CURSOR and FOR select_statement keywords, you cannot specify SCROLL or INSENSITIVE before the CURSOR keyword.

If a DECLARE CURSOR using Transact-SQL syntax does not specify READ_ONLY, OPTIMISTIC, or SCROLL_LOCKS, the default is as follows:

  • If the SELECT statement does not support updates (insufficient permissions, accessing remote tables that do not support updates, and so on), the cursor is READ_ONLY.
  • STATIC and FAST_FORWARD cursors default to READ_ONLY.
  • DYNAMIC, and KEYSET cursors default to OPTIMISTIC.

Cursor names can be referenced only by other Transact-SQL statements. They cannot be referenced by database API functions. For example, after declaring a cursor, the cursor name cannot be referenced from OLE DB, ODBC, ADO, or DB-Library functions or methods. The cursor rows cannot be fetched using the fetch functions or methods of the APIs; the rows can be fetched only by Transact-SQL FETCH statements.

After a cursor has been declared, these system stored procedures can be used to determine the characteristics of the cursor.

System stored procedure | Description
sp_cursor_list | Returns a list of cursors currently visible on the connection and their attributes.
sp_describe_cursor | Describes the attributes of a cursor, such as whether it is a forward-only or scrolling cursor.
sp_describe_cursor_columns | Describes the attributes of the columns in the cursor result set.
sp_describe_cursor_tables | Describes the base tables accessed by the cursor.

Permissions

DECLARE CURSOR permissions default to any user that has SELECT permissions on the views, tables, and columns used in the cursor.

Examples
A. Use simple cursor and syntax

The result set generated at the opening of this cursor includes all rows and all columns in the authors table of the pubs database. This cursor can be updated, and all updates and deletes are represented in fetches made against this cursor. FETCH NEXT is the only fetch available because the SCROLL option has not been specified.

DECLARE authors_cursor CURSOR

    FOR SELECT * FROM authors

OPEN authors_cursor

FETCH NEXT FROM authors_cursor

B. Use nested cursors to produce report output

This example shows how cursors can be nested to produce complex reports. The inner cursor is declared for each author.

SET NOCOUNT ON

DECLARE @au_id varchar(11), @au_fname varchar(20), @au_lname varchar(40),

    @message varchar(80), @title varchar(80)

PRINT "-------- Utah Authors report --------"

DECLARE authors_cursor CURSOR FOR

SELECT au_id, au_fname, au_lname

FROM authors

WHERE state = "UT"

ORDER BY au_id

OPEN authors_cursor

FETCH NEXT FROM authors_cursor

INTO @au_id, @au_fname, @au_lname

WHILE @@FETCH_STATUS = 0

BEGIN

    PRINT " "

    SELECT @message = "----- Books by Author: " +

        @au_fname + " " + @au_lname

    PRINT @message

    -- Declare an inner cursor based

    -- on au_id from the outer cursor.

    DECLARE titles_cursor CURSOR FOR

    SELECT t.title

    FROM titleauthor ta, titles t

    WHERE ta.title_id = t.title_id AND

    ta.au_id = @au_id    -- Variable value from the outer cursor

    OPEN titles_cursor

    FETCH NEXT FROM titles_cursor INTO @title

    IF @@FETCH_STATUS <> 0

        PRINT "         <<No Books>>"

    WHILE @@FETCH_STATUS = 0

    BEGIN

        SELECT @message = "         " + @title

        PRINT @message

        FETCH NEXT FROM titles_cursor INTO @title

    END

    CLOSE titles_cursor

    DEALLOCATE titles_cursor

    -- Get the next author.

    FETCH NEXT FROM authors_cursor

    INTO @au_id, @au_fname, @au_lname

END

CLOSE authors_cursor

DEALLOCATE authors_cursor

GO

-------- Utah Authors report --------

----- Books by Author: Anne Ringer

         The Gourmet Microwave

         Is Anger the Enemy?

----- Books by Author: Albert Ringer

         Is Anger the Enemy?

         Life Without Fear

See Also
@@FETCH_STATUS | OPEN
CLOSE | SELECT
DEALLOCATE | sp_configure
FETCH |


DEGREES

Given an angle in radians, returns the corresponding angle in degrees.

Syntax

DEGREES(numeric_expression)

Arguments
numeric_expression
Is an expression of the exact numeric or approximate numeric data type category, except for the bit data type.
Return Code Values

Returns the same type as numeric_expression.

Examples

This example returns the number of degrees in an angle of PI/2 radians.

SELECT 'The number of degrees in PI/2 radians is: ' +
CONVERT(varchar, DEGREES((PI()/2)))

GO

Here is the result set:

The number of degrees in PI/2 radians is 90

(1 row(s) affected)

See Also

Mathematical Functions


DELETE

Removes rows from a table.

Syntax

DELETE
[FROM ]
{
table_name [ [AS] table_alias] WITH ( <table_hint_limited> […n])
| view_name [ [AS] table_alias]
 | rowset_function_limited
}

[ FROM {<table_source>} [,…n] ]

[WHERE
{ <search_condition>
| { [ CURRENT OF
{
{ [ GLOBAL ] cursor_name }
| cursor_variable_name
}
]
}
]
[OPTION (<query_hint> [,…n])]

<table_source> ::=
 table_name [ [AS] table_alias ] [ WITH ( <table_hint> [,…n]) ]
| view_name [ [AS] table_alias ]
| rowset_function [ [AS] table_alias ]
| derived_table [AS] table_alias [ (column_alias [,…n] ) ]
| <joined_table>

<joined_table> ::=
<table_source> <join_type> <table_source> ON <search_condition>
| <table_source> CROSS JOIN <table_source>
| <joined_table>

<join_type> ::=
[ INNER | { { LEFT | RIGHT | FULL } [OUTER] } ]
[ <join_hint> ]
JOIN

<table_hint_limited> ::=
{ INDEX(index_val [,…n])
| FASTFIRSTROW
| HOLDLOCK
| PAGLOCK
| READCOMMITTED
| REPEATABLEREAD
| ROWLOCK
| SERIALIZABLE
| TABLOCK
| TABLOCKX
}

<table_hint> ::=
{ INDEX(index_val [,…n])
| FASTFIRSTROW
| HOLDLOCK
| NOLOCK
| PAGLOCK
| READCOMMITTED
| READPAST
| READUNCOMMITTED
| REPEATABLEREAD
| ROWLOCK
| SERIALIZABLE
| TABLOCK
| TABLOCKX
| UPDLOCK
}

<query_hint> ::=
{ { HASH | ORDER } GROUP
| { CONCAT | HASH | MERGE } UNION
| FAST number_rows
| FORCE ORDER
| ROBUST PLAN
| KEEP PLAN
}

Arguments
FROM
Is an optional keyword that can be used between the DELETE keyword and the target table_name, view_name, or rowset_function_limited.
table_name [ [AS] table_alias ]
Is the name and optional alias of the table from which the rows are to be removed.
WITH (<table_hint_limited> […n])
Specifies one or more table hints that are allowed for a target table. The WITH keyword and the parentheses are required. READPAST, NOLOCK, READUNCOMMITTED, and UPDLOCK are not allowed. For information about table hints, see FROM.
view_name [ [AS] table_alias ]
Is the name and optional alias of a view. The view referenced by view_name must be updatable and reference exactly one base table in the FROM clause of the view. For more information on updatable views, see CREATE VIEW.

Note If the table or view exists in another database or has an owner other than the current user, use a four-part qualified name in the format server_name.database.[owner].object_name. For more information, see Transact-SQL Syntax Conventions.

rowset_function_limited
Is either the OPENQUERY or OPENROWSET function, subject to provider capabilities. For more information about the rowset functions, see OPENQUERY and OPENROWSET.
FROM <table_source>
Specifies an additional FROM clause. This Transact-SQL extension to DELETE allows you to specify data from <table_sources> and delete corresponding rows from the table in the first FROM clause.

This extension, specifying a join, can be used instead of a subquery in the WHERE clause to identify rows to be removed. For more information, see FROM.

table_name [[AS] table_alias ]
Is the name of the table to provide criteria values for the delete operation.
view_name [[AS] table_alias ]
Is the name of the view to provide criteria values for the delete operation.
WITH (<table_hint>
Specifies one or more table hints. For more information about table hints, see FROM.
rowset_function [ [AS] table_alias ]
Is the name of a rowset function and an optional alias. For more information about a list of rowset functions, see Rowset Functions.
derived_table [AS] table_alias
Is a subquery that retrieves rows from the database. derived_table is used as input to the outer query.
column_alias
Is an optional alias to replace a column name in the result set. Include one column alias for each column in the select list, and enclose the entire list of column aliases in parentheses.
<joined_table>
Is a result set that is the product of two or more tables for example:

FROM tab1 LEFT OUTER JOIN tab1.c3 = tab2.c3
    RIGHT OUTER JOIN tab3 LEFT OUTER JOIN tab4
        ON tab3.c1
    ON tab2.c3 = tab4.c3

For multiple CROSS joins, use parentheses to change the natural order of the joins.

<join_type>
Specifies the type of join operation.
INNER
Specifies all matching pairs of rows are returned. Discards unmatched rows from both tables. This is the default if no join type is specified.
LEFT [OUTER]
Specifies that all rows from the left table not meeting the specified condition are included in the result set, and output columns from the right table are set to NULL in addition to all rows returned by the inner join.
RIGHT [OUTER]
Specifies that all rows from the right table not meeting the specified condition are included in the result set, and output columns from the left table are set to NULL in addition to all rows returned by the inner join.
FULL [OUTER]
If a row from either the left or right table does not match the selection criteria, specifies the row be included in the result set, and output columns that correspond to the other table be set to NULL. This is in addition to all rows usually returned by the inner join.
JOIN
Is a keyword to indicate that an SQL-92 style join be used in the delete operation.
ON <search_condition>
Specifies the condition on which the join is based. The condition can specify any predicate, although columns and comparison operators are often used, for example:

FROM Suppliers JOIN Products
    ON (Suppliers.SupplierID = Products.SupplierID)

When the condition specifies columns, they need not have the same name or same data type; however, if the data types are not identical, they must be either compatible or types that Microsoft® SQL Server™ can implicitly convert. If the data types cannot be implicitly converted, the condition must explicitly convert the data type using the CAST function.

For more information about search conditions and predicates, see Search Condition.

CROSS JOIN
Specifies the cross-product of two tables. Returns the same rows as if no WHERE clause was specified in an old-style, non-SQL-92-style join.
WHERE
Specifies the conditions used to limit the number of rows that are deleted. If a WHERE clause is not supplied, DELETE removes all the rows from the table. There are two forms of delete operations based on what is specified in the WHERE clause:
  • Searched deletes specify a search condition to qualify the rows to delete.
  • Positioned deletes use the CURRENT OF clause to specify a cursor. The delete operation occurs at the current position of the cursor. This can be more accurate than a searched DELETE that uses a WHERE search_condition clause to qualify the rows to be deleted. A searched DELETE deletes multiple rows if the search condition does not uniquely identify a single row.
<search_condition>
Specifies the restricting conditions for the rows to be deleted. There is no limit to the number of predicates that can be included in a search condition. For more information, see Search Condition.
CURRENT OF
Specifies that the DELETE is done at the current position of the specified cursor.
GLOBAL
Specifies that cursor_name refers to a global cursor.
cursor_name
Is the name of the open cursor from which the fetch is made. If both a global and a local cursor with the name cursor_name exist, this argument refers to the global cursor if GLOBAL is specified, and to the local cursor otherwise. The cursor must allow updates.
cursor_variable_name
Is the name of a cursor variable. The cursor variable must reference a cursor that allows updates.
OPTION (<query_hint> [,…n] )
Are keywords indicating that optimizer hints are used to customize SQL Server’s processing of the statement.
{HASH | ORDER} GROUP
Specifies that the aggregations specified in the GROUP BY or COMPUTE clause of the query should use hashing or ordering.
{MERGE | HASH | CONCAT} UNION
Specifies that all UNION operations should be performed by merging, hashing, or concatenating UNION sets. If more than one UNION hint is specified, the query optimizer selects the least expensive strategy from those hints specified.

Note If a <joint_hint> is also specified for any particular pair of joined tables in the FROM clause, it takes precedence over any <join_hint> specified in the OPTION clause.

FAST number_rows
Specifies that the query is optimized for fast retrieval of the first number_rows (a nonnegative integer). After the first number_rows are returned, the query continues execution and produces its full result set.
FORCE ORDER
Specifies that the join order indicated by the query syntax is preserved during query optimization.
ROBUST PLAN
Forces the query optimizer to attempt a plan that works for the maximum potential row size at the expense of performance. If such a plan is not possible, the query optimizer returns an error rather than deferring error detection to query execution. Rows may contain variable-length columns; SQL Server allows rows to be defined that have a maximum potential size beyond the ability of SQL Server to process them. Usually, despite the maximum potential size, an application stores rows that have actual sizes within the limits that SQL Server can process. If SQL Server encounters a row that is too long, an execution error is returned.
KEEP PLAN
Forces the query optimizer to relax the estimated recompile threshold for a query. The estimated recompile threshold is the point at which a query is automatically recompiled when the estimated number of indexed column changes (update, delete or insert) have been made to a table. Specifying KEEP PLAN ensures that a query will not be recompiled as frequently when there are multiple updates to a table.
Remarks

DELETE cannot remove data from tables on the nullable side of an outer join.

The DELETE statement may fail if it violates a trigger or attempts to remove a row referenced by data in another table with a FOREIGN KEY constraint. If the DELETE removes multiple rows, and any one of the removed rows violates a trigger or constraint, the statement is canceled, an error is returned, and no rows are removed.

When a DELETE statement encounters an arithmetic error (overflow, divide by zero, or a domain error) occurring during expression evaluation, SQL Server handles these errors as if SET ARITHABORT is ON. The remainder of the batch is canceled, and an error message is returned.

If you want to delete all the rows in a table, TRUNCATE TABLE is faster than DELETE. DELETE physically removes rows one at a time and records each deleted row in the transaction log. TRUNCATE TABLE deallocates all pages associated with the table. For this reason, TRUNCATE TABLE is faster and requires less transaction log space than DELETE. TRUNCATE TABLE is functionally equivalent to DELETE with no WHERE clause, but TRUNCATE TABLE cannot be used with tables referenced by foreign keys. Both DELETE and TRUNCATE TABLE make the space occupied by the deleted rows available for the storage of new data.

Permissions

DELETE permissions default to members of the sysadmin fixed server role, members of the db_owner fixed database role, and the table owner, who can transfer permissions to other users. SELECT permissions are also required if the statement contains a WHERE clause.

Examples
A. Use DELETE with no parameters

This example deletes all rows from the authors table.

USE pubs

DELETE authors

B. Use DELETE on a set of rows

Because au_lname may not be unique, this example deletes all rows in which au_lname is McBadden.

USE pubs

DELETE FROM authors

WHERE au_lname = 'McBadden'

C. Use DELETE on the current row of a cursor

This example shows a delete made against a cursor named complex_join_cursor. It affects only the single row currently fetched from the cursor.

USE pubs

DELETE FROM authors

WHERE CURRENT OF complex_join_cursor

D.Use DELETE based on a subquery or use the Transact-SQL extension

This example shows the Transact-SQL extension used to delete records from a base table that is based on a join or correlated subquery. The first DELETE shows the SQL-92-compatible subquery solution, and the second DELETE shows the Transact-SQL extension. Both queries remove rows from the titleauthors table based on the titles stored in the titles table.

/* SQL-92-Standard subquery */

USE pubs

DELETE FROM titleauthor

WHERE title_id IN

    (SELECT title_id

    FROM titles

    WHERE title LIKE '%computers%')

/* Transact-SQL extension */

USE pubs

DELETE titleauthor

FROM titleauthor INNER JOIN titles

    ON titleauthor.title_id = titles.title_id

WHERE titles.title LIKE '%computers%'

E. Use DELETE and a SELECT with the TOP Clause

Because a SELECT statement can be specified in a DELETE statement, the TOP clause can also be used within the SELECT statement. For example, this example deletes the top 10 authors from the authors table.

DELETE authors

FROM (SELECT TOP 10 * FROM authors) AS t1

WHERE authors.au_id = t1.au_id

See Also
CREATE TABLE | SELECT
CREATE TRIGGER | TRUNCATE TABLE
DROP TABLE | UPDATE
INSERT |


DENY

Creates an entry in the security system that denies a permission from a security account in the current database and prevents the security account from inheriting the permission through its group or role memberships.

Syntax

Statement permissions:

DENY{ALL | statement[,…n]}
TO security_account[,…n]

Object permissions:

DENY
{ALL [PRIVILEGES] | permission[,…n]}
{
[(column[,…n])] ON {table | view}
| ON {table | view}[(column[,…n])]
| ON {stored_procedure | extended_procedure}
}
TO security_account[,…n]
[CASCADE]

Arguments
ALL
Specifies that all applicable permissions are being denied. For statement permissions, ALL can be used only by members of the sysadmin role. For object permissions, ALL can be used by members of the sysadmin and db_owner roles, and database object owners.
statement
Is the statement for which permission is being denied. The statement list can include:
  • CREATE DATABASE
  • CREATE DEFAULT
  • CREATE PROCEDURE
  • CREATE RULE
  • CREATE TABLE
  • CREATE VIEW
  • BACKUP DATABASE
  • BACKUP LOG
n
Is a placeholder indicating that the item can be repeated in a comma-separated list.
TO
Specifies the security account list.
security_account
Is the name of the security account in the current database affected by the denied permission. The security account can be a:
  • Microsoft® SQL Server™ user.
  • SQL Server role.
  • Microsoft Windows NT® user.
  • Windows NT group.

When a permission is denied from a SQL Server user or Windows NT user account, the specified security_account is the only account affected by the permission. If a permission is denied from a SQL Server role or a Windows NT group, the permission affects all users in the current database who are members of the group or role, regardless of the permissions that have been granted to the members of the group or role. If there are permission conflicts between a group or role and its members, the most restrictive permission (DENY) takes precedence.

Two special security accounts can be used with DENY. Permissions denied from the public role are applied to all users in the database. Permissions denied from the guest user are used by all users who do not have a user account in the database.

When denying permissions to a Windows NT local or global group, specify the domain or computer name the group is defined on, followed by a backslash, then the group name. However, to deny permissions to a Windows NT built-in local group, specify BUILTIN instead of the domain or computer name.

PRIVILEGES
Is an optional keyword that can be included for SQL-92 compliance.
permission
Is an object permission that is being denied. When permissions are denied on a table or a view, the permission list can include one or more of these statements: SELECT, INSERT, DELETE, or UPDATE.

Object permissions denied on a table can also include REFERENCES, and object permissions denied on a stored procedure or extended stored procedure can include EXECUTE. When permissions are denied on columns, the permissions list can include SELECT or UPDATE.

column
Is the name of the column in the current database for which permissions are being denied.
table
Is the name of the table in the current database for which permissions are being denied.
view
Is the name of the view in the current database for which permissions are being denied.
stored_procedure
Is the name of the stored procedure in the current database for which permissions are being denied.
extended_procedure
Is the name of an extended stored procedure for which permissions are being denied.
CASCADE
Specifies that permissions are being denied from security_account as well as any other security accounts granted permissions by security_account. Use CASCADE when denying a grantable permission. If CASCADE is not specified and the specified user is granted WITH GRANT OPTION permission, an error is returned.
Remarks

If the DENY statement is used to prevent a user from gaining a permission and the user is later added to a group or role with the permission granted, the user does not gain access to the permission.

If a user activates an application role, the effect of DENY is null for any objects the user accesses using the application role. Although a user may be denied access to a specific object in the current database, if the application role has access to the object, the user also has access while the application role is activated.

Use the REVOKE statement to remove a denied permission from a user account. The security account does not gain access to the permission unless the permission has been granted to a group or role in which the user is a member. Use the GRANT statement to both remove a denied permission, and explicitly apply the permission to the security account.

Note DENY is a new keyword in SQL Server version 6.x compatibility mode. DENY is needed to specifically deny a permission from a user account, because in SQL Server version 7.0 REVOKE removes only previously granted or denied permissions. Existing SQL Server 6.x scripts that use REVOKE may have to be changed to use DENY to maintain behavior.

Permissions

DENY permissions default to members of the sysadmin, db_owner, or db_securityadmin roles, and database object owners.

Examples
A. Deny statement permissions

This example denies multiple statement permissions to multiple users. Users cannot use the CREATE DATABASE or CREATE TABLE statements unless they are explicitly granted the permission.

DENY CREATE DATABASE, CREATE TABLE

TO Mary, John, [Corporate\BobJ]

B. Deny object permissions within the permission hierarchy

This example shows the preferred ordering of permissions. First, SELECT permissions are granted to the public role. After this, specific permissions are denied for users Mary, John, and Tom. These users then have no permissions to the authors table.

USE pubs

GO

GRANT SELECT

ON authors

TO public

GO

DENY SELECT, INSERT, UPDATE, DELETE

ON authors

TO Mary, John, Tom

C. Deny permissions to a SQL Server role

This example denies CREATE TABLE permissions to all members of the Accounting role. Even if existing users of Accounting have been explicitly granted CREATE TABLE permission, the DENY overrides that permission.

DENY CREATE TABLE TO Accounting

See Also
GRANT | REVOKE
sp_helprotect |


DIFFERENCE

Returns the difference between the SOUNDEX values of two character expressions as an integer.

Syntax

DIFFERENCE(character_expression, character_expression)

Arguments
character_expression
Is an expression of type char or varchar.
Return Types

int

Remarks

The integer returned is the number of characters in the SOUNDEX values that are the same. The return value ranges from 0 through 4, with 4 indicating the SOUNDEX values are identical.

Examples

In the first part of this example, the SOUNDEX values of two very similar strings are compared, and DIFFERENCE returns a value of 4. In the second part of this example, the SOUNDEX values for two very different strings are compared, and DIFFERENCE returns a value of 0.

USE pubs

GO

-- Returns a DIFFERENCE value of 4, the least possible difference.

SELECT SOUNDEX('Green'),

  SOUNDEX('Greene'), DIFFERENCE('Green','Greene')

GO

-- Returns a DIFFERENCE value of 0, the highest possible difference.

SELECT SOUNDEX('Blotchet-Halls'),

  SOUNDEX('Greene'), DIFFERENCE('Blotchet-Halls', 'Greene')

GO

Here is the result set:

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

G650  G650  4

(1 row(s) affected)

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

B432  G650  0

(1 row(s) affected)

See Also
SOUNDEX String Functions


DROP DATABASE

Removes one or more databases from Microsoft® SQL Server™. Removing a database deletes the database and the disk files used by the database.

Syntax

DROP DATABASE database_name [,…n]

Arguments
database_name
Specifies the name of the database to be removed. Execute sp_helpdb from the master database to see a list of databases.
Remarks

The database context of the connection must be in the master database to use DROP DATABASE.

In SQL Server version 7.0, DROP DATABASE removes damaged databases that have been marked suspect. DROP DATABASE removes the specified database unless it has been marked OFFLINE.

A database that has been dropped can be re-created only by restoring a backup. You cannot drop a database currently in use (open for reading or writing by any user). Whenever a database is dropped, the master database should be backed up .

Permissions

DROP DATABASE permission defaults to the database owner and members of the sysadmin fixed server role, and is not transferable.

Examples
A. Drop a single database

This example removes all references for the publishing database from the system tables.

DROP DATABASE publishing

B. Drop multiple databases

This example removes all references for each of the listed databases from the system tables.

DROP DATABASE pubs, newpubs

See Also
ALTER DATABASE | sp_renamedb
CREATE DATABASE | USE
sp_helpdb | sp_dropdevice


DROP DEFAULT

Removes one or more user-defined defaults from the current database.

The DROP DEFAULT statement does not apply to DEFAULT constraints. For information about dropping DEFAULT constraints (created by using the DEFAULT option of either the CREATE TABLE or ALTER TABLE statements), see ALTER TABLE.

Syntax

DROP DEFAULT {default} [,…n]

Arguments
default
Is the name of an existing default. To see a list of defaults that exist, execute sp_help. Defaults must conform to the rules for identifiers. Specifying the default owner name is optional.
n
Is a placeholder indicating that multiple defaults can be specified.
Remarks

Before dropping a default, unbind the default by executing sp_unbindefault (if the default is currently bound to a column or a user-defined data type).

After a default is dropped from a column that allows null values, NULL is inserted in that position when rows are added and no value is explicitly supplied. After a default is dropped from a NOT NULL column, an error message is returned when rows are added and no value is explicitly supplied. These rows are added later as part of the normal INSERT statement behavior.

Permissions

DROP DEFAULT permission defaults to the owner of the default, and is not transferable. However, members of the db_owner fixed database role or members of the sysadmin fixed database role can drop any default object by specifying the owner in DROP DEFAULT.

Examples
A. Drop a default

If a default has not been bound to a column or to a user-defined data type, it can simply be dropped using DROP DEFAULT. This example removes the user-created default named datedflt.

USE pubs

IF EXISTS (SELECT name FROM sysobjects

            WHERE name = 'datedflt'

                AND type = 'D')

    DROP DEFAULT datedflt

GO

B. Drop a default that has been bound to a column

This example unbinds the default associated with the phone column of the authors table and then drops the default named phonedflt.

USE pubs

IF EXISTS (SELECT name FROM sysobjects

            WHERE name = 'phonedflt'

                AND type = 'D')

    BEGIN

        EXEC sp_unbindefault 'authors.phone'

        DROP DEFAULT phonedflt

    END

GO

See Also
ALTER TABLE | sp_helptext
CREATE DEFAULT | sp_unbindefault
sp_help |


DROP INDEX

Removes one or more indexes from the current database.

The DROP INDEX statement does not apply to indexes created by defining PRIMARY KEY or UNIQUE constraints (created by using the PRIMARY KEY or UNIQUE options of either the CREATE TABLE or ALTER TABLE statements, respectively). For more information about PRIMARY or UNIQUE KEY constraints, see CREATE TABLE or ALTER TABLE.

Syntax

DROP INDEX 'table.index' [,…n]

Arguments
table
Is the table in which the indexed column is located. To see a list of indexes that exist on a table, use sp_helpindex and specify the table name. Table names must conform to the rules for identifiers. Specifying the table owner name is optional.
index
Is the name of the index to be dropped. Index names must conform to the rules for identifiers.
n
Is a placeholder indicating that multiple indexes can be specified.
Remarks

After DROP INDEX is executed, all the space previously occupied by the index is regained. This space can then be used for any database object.

DROP INDEX cannot be specified on an index on a system table.

To drop the indexes created to implement PRIMARY KEY or UNIQUE constraints, the constraint must be dropped. For more information about dropping constraints, see ALTER TABLE.

Nonclustered indexes have different pointers to data rows depending on whether or not a clustered index is defined for the table. If there is a clustered index the leaf rows of the nonclustered indexes use the clustered index keys to point to the data rows. If the table is a heap, the leaf rows of nonclustered indexes use row pointers. If you drop a clustered index on a table with nonclustered indexes, all the nonclustered indexes are rebuilt to replace the clustered index keys with row pointers.

Sometimes indexes are dropped and re-created to reorganize the index, for example to apply a new fillfactor or to reorganize data after a bulk load. It is more efficient to use CREATE INDEX and the WITH DROP_EXISTING clause for this, especially for clustered indexes. Dropping a clustered index causes all the nonclustered indexes to be rebuilt. If the clustered index is then re-created, the nonclustered indexes are rebuilt once again to replace the row pointers with clustered index keys. The WITH DROP_EXISTING clause of CREATE INDEX has optimizations to prevent this overhead of rebuilding the nonclustered indexes twice. DBCC DBREINDEX can also be used and has the advantage that it does not require that the structure of the index be known.

Permissions

DROP INDEX permissions default to the table owner, and is not transferable. However, members of the db_owner fixed database role or sysadmin fixed server role can drop any object by specifying the owner in DROP INDEX.

Examples

This example removes the index named au_id_ind in the authors table.

USE pubs

IF EXISTS (SELECT name FROM sysindexes

            WHERE name = 'au_id_ind')

    DROP INDEX authors.au_id_ind

GO

See Also
ALTER TABLE | DBCC DBREINDEX
CREATE INDEX | sp_helpindex
CREATE TABLE | sp_spaceused


DROP PROCEDURE

Removes one or more stored procedures or procedure groups from the current database.

Syntax

DROP PROCEDURE {procedure} [,…n]

Arguments
procedure
Is name of the stored procedure or stored procedure group to be removed. Procedure names must conform to the rules for identifiers Specifying the procedure owner name is optional, and a server name or database name cannot be specified.
n
Is a placeholder indicating that multiple procedures can be specified.
Remarks

To see a list of procedure names, use sp_help. To display the procedure definition (which is stored in the syscomments system table), use sp_helptext. When a stored procedure is dropped, information about the procedure is removed from the sysobjects and syscomments system tables.

Individual procedures in the group cannot be dropped; the entire procedure group is dropped.

User-defined system procedures (prefixed with sp_) are dropped from the master database whether or not it is the current database. If the system procedure is not found in the current database, Microsoft® SQL Server™ tries to drop it from the master database.

Permissions

DROP PROCEDURE permissions defaults to the procedure owner and is not transferable. However, members of the db_owner and sysadmin fixed database roles can drop any object by specifying the owner in DROP PROCEDURE.

Examples

This example removes the byroyalty stored procedure (in the current database) .

DROP PROCEDURE byroyalty

GO

See Also
ALTER PROCEDURE | USE
CREATE PROCEDURE | sp_helptext
sp_depends | sp_rename
sysobjects | syscomments


DROP RULE

Removes one or more user-defined rules from the current database.

Syntax

DROP RULE {rule} [,…n]

Arguments
rule
Is the rule to be removed. Rule names must conform to the rules for identifiers. Specifying the rule owner name is optional.
n
Is a placeholder indicating that multiple rules can be specified.
Remarks

To drop a rule, first unbind it if the rule is currently bound to a column or to a user-defined data type. Use sp_unbindrule to unbind the rule. If the rule is bound when attempting to drop it, an error message is displayed and the DROP RULE statement is canceled.

After a rule is dropped, new data entered into the columns previously governed by the rule is entered without the rule’s constraints. Existing data is not affected in any way.

The DROP RULE statement does not apply to CHECK constraints. For more information about dropping CHECK constraints, see ALTER TABLE.

Permissions

DROP RULE permission defaults to the rule owner and is not transferable. However, members of the db_owner fixed database role or sysadmin fixed server role can drop any object by specifying the owner in DROP RULE.

Examples

This example unbinds and then drops the rule named pub_id_rule.

USE pubs

IF EXISTS (SELECT name FROM sysobjects

            WHERE name = 'pub_id_rule'

                AND type = 'R')

    BEGIN

        EXEC sp_unbindrule 'publishers.pub_id'

        DROP RULE pub_id_rule

    END

GO

See Also
ALTER TABLE | sp_help
CREATE RULE | sp_helptext
USE | sp_unbindrule
sp_bindrule |


DROP STATISTICS

Drops statistics for multiple collections within the specified tables (in the current database).

Syntax

DROP STATISTICS table.statistics_name [,…n]

Arguments
table
Is the name of the target table for which statistics should be dropped. Table names must conform to the rules for identifiers. Specifying the table owner name is optional.
statistics_name
Is the name of the statistics group to drop. Statistics names must conform to the rules for identifiers.
n
Is a placeholder indicating that more than one statistics_name group (collection) can be specified.
Remarks

Be careful when dropping statistics because dropping statistics may affect the plan chosen by the optimizer.

For information about displaying statistics, see DBCC SHOW_STATISTICS. For information about updating statistics, see UPDATE STATISTICS and the auto update statistics option of sp_dboption. For information about creating statistics, see CREATE STATISTICS, CREATE INDEX, and the auto create statistics option of sp_dboption.

Permissions

DROP STATISTICS permission defaults to the table owner, and is not transferable. However, members of the db_owner fixed database role or sysadmin fixed server role can drop any object by specifying the owner in DROP STATISTICS.

Examples

This example drops the anames statistics group (collection) of the authors table and the tnames statistics (collection) of the titles table.

-- Create the statistics groups.

CREATE STATISTICS anames

    ON authors (au_lname, au_fname)

    WITH SAMPLE 50 PERCENT
GO

CREATE STATISTICS tnames

    ON titles (title_id)

    WITH FULLSCAN

GO

DROP STATISTICS authors.anames, titles.tnames

GO

See Also
CREATE INDEX | sp_createstats
CREATE STATISTICS | sp_dboption
DBCC SHOW_STATISTICS | UPDATE STATISTICS
sp_autostats | USE


DROP TABLE

Removes a table definition and all data, indexes, triggers, constraints, and permission specifications for that table. Any view or stored procedure that references the dropped table must be explicitly dropped by using the DROP VIEW or DROP PROCEDURE statement.

Syntax

DROP TABLE table_name

Arguments
table_name
Is the name of the table to be removed.
Remarks

DROP TABLE cannot be used to drop a table being referenced by a FOREIGN KEY constraint. The referencing FOREIGN KEY constraint or the referencing table must first be dropped.

A table owner can drop a table in any database. When a table is dropped, rules or defaults on it lose their binding, and any constraints or triggers associated with it are automatically dropped. If you re-create a table, you must rebind the appropriate rules and defaults, re-create any triggers, and add all necessary constraints.

You cannot use the DROP TABLE statement on system tables.

If you delete all rows in a table (DELETE tablename) or use the TRUNCATE TABLE statement, the table exists until it is dropped.

Permissions

DROP TABLE permission defaults to the table owner, and is not transferable. However, members of the sysadmin fixed server role or the db_owner and ddl_admin fixed database roles can drop any object by specifying the owner in the DROP TABLE statement.

Examples
A. Drop a table in the current database

This example removes the titles1 table and its data and indexes from the current database.

DROP TABLE titles1

B. Drop a table in another database

This example drops the authors2 table in the pubs database. It can be executed from any database.

DROP TABLE pubs.dbo.authors2

See Also
ALTER TABLE | sp_help
CREATE TABLE | sp_spaceused
DELETE | TRUNCATE TABLE
sp_depends |


DROP TRIGGER

Removes one or more triggers from the current database.

Syntax

DROP TRIGGER {trigger} [,…n]

Arguments
trigger
Is the name of the trigger(s) to remove. Trigger names must conform to the rules for identifiers. Specifying the trigger owner name is optional. To see a list of currently created triggers, use sp_helptrigger.
n
Is a placeholder indicating that multiple triggers can be specified.
Remarks

You can remove a trigger by dropping it or by dropping the trigger table. When a table is dropped, all triggers associated with it are also dropped. When a trigger is dropped, information about the trigger is removed from the sysobjects and syscomments system tables.

Use DROP TRIGGER and CREATE TRIGGER to rename a trigger. Use ALTER TRIGGER to change the definition of a trigger.

For more information about determining dependencies for a specific trigger, see sp_depends.

For more information about viewing the text of the trigger, see sp_helptext.

For more information about viewing a list of existing triggers, see sp_helptrigger.

Permissions

DROP TRIGGER permissions default to the trigger table owner, and is not transferable. However, members of the db_owner fixed database role or sysadmin fixed server role can drop any object by explicitly specifying the owner in the DROP TRIGGER statement.

Examples

This example drops the employee_insupd trigger.

USE pubs

IF EXISTS (SELECT name FROM sysobjects

        WHERE name = 'employee_insupd' AND type = 'TR')

    DROP TRIGGER employee_insupd

GO

See Also
ALTER TRIGGER | sp_helptext
CREATE TRIGGER | sp_helptrigger
sp_depends | syscomments
sp_help | sysobjects


DROP VIEW

Removes one or more views from the current database. Any view on the dropped table (dropped by using the DROP TABLE statement) must be explicitly dropped by using DROP VIEW.

Syntax

DROP VIEW {view} [,…n]

Arguments
view
Is the name of the view(s) to be removed. View names must conform to the rules for identifiers. Specifying the view owner name is optional. To see a list of currently created views, use sp_help.
n
Is a placeholder indicating that multiple views can be specified.
Remarks

When you drop a view, the definition of the view and other information about the view is deleted from the sysobjects, syscolumns, syscomments, sysdepends, and sysprotects system tables. All permissions for the view are also deleted.

When querying through a view, Microsoft® SQL Server™ checks to make sure that all the database objects referenced anywhere in the statement exist, that they are valid in the context of the statement, and that data modification statements do not violate any data integrity rules. A check that fails returns an error message. A successful check translates the action into an action against the underlying table(s).

If the underlying table(s) or view(s) have changed since the view was originally created, it may be useful to drop and re-create the view.

For more information about determining dependencies for a specific view, see sp_depends.

For more information about viewing the text of the view, see sp_helptext.

Permissions

DROP VIEW permission defaults to the view owner, and is not transferable. However, members of the db_owner fixed database role or sysadmin fixed server role can drop any object by explicitly specifying the owner in DROP VIEW.

Examples

This example removes the view titles_view .

USE pubs

IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS

            WHERE TABLE_NAME = 'titles_view')

    DROP VIEW titles_view

GO

See Also
ALTER VIEW | sysdepends
CREATE VIEW | sysobjects
syscolumns | USE
syscomments | sysprotects


DUMP

Makes a backup copy of a database (DUMP DATABASE) or makes a copy of the transaction log (DUMP TRANSACTION) in a form that can be read into Microsoft® SQL Server™ using the BACKUP or LOAD statements.

Important The DUMP statement is included in SQL Server version 7.0 for backward compatibility. It is recommended that the BACKUP statement be used instead of the DUMP statement. In a future version of SQL Server, DUMP will not be supported.

See Also
BACKUP | sp_helpdb
LOAD | sp_helpdevice
sp_addumpdevice | sp_spaceused
sp_dropdevice |


ELSE (IF…ELSE)

Imposes conditions on the execution of a Transact-SQL statement. The Transact-SQL statement (sql_statement) following the Boolean_expression is executed if the Boolean_expression evaluates to TRUE. The optional ELSE keyword is an alternate Transact-SQL statement that is executed when Boolean_expression evaluates to FALSE or NULL.

Syntax

IF Boolean_expression{sql_statement | statement_block}
[
ELSE
{sql_statement | statement_block}]

Arguments
Boolean_expression
Is an expression that returns TRUE or FALSE. If the Boolean expression contains a SELECT statement, the SELECT statement must be enclosed in parentheses.
{sql_statement | statement_block}
Is any valid Transact-SQL statement or statement grouping as defined with a statement block. To define a statement block (batch), use the control-of-flow language keywords BEGIN and END. Although all Transact-SQL statements are valid within a BEGIN…END block, certain Transact-SQL statements should not be grouped together within the same batch (statement block). For more information, see Batches and the specific statements being used.
Result Types

Boolean

Examples

This example produces a list of traditional cookbooks priced between $10 and $20 when one or more books meet these conditions. Otherwise, SQL Server prints a message that no books meet the condition and a list of traditional cookbooks that costs less than $10 is produced.

USE pubs

GO

DECLARE @msg varchar(255)

IF (SELECT COUNT(price)

    FROM titles

    WHERE title_id LIKE 'TC%' AND price BETWEEN 10 AND 20) > 0

    BEGIN

     SET NOCOUNT ON

     SET @msg = 'There are several books that are a good value between $10 and $20. These books are: '

         PRINT @msg

      SELECT title

     FROM titles

     WHERE title_id LIKE 'TC%' AND price BETWEEN 10 AND 20

    END

ELSE

    BEGIN

     SET NOCOUNT ON

     SET @msg = 'There are no books between $10 and $20. You might consider the following books that are under $10.'

         PRINT @msg

     SELECT title

     FROM titles

     WHERE title_id LIKE 'TC%' AND price < 10

    END

Here is the result set:

There are several books that are a good value between $10 and $20. These books are:

title

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

Fifty Years in Buckingham Palace Kitchens

Sushi, Anyone?

(2 row(s) affected)

See Also
ALTER TRIGGER | CREATE TRIGGER
Control-of-Flow Language | IF…ELSE


END (BEGIN…END)

Encloses a series of Transact-SQL statements that will execute as a group. BEGIN...END blocks can be nested.

Syntax

BEGIN
{sql_statement | statement_block}
END

Arguments
{sql_statement | statement_block}
Is any valid Transact-SQL statement or statement grouping as defined with a statement block. To define a statement block (batch), use the control-of-flow language keywords BEGIN and END. Although all Transact-SQL statements are valid within a BEGIN...END block, certain Transact-SQL statements should not be grouped together within the same batch (statement block). For more information, see Batches and the specific statements being used.
Result Types

Boolean

Examples

This example produces a list of business books that are priced less than $20 when one or more books meet these conditions. Otherwise, SQL Server prints a message that no books meet the conditions and a list of all books that cost less than $20 is produced.

SET NOCOUNT OFF

GO

USE pubs

GO

SET NOCOUNT ON

GO

DECLARE @msg varchar(255)

IF (SELECT COUNT(price)

    FROM titles

    WHERE title_id LIKE 'BU%' AND price < 20) > 0

    BEGIN

     SET @msg = 'There are several books that are a good value at under $20. These books are: '

         PRINT @msg

     SET NOCOUNT OFF

       SELECT title

       FROM titles

       WHERE price < 20

    END

ELSE

    BEGIN

     SET @msg = 'There are no books under $20. '

         PRINT @msg

     SELECT title

     FROM titles

     WHERE title_id

     LIKE 'BU%'

     AND

     PRICE <10

    END

Here is the result set:

There are several books that are a good value at under $20. These books are:

title

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

The Busy Executive's Database Guide

Cooking with Computers: Surreptitious Balance Sheets

You Can Combat Computer Stress!

Straight Talk About Computers

Silicon Valley Gastronomic Treats

The Gourmet Microwave

Is Anger the Enemy?

Life Without Fear

Prolonged Data Deprivation: Four Case Studies

Emotional Security: A New Algorithm

Fifty Years in Buckingham Palace Kitchens

Sushi, Anyone?

(12 row(s) affected)

See Also
ALTER TRIGGER | ELSE (IF…ELSE)
BEGIN…END | IF…ELSE
CREATE TRIGGER | WHILE
Control-of-Flow Language |


EXECUTE

Executes a system procedure, a user-defined stored procedure, or an extended stored procedure. Also supports the execution of a character string within a Transact-SQL batch.

Syntax

Execute a stored procedure:

[[EXEC[UTE]]
{
[@return_status =]
{procedure_name [;number] | @procedure_name_var
}
[[@parameter =] {value | @variable [OUTPUT] | [DEFAULT]]
[,…n]
[WITH RECOMPILE]

Execute a character string:

EXEC[UTE] ({@string_variable | [N]'tsql_string'} [+…n])

Arguments
@return_status
Is an optional integer variable that stores the return status of a stored procedure. This variable must be declared in the batch or stored procedure before it is used in an EXECUTE statement.
procedure_name
Is the fully qualified or non-fully qualified name of the stored procedure to call. Procedure names must conform to the rules for identifiers. A procedure that has been created in another database can be executed if the user executing the procedure owns the procedure or has the appropriate permission to execute it in that database. A procedure can be executed on another server running Microsoft® SQL Server™ if the user executing the procedure has the appropriate permission to use that server (remote access) and to execute the procedure in that database. If a server name is specified but no database name is specified, SQL Server looks for the procedure in the user’s default database.
;number
Is an optional integer used to group procedures of the same name so they can be dropped with a single DROP PROCEDURE statement. This parameter is not used for extended stored procedures.

Procedures used in the same application are often grouped this way. For example, the procedures used with the orders application may be named orderproc;1, orderproc;2, and so on. The statement DROP PROCEDURE orderproc drops the entire group. After procedures have been grouped, individual procedures within the group cannot be dropped. For example, the statement DROP PROCEDURE orderproc;2 is not allowed. For more information about procedure groups, see CREATE PROCEDURE.

@procedure_name_var
Is the name of a locally defined variable that represents a stored procedure name.
@parameter
Is the parameter for a procedure, as defined in the CREATE PROCEDURE statement. Parameter names must be preceded by the at sign (@). When used with the @parameter_name = value form, parameter names and constants do not have to be supplied in the order in which they are defined in the CREATE PROCEDURE statement. However, if the @parameter_name = value form is used for any parameter, it must be used for all subsequent parameters.

Parameters are nullable, by default. If a NULL parameter value is passed and that parameter is used in a CREATE or ALTER TABLE statement in which the column referenced does not allow NULLs (for example, inserting into a column that does not allow NULLs), SQL Server generates an error. To prevent passing a parameter value of NULL to a column that does not allow NULLs, either add programming logic to the procedure or use a default value (with the DEFAULT keyword of CREATE or ALTER TABLE) for the column.

value
Is the value of the parameter to the procedure. If parameter names are not specified, parameter values must be supplied in the order defined in the CREATE PROCEDURE statement.

If the value of a parameter is an object name, character string, or qualified by a database name or owner name, the entire name must be enclosed in single quotation marks. If the value of a parameter is a keyword, the keyword must be enclosed in double quotation marks.

If a default is defined in the CREATE PROCEDURE statement, a user can execute the procedure without specifying a parameter. The default must be a constant and can include the wildcard characters %, _, [ ], and [^] if the procedure uses the parameter name with the LIKE keyword.

The default can also be NULL. Usually, the procedure definition specifies the action that should be taken if a parameter value is NULL.

@variable
Is the variable that stores a parameter or a return parameter.
OUTPUT
Specifies that the stored procedure returns a parameter. The matching parameter in the stored procedure must also have been created with the keyword OUTPUT. Use this keyword when using cursor variables as parameters.

If OUTPUT parameters are being used and the intent is to use the return values in other statements within the calling batch or procedure, the value of the parameter must be passed as a variable (that is, @parameter = @variable). You cannot execute a procedure specifying OUTPUT for a parameter that is not defined as an OUTPUT parameter in the CREATE PROCEDURE statement. Constants cannot be passed to stored procedures using OUTPUT; the return parameter requires a variable name. The variable’s data type must be declared and a value assigned before executing the procedure. Return parameters can be of any data type except the text or image data types.

DEFAULT
Supplies the default value of the parameter as defined in the procedure. When the procedure expects a value for a parameter that does not have a defined default and either a parameter is missing or the DEFAULT keyword is specified, an error occurs.
n
Is a placeholder indicating that the preceding item(s) can be repeated multiple times. For example, EXECUTE can specify one or more @parameter, value, or @variable items.
WITH RECOMPILE
Forces a new plan to be compiled. Use this option if the parameter you are supplying is atypical or if the data has significantly changed. The changed plan is used in subsequent executions. This option is not used for extended stored procedures. It is recommended that you use this option sparingly because it is expensive.
@string_variable
Is the name of a local variable. @string_variable can be of char, varchar, nchar, or nvarchar data type with a maximum value of the server’s available memory. If the string is greater than 4,000 characters, concatenate multiple local variables to use for the EXECUTE string. For more information about system-supplied SQL Server data types, see Data Types.
[N]'tsql_string'
Is a constant string. tsql_string can be of nvarchar or varchar data type. If the N is included, the string is interpreted as nvarchar data type with a maximum value of the server’s available memory. If the string is greater than 4,000 characters, concatenate multiple local variables to use for the EXECUTE string.
Remarks

If the first three characters of the procedure name are sp_, SQL Server searches the master database for the procedure. If no qualified procedure name is provided, SQL Server searches for the procedure as if the owner name is dbo. To resolve the stored procedure name as a user-defined stored procedure with the same name as a system stored procedure, provide the fully qualified procedure name.

Parameters can be supplied either by using value or by using @parameter_name = value. A parameter is not part of a transaction, so if a parameter is changed in a transaction that is later rolled back, the parameter’s value does not revert to its previous value. The value returned to the caller is always the value at the time the procedure returns.

Nesting occurs when one stored procedure calls another. The nesting level is incremented when the called procedure begins execution, and it is decremented when the called procedure has finished. Exceeding the maximum of 32 nesting levels causes the entire calling procedure chain to fail. The current nesting level is stored in the @@NESTLEVEL function.

SQL Server currently uses return values 0 through -14 to indicate the execution status of stored procedures. Values from -15 through -99 are reserved for future use. For more information about a list of reserved return status values, see RETURN.

Because remote stored procedures and extended stored procedures are not within the scope of a transaction (unless issued within a BEGIN DISTRIBUTED TRANSACTION statement or when used with various configuration options), commands executed through calls to them cannot be rolled back. For more information, see System Stored Procedures and BEGIN DISTRIBUTED TRANSACTION.

When using cursor variables, if you execute a procedure that passes in a cursor variable with a cursor allocated to it an error occurs.

You do not have to specify the EXECUTE keyword when executing stored procedures if the statement is the first one in a batch.

Using EXECUTE with a Character String

Use the string concatenation operator (+) to create large strings for dynamic execution. Each string expression can be a mixture of Unicode and non-Unicode data types.

Although each [N] 'tsql_string' or @string_variable must be less than 8,000 bytes, the concatenation is performed logically in the SQL Server parser and never materializes in memory. For example, this statement never produces the expected 16,000 concatenated character string:

EXEC('name_of_8000_char_string' + 'another_name_of_8000_char_string')

Statement(s) inside the EXECUTE statement are not compiled until the EXECUTE statement is executed.

Changes in database context last only until the end of the EXECUTE statement. For example, after the EXEC in this example, the database context is master.

USE master EXEC ("USE pubs") SELECT * FROM authors

Permissions

EXECUTE permissions for a stored procedure default to the owner of the stored procedure, who can transfer them to other users. Permissions to use the statement(s) within the EXECUTE string are checked at the time EXECUTE is encountered, even if the EXECUTE statement is included within a stored procedure. When a stored procedure is run that executes a string, permissions are checked in the context of the user who executes the procedure, not in the context of the user who created the procedure. However, if a user owns two stored procedures in which the first procedure calls the second, then EXECUTE permission checking is not performed for the second stored procedure.

Examples
A. Use EXECUTE to pass a single parameter

The showind stored procedure expects one parameter (@tabname), a table name. The following examples execute the showind stored procedure with titles as its parameter value.

Note The showind stored procedure is shown for illustrative purposes only and does not exist in the pubs database.

EXEC showind titles

The variable can be explicitly named in the execution:

EXEC showind @tabname = titles

If this is the first statement in a batch or an isql script, EXEC is not required:

showind titles

Or

showind @tabname = titles

B. Use multiple parameters and an output parameter

This example executes the roy_check stored procedure, which passes three parameters. The third parameter, @pc, is an OUTPUT parameter. After the procedure has been executed, the return value is available in the variable @percent.

Note The roy_check stored procedure is shown for illustrative purposes only and does not exist in the pubs database.

DECLARE @percent int

EXECUTE roy_check 'BU1032', 1050, @pc = @percent OUTPUT

SET Percent = @percent

C. Use EXECUTE ‘tsql_string’ with a variable

This example shows how EXECUTE handles dynamically built strings containing variables. This example creates the tables_cursor cursor to hold a list of all user-defined tables (type = U).

Note This example is shown for illustrative purposes only.

DECLARE tables_cursor CURSOR

    FOR

    SELECT name FROM sysobjects WHERE type = 'U'

OPEN tables_cursor

DECLARE @tablename sysname

FETCH NEXT FROM tables_cursor INTO @tablename

WHILE (@@FETCH_STATUS <> -1)

BEGIN

    /* A @@FETCH_STATUS of -2 means that the row has been deleted.

    There is no need to test for this because this loop drops all

    user-defined tables.    */.

    EXEC ('DROP TABLE ' + @tablename)

    FETCH NEXT FROM tables_cursor INTO @tablename

END

PRINT 'All user-defined tables have been dropped from the database.'

DEALLOCATE tables_cursor

D. Use EXECUTE with a remote stored procedure

This example executes the checkcontract stored procedure on the remote server SQLSERVER1 and stores the return status indicating success or failure in @retstat.

DECLARE @retstat int

EXECUTE @retstat = SQLSERVER1.pubs.dbo.checkcontract '409-56-4008'

E. Use EXECUTE with an extended stored procedure

This example uses the xp_cmdshell extended stored procedure to list a directory of all files with an .exe file extension.

USE master

EXECUTE xp_cmdshell 'dir *.exe'

F. Use EXECUTE with a stored procedure variable

This example creates a variable that represents a stored procedure name.

DECLARE @proc_name varchar(30)

SET @proc_name = 'sp_who'

EXEC @proc_name

G. Use EXECUTE with DEFAULT

This example creates a stored procedure with default values for the first and third parameters. When the procedure is run, these defaults are inserted for the first and third parameters if no value is passed in the call or if the default is specified. Note the various ways the DEFAULT keyword can be used.

USE pubs

IF EXISTS (SELECT name FROM sysobjects

        WHERE name = 'proc_calculate_taxes' AND type = 'P')

    DROP PROCEDURE proc_calculate_taxes

GO

-- Create the stored procedure.

CREATE PROCEDURE proc_calculate_taxes (@p1 smallint = 42, @p2 char(1),

        @p3 varchar(8) = 'CAR')

     AS

    SELECT *

    FROM mytable

The proc_calculate_taxes stored procedure can be executed in many combinations:

EXECUTE proc_calculate_taxes @p2 = 'A'
EXECUTE proc_calculate_taxes 69, 'B'
EXECUTE proc_calculate_taxes 69, 'C', 'House'
EXECUTE proc_calculate_taxes @p1 = DEFAULT, @p2 = 'D'
EXECUTE proc_calculate_taxes DEFAULT, @p3 = 'Local', @p2 = 'E'
EXECUTE proc_calculate_taxes 69, 'F', @p3 = DEFAULT
EXECUTE proc_calculate_taxes 95, 'G', DEFAULT
EXECUTE proc_calculate_taxes DEFAULT, 'H', DEFAULT
EXECUTE proc_calculate_taxes DEFAULT, 'I', @p3 = DEFAULT

See Also
+ (String Concatenation) | Functions
[ ] (Wildcard - Character (s) to Match) | @@NESTLEVEL
ALTER PROCEDURE | sp_depends
DECLARE @local_variable | sp_helptext
DROP PROCEDURE |


EXISTS

Specifies a subquery to test for the existence of rows.

Syntax

EXISTS subquery

Arguments
subquery
Is a restricted SELECT statement (the COMPUTE clause, and the INTO keyword are not allowed). For more information, see the discussion of subqueries in SELECT.
Result Types

Boolean

Result Values

Returns TRUE if a subquery contains any rows.

Examples
A. Use NULL in subquery to still return a result set

This example returns a result set with NULL specified in the subquery and still evaluates to TRUE by using EXISTS.

USE Northwind

GO

SELECT CategoryName

FROM Categories

WHERE EXISTS (SELECT NULL)

ORDER BY CategoryName ASC

GO

B. Compare queries using EXISTS and IN

This example compares two queries that are semantically equivalent. The first query uses EXISTS and the second query uses IN. Note that both queries return the same information.

USE pubs

GO

SELECT DISTINCT pub_name

FROM publishers

WHERE EXISTS

    (SELECT *

    FROM titles

    WHERE pub_id = publishers.pub_id

    AND type = 'business')

GO

-- Or, using the IN clause:

USE pubs

GO

SELECT distinct pub_name

FROM publishers

WHERE pub_id IN

    (SELECT pub_id

    FROM titles

    WHERE type = 'business')

GO

Here is the result set for either query:

pub_name

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

Algodata Infosystems

New Moon Books

(2 row(s) affected)

C. Compare queries using EXISTS and = ANY

This example shows two queries to find authors who live in the same city as a publisher. The first query uses = ANY and the second uses EXISTS. Note that both queries return the same information.

USE pubs

GO

SELECT au_lname, au_fname

FROM authors

WHERE exists

    (SELECT *

    FROM publishers

    WHERE authors.city = publishers.city)

GO

-- Or, using = ANY

USE pubs

GO

SELECT au_lname, au_fname

FROM authors

WHERE city = ANY

    (SELECT city

    FROM publishers)

GO

Here is the result set for either query:

au_lname                                 au_fname

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

Carson                                   Cheryl

Bennet                                   Abraham

(2 row(s) affected)

D. Compare queries using EXISTS and IN

This example shows queries to find titles of books published by any publisher located in a city that begins with the letter B.

USE pubs

GO

SELECT title

FROM titles

WHERE EXISTS

    (SELECT *

    FROM publishers

    WHERE pub_id = titles.pub_id

    AND city LIKE 'B%')

GO

-- Or, using IN:

USE pubs

GO

SELECT title

FROM titles

WHERE pub_id IN

    (SELECT pub_id

    FROM publishers

    WHERE city LIKE 'B%')

GO

Here is the result set for either query:

title

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

The Busy Executive's Database Guide

Cooking with Computers: Surreptitious Balance Sheets

You Can Combat Computer Stress!

Straight Talk About Computers

But Is It User Friendly?

Secrets of Silicon Valley

Net Etiquette

Is Anger the Enemy?

Life Without Fear

Prolonged Data Deprivation: Four Case Studies

Emotional Security: A New Algorithm

(11 row(s) affected)

E. Use NOT EXISTS

NOT EXISTS works the same as EXISTS, except the WHERE clause in which NOT EXISTS is used is satisfied if no rows are returned by the subquery. This example finds the names of publishers who do not publish business books.

USE pubs

GO

SELECT pub_name

FROM publishers

WHERE NOT EXISTS

    (SELECT *

    FROM titles

    WHERE pub_id = publishers.pub_id

    AND type = 'business')

ORDER BY pub_name

GO

Here is the result set:

pub_name

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

Binnet & Hardley

Five Lakes Publishing

GGG&G

Lucerne Publishing

Ramona Publishers

Scootney Books

(6 row(s) affected)

See Also
Expressions | WHERE
Functions |


EXP

Returns the exponential value of the given float expression.

Syntax

EXP(float_expression)

Arguments
float_expression
Is an expression of type float.
Return Types

float

Examples

This example declares a variable and returns the exponential value of the given variable (378.615345498) with a text description.

DECLARE @var float

SET @var = 378.615345498

SELECT 'The EXP of the variable is: ' + CONVERT(varchar,EXP(@var))

GO

Here is the result set:

The EXP of the variable is: 2.69498e+164

(1 row(s) affected)

See Also
CAST and CONVERT | money and smallmoney
float and real | Mathematical Functions


Expressions

An expression is a combination of symbols and operators that Microsoft® SQL Server™ evaluates to obtain a single data value. Simple expressions can be a single constant, variable, column, or scalar function. Operators can be used to join two or more simple expressions into a complex expression.

Syntax

{ constant
| scalar_function
| [alias.]column
| local_variable
| (expression)
 | (scalar_subquery)
| {unary_operator}expression
| expression {binary_operator} expression
}

Arguments
constant
Is a symbol that represents a single, specific data value. constant is one or more alphanumeric characters (letters a-z and A-Z) or symbols (!, @, #, and so on). Character and datetime values are enclosed in quotation marks, binary strings and numeric constants are not. For more information, see Constants.
scalar_function
Is a unit of Transact-SQL syntax that provides a specific service and returns a single value, such as the SUM, GETDATE, or CAST functions.
[alias.]
Is the alias, or correlation name, assigned to a table by the AS keyword in the FROM clause.
column
Is the name of a column. Only the name of the column is allowed in an expression; a four-part name cannot be specified.
local_variable
Is the name of a user-defined variable. For more information, see DECLARE @local_variable.
(expression)
Is any valid SQL Server expression as defined in this topic. The parentheses are grouping operators that ensure that all the operators in the expression within the parentheses are evaluated before the resulting expression is combined with another.
(scalar_subquery)
Is a subquery that returns one value, for example:

SELECT MAX(UnitPrice)

FROM Products

{unary_operator}
Is an operator that has only one numeric operand:
  • + indicates a positive number.
  • - indicates a negative number.
  • ~ indicates the one’s complement operator.

Unary operators can be applied only to expressions that evaluate to any of the data types of the numeric data type category.

{binary_operator}
Is an operator that defines the way two expressions are combined to yield a single result. binary _operator can be an arithmetic operator, the assignment operator (=), a bitwise operator, a comparison operator, a logical operator, the string concatenation operator (+), or a unary operator. For more information about operators, see Operators.
Expression Results

For a simple expression built of a single constant, variable, scalar function, or column name, the data type, precision, scale, and value of the expression is the data type, precision, scale, and value of the referenced element.

When two expressions are combined using comparison or logical operators, the resulting data type is Boolean and the value is one of three values: TRUE, FALSE, or UNKNOWN. For more information about Boolean data types, see Operators.

When two expressions are combined using arithmetic, bitwise, or string operators, the resulting data type is determined by the operator.

Complex expressions made up of many symbols and operators evaluate to a single-valued result. The data type, precision, and value of the resulting expression is determined by combining the component expressions two at a time until a final result is reached. The sequence in which the expressions are combined is defined by the precedence of the operators in the expression.

Remarks

Two expressions can be combined by an operator if they both have data types supported by the operator and at least one of these conditions is TRUE:

  • The expressions have the same data type.
  • The data type with the lower precedence can be implicitly converted to the data type with the higher data type precedence.
  • The CAST function can explicitly convert the data type with the lower precedence to either the data type with the higher precedence or to an intermediate data type that can be implicitly converted to the data type with the higher precedence.

If there is no supported implicit or explicit conversion, the two expressions cannot be combined.

In a programming language such as C or Microsoft Visual Basic®, an expression always evaluates to a single result. Expressions in an Transact-SQL select list have a variation on this rule: The expression is evaluated individually for each row in the result set. A single expression may have a different value in each row of the result set, but each row has only one value for the expression. For example, in this SELECT statement both the reference to ProductID and the term 1+2 in the select list are expressions:

SELECT ProductID, 1+2

FROM Northwind.dbo.Products

The expression 1+2 evaluates to 3 in each row in the result set. Although the expression ProductID generates a unique value in each result set row, each row only has one value for ProductID.

See Also
CASE | Functions
CAST and CONVERT | LIKE
COALESCE | NULLIF
Data Types | SELECT
Data Type Precedence | WHERE


FETCH

Retrieves a specific row from a Transact-SQL server cursor.

Syntax

FETCH
[ [ NEXT | PRIOR | FIRST | LAST
| ABSOLUTE {n | @nvar}
| RELATIVE {n | @nvar}
]
FROM
]
{ { [GLOBAL] cursor_name } | @cursor_variable_name}
[INTO @variable_name[,…n] ]

Arguments
NEXT
Returns the result row immediately following the current row, and increments the current row to the row returned. If FETCH NEXT is the first fetch against a cursor, it returns the first row in the result set. NEXT is the default cursor fetch option.
PRIOR
Returns the result row immediately preceding the current row, and decrements the current row to the row returned. If FETCH PRIOR is the first fetch against a cursor, no row is returned and the cursor is left positioned before the first row.
FIRST
Returns the first row in the cursor and makes it the current row.
LAST
Returns the last row in the cursor and makes it the current row.
ABSOLUTE {n | @nvar}
If n or @nvar is positive, returns the row n rows from the front of the cursor and makes the returned row the new current row. If n or @nvar is negative, returns the row n rows before the end of the cursor and makes the returned row the new current row. If n or @nvar is 0, no rows are returned. n must be an integer constant and @nvar must be smallint, tinyint, or int.
RELATIVE {n | @nvar}
If n or @nvar is positive, returns the row n rows beyond the current row and makes the returned row the new current row. If n or @nvar is negative, returns the row n rows prior to the current row and makes the returned row the new current row. If n or @nvar is 0, returns the current row. If FETCH RELATIVE is specified with n or @nvar set to negative numbers or 0 on the first fetch done against a cursor, no rows are returned. n must be an integer constant and @nvar must be smallint, tinyint, or int.
GLOBAL
Specifies that cursor_name refers to a global cursor.
cursor_name
Is the name of the open cursor from which the fetch should be made. If both a global and a local cursor exist with cursor_name as their name, cursor_name to the global cursor if GLOBAL is specified and to the local cursor if GLOBAL is not specified.
@cursor_variable_name
Is the name of a cursor variable referencing the open cursor from which the fetch should be made.
INTO @variable_name[,…n]
Allows data from the columns of a fetch to be placed into local variables. Each variable in the list, from left to right, is associated with the corresponding column in the cursor result set. The data type of each variable must either match or be a supported implicit conversion of the data type of the corresponding result set column. The number of variables must match the number of columns in the cursor select list.
Remarks

If the SCROLL option is not specified in an SQL-92 style DECLARE CURSOR statement, NEXT is the only FETCH option supported. If SCROLL is specified in an SQL-92 style DECLARE CURSOR, all FETCH options are supported.

When the Transact_SQL DBCLARE cursor extensions are used, these rules apply:

  • If either FORWARD-ONLY or FAST_FORWARD is specified, NEXT is the only FETCH option supported.
  • If DYNAMIC, FORWARD_ONLY or FAST_FORWARD are not specified, and one of KEYSET, STATIC, or SCROLL are specified, all FETCH options are supported.
  • DYNAMIC SCROLL cursors support all the FETCH options except ABSOLUTE.

The @@FETCH_STATUS function reports the status of the last FETCH statement. The same information is recorded in the fetch_status column in the cursor returned by sp_describe_cursor. This status information should be used to determine the validity of the data returned by a FETCH statement prior to attempting any operation against that data. For more information, see @@FETCH_STATUS.

Permissions

FETCH permissions default to any valid user.

Examples

A. Use FETCH in a simple cursor

This example declares a simple cursor for the rows in the authors table with a last name beginning with B, and uses FETCH NEXT to step through the rows. The FETCH statements return the value for the column specified in the DECLARE CURSOR as a single-row result set.

USE pubs

GO

DECLARE authors_cursor CURSOR FOR

SELECT au_lname FROM authors

WHERE au_lname LIKE “B%”

ORDER BY au_lname

OPEN authors_cursor

-- Perform the first fetch.

FETCH NEXT FROM authors_cursor

-- Check @@FETCH_STATUS to see if there are any more rows to fetch.

WHILE @@FETCH_STATUS = 0

BEGIN

    -- This is executed as long as the previous fetch succeeds.

    FETCH NEXT FROM authors_cursor

END

CLOSE authors_cursor

DEALLOCATE authors_cursor

GO

au_lname

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

Bennet

au_lname

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

Blotchet-Halls

au_lname

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

B. Use FETCH to store values in variables

This example is similar to the last example, except the output of the FETCH statements is stored in local variables rather than being returned directly to the client. The PRINT statement combines the variables into a single string and returns them to the client.

USE pubs

GO

-- Declare the variables to store the values returned by FETCH.

DECLARE @au_lname varchar(40), @au_fname varchar(20)

DECLARE authors_cursor CURSOR FOR

SELECT au_lname, au_fname FROM authors

WHERE au_lname LIKE “B%”

ORDER BY au_lname, au_fname

OPEN authors_cursor

-- Perform the first fetch and store the values in variables.

-- Note: The variables are in the same order as the columns

-- in the SELECT statement.

FETCH NEXT FROM authors_cursor

INTO @au_lname, @au_fname

-- Check @@FETCH_STATUS to see if there are any more rows to fetch.

WHILE @@FETCH_STATUS = 0

BEGIN

    -- Concatenate and display the current values in the variables.

    PRINT "Author: " + @au_fname + " " +  @au_lname

    -- This is executed as long as the previous fetch succeeds.

    FETCH NEXT FROM authors_cursor

    INTO @au_lname, @au_fname

END

CLOSE authors_cursor

DEALLOCATE authors_cursor

GO

Author: Abraham Bennet

Author: Reginald Blotchet-Halls

C. Declare a SCROLL cursor and use the other FETCH options

This example creates a SCROLL cursor to allow full scrolling capabilities through the LAST, PRIOR, RELATIVE, and ABSOLUTE options.

USE pubs

GO

-- Execute the SELECT statement alone to show the

-- full result set that is used by the cursor.

SELECT au_lname, au_fname FROM authors

ORDER BY au_lname, au_fname

-- Declare the cursor.

DECLARE authors_cursor SCROLL CURSOR FOR

SELECT au_lname, au_fname FROM authors

ORDER BY au_lname, au_fname

OPEN authors_cursor

-- Fetch the last row in the cursor.

FETCH LAST FROM authors_cursor

-- Fetch the row immediately prior to the current row in the cursor.

FETCH PRIOR FROM authors_cursor

-- Fetch the second row in the cursor.

FETCH ABSOLUTE 2 FROM authors_cursor

-- Fetch the row that is three rows after the current row.

FETCH RELATIVE 3 FROM authors_cursor

-- Fetch the row that is two rows prior to the current row.

FETCH RELATIVE -2 FROM authors_cursor

CLOSE authors_cursor

DEALLOCATE authors_cursor

GO

au_lname                                 au_fname

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

Bennet                                   Abraham

Blotchet-Halls                           Reginald

Carson                                   Cheryl

DeFrance                                 Michel

del Castillo                             Innes

Dull                                     Ann

Green                                    Marjorie

Greene                                   Morningstar

Gringlesby                               Burt

Hunter                                   Sheryl

Karsen                                   Livia

Locksley                                 Charlene

MacFeather                               Stearns

McBadden                                 Heather

O'Leary                                  Michael

Panteley                                 Sylvia

Ringer                                   Albert

Ringer                                   Anne

Smith                                    Meander

Straight                                 Dean

Stringer                                 Dirk

White                                    Johnson

Yokomoto                                 Akiko

au_lname                                 au_fname

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

Yokomoto                                 Akiko

au_lname                                 au_fname

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

White                                    Johnson

au_lname                                 au_fname

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

Blotchet-Halls                           Reginald

au_lname                                 au_fname

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

del Castillo                             Innes

au_lname                                 au_fname

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

Carson                                   Cheryl

See Also
CLOSE | DECLARE CURSOR
DEALLOCATE | OPEN


FILE_ID

Returns the file identification number (file ID) for the given logical file name in the current database.

Syntax

FILE_ID('file_name')

Arguments
'file_name'
Is the name of the file for which to return the file ID. file_name is nchar(128).
Return Types

smallint

Remarks

file_name corresponds to the name column in sysfiles.

Examples

This example returns the file ID (1) for the master database.

USE master

SELECT FILE_ID('master')

See Also
Control-of-Flow Language | UPDATE
DELETE | WHERE
INSERT | Metadata Functions
SELECT |


FILE_NAME

Returns the logical file name for the given file identification number (ID).

Syntax

FILE_NAME(file_id)

Arguments
file_id
Is the file identification number for which to return the file name. file_id is smallint.
Return Types

nvarchar(128)

Remarks

file_ID corresponds to the fileid column in sysfiles.

Examples

This example returns the file name for a file_ID of 1 (the master database file).

USE master

SELECT FILE_NAME(1)

See Also
Control-of-Flow Language | UPDATE
DELETE | WHERE
INSERT | Metadata Functions
SELECT |


FILEGROUP_ID

Returns the filegroup identification number (ID) for the given filegroup name.

Syntax

FILEGROUP_ID('filegroup_name')

Arguments
'filegroup_name'
Is the filegroup name for which to return the filegroup ID. filegroup_name is nvarchar(128).
Return Types

smallint

Remarks

filegroup_name corresponds to the groupname column in sysfilegroups.

Examples

This example returns the filegroup ID for the filegroup named default.

USE master

SELECT FILEGROUP_ID('default')

See Also
Control-of-Flow Language | UPDATE
DELETE | WHERE
INSERT | Metadata Functions
SELECT |


FILEGROUP_NAME

Returns the filegroup name for the given filegroup identification number (ID).

Syntax

FILEGROUP_NAME(filegroup_id)

Arguments
filegroup_id
Is the filegroup identification number (ID) for which to return the filegroup name. filegroup_id is smallint.
Return Types

nvarchar(128)

Remarks

filegroup_id corresponds to the groupid column in sysfilegroups.

Examples

This example returns the filegroup name for the filegroup ID 1 (the default).

USE master

SELECT FILEGROUP_NAME(1)

See Also
Control-of-Flow Language | UPDATE
DELETE | WHERE
INSERT | Metadata Functions
SELECT |


FILEGROUPPROPERTY

Returns the specified filegroup property value when given a filegroup and property name.

Syntax

FILEGROUPPROPERTY(filegroup_name, property)

Arguments
filegroup_name
Is an expression containing the name of the filegroup for which to return the named property information. filegroup_name is nvarchar(128).
property
Is an expression containing the name of the filegroup property to return. property is varchar(128), and can be one of these values.

Value Description Value returned
IsReadOnly Filegroup name is read-only. 1 = True
0 = False
NULL = Invalid input
IsUserDefinedFG Filegroup name is a user-defined filegroup. 1 = True
0 = False
NULL = Invalid input
IsDefault Filegroup name is the default filegroup. 1 = True
0 = False
NULL = Invalid input

Return Types

int

Examples

This example returns the setting for the IsUserDefinedFG property for the primary filegroup.

USE master

SELECT FILEGROUPPROPERTY('primary', 'IsUserDefinedFG')

See Also
Control-of-Flow Language | UPDATE
DELETE | WHERE
INSERT | Metadata Functions
SELECT |


FILEPROPERTY

Returns the specified file name property value when given a file name and property name.

Syntax

FILEPROPERTY(file_name, property)

Arguments
file_name
Is an expression containing the name of the file associated with the current database for which to return property information. file_name is nchar(128).
property
Is an expression containing the name of the file property to return. property is varchar(128), and can be one of these values.

Value | Description | Value returned
IsReadOnly File is read-only. 1 = True
0 = False
NULL = Invalid input
IsPrimaryFile File is the primary file. 1 = True
0 = False
NULL = Invalid input
IsLogFile File is a log file. 1 = True
0 = False
NULL = Invalid input
SpaceUsed | Amount of space used by the specified file. | Number of pages allocated in the file

Return Types

int

Examples

This example returns the setting for the IsPrimaryFile property for the master file name in the master database.

USE master

SELECT FILEPROPERTY('master', 'IsPrimaryFile')

See Also
Control-of-Flow Language | UPDATE
DELETE | WHERE
INSERT | Metadata Functions
SELECT |


float and real

Approximate number data types for use with floating point numeric data. Floating point data is approximate; not all values in the data type range can be precisely represented.

Syntax
float[(n)]
Is a floating point number data from - 1.79E + 308 through 1.79E + 308. n is the number of bits used to store the mantissa of the float number in scientific notation and thus dictates the precision and storage size. n must be a value from 1 through 53.

n is | Precision | Storage size
1-24 | 7 digits | 4 bytes
25-53 | 15 digits | 8 bytes

The Microsoft® SQL Server™ float[(n)] data type conforms to the SQL-92 standard for all values of n from 1 to 53. The synonym for double precision is float(53).

real
Floating point number data from –3.40E + 38 through 3.40E + 38. Storage size is 4 bytes. In SQL Server, the synonym for real is float(24).
See Also
ALTER TABLE | DELETE
CAST and CONVERT | INSERT
CREATE TABLE | SET @local_variable
Data Types | UPDATE
DECLARE @local_variable |


FLOOR

Returns the largest integer less than or equal to the given numeric expression.

Syntax

FLOOR(numeric_expression)

Arguments
numeric_expression
Is an expression of the exact numeric or approximate numeric data type category, except for the bit data type.
Return Types

Returns the same type as numeric_expression.

Examples

This example shows positive numeric, negative numeric, and currency values with the FLOOR function.

SELECT FLOOR(123.45), FLOOR(-123.45), FLOOR($123.45)

The result is the integer portion of the calculated value in the same data type as numeric_expression.

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

123            -124          123.0000

See Also

Mathematical Functions


FORMATMESSAGE

Constructs a message from an existing message in sysmessages. The functionality of FORMATMESSAGE resembles that of the RAISERROR statement; however, RAISERROR prints the message immediately, and FORMATMESSAGE returns the edited message for further processing.

Syntax

FORMATMESSAGE(msg_number, param_value[,…n])

Arguments
msg_number
Is the ID of the message that is stored in sysmessages. If the message does not exist in sysmessages, an error is returned.
param_value
Is one or more parameter values for use in the message. The values must be specified in the order in which the placeholder variables appear in the message. The maximum number of values is 20.
Return Types

nvarchar

Remarks

Like the RAISERROR statement, FORMATMESSAGE edits the message by substituting the supplied parameter values for placeholder variables in the message. For information about the placeholders allowed in error messages and the editing process, see RAISERROR.

FORMATMESSAGE looks up the message in the current language of the user. If there is no localized version of the message, the U.S. English version is used.

For localized messages, the supplied parameter values must correspond to the parameter placeholders in the U.S. English version. That is, parameter 1 in the localized version must correspond to parameter 1 in the U.S. English version, parameter 2 must correspond to parameter 2, and so on.

Example:

This example uses a hypothetical message 50001, stored in sysmessages as “The number of rows in %s is %1d.” FORMATMESSAGE substitutes the values Table1 and 5 for the parameter placeholders. The resulting string, “The number of rows in Table1 is 5.” is stored in the local variable @var1.

DECLARE @var1 VARCHAR(100)

SELECT @var1 = FORMATMESSAGE(50001, 'Table1', 5)

See Also
sp_addmessage System Functions


FREETEXT

Is a predicate used to search columns containing character-based data types for values that match the meaning and not the exact wording of the words in the search condition. When FREETEXT is used, the full-text query engine internally “word-breaks” the freetext_string into a number of search terms and assigns each term a weight and then finds the matches.

Syntax

FREETEXT
(
 {column | * }, 'freetext_string'
)

Arguments
column
Is the name of a specific column that has been registered for full-text searching. Columns of the character string data types are valid columns for full-text searching.
*
Specifies that all columns that have been registered for full-text searching should be used to search for the given freetext_string.
freetext_string
Is some text to search for in the specified column. Any text, including words, phrases or sentences, can be entered; there is no concern about syntax. However, variables cannot be used.
Remarks

Full-text queries using FREETEXT are less precise than those full-text queries using CONTAINS. The Microsoft® SQL Server™ full-text search engine identifies important words and phrases. No special meaning is given to any of the reserved keywords or wildcard characters that typically have meaning when specified in the <contains_search_condition> parameter of the CONTAINS predicate.

Examples

This example searches for all product categories containing the words related to bread, candy, dry, and meat in the product description, such as breads, candies, dried, and meats.

USE Northwind

GO

SELECT CategoryName

FROM Categories

WHERE FREETEXT (Description, 'sweetest candy bread and dry meat' )

GO

See Also
CONTAINS | FREETEXTTABLE
CONTAINSTABLE | WHERE
Data Types |


FREETEXTTABLE

Returns a table of zero, one, or more rows for those columns containing character-based data types for values that match the meaning but not the exact wording of the text in the specified freetext_string. FREETEXTTABLE can be referenced in the FROM clause of a SELECT statement like a regular table name.

Queries using FREETEXTTABLE specify freetext-type full-text queries that return a relevance ranking value (RANK) for each row.

Syntax

FREETEXTTABLE (table, {column | *}, 'freetext_string')

Arguments
table
Is the name of the table that has been marked for full-text querying. table can be a one-part database object name or a multipart database object name. For more information, see Transact-SQL Syntax Conventions.
column
Is the name of the column to search that resides within table. Columns of the character string data types are valid columns for full-text searching.
*
Specifies that all columns that have been registered for full-text searching should be used to search for the given freetext_string.
freetext_string
Is the text to search for in the specified column. Variables cannot be used.
Remarks

FREETEXTTABLE uses the same search conditions as the FREETEXT predicate.

Like CONTAINSTABLE, the table returned has columns named KEY and RANK, which are referenced within the query to obtain the appropriate rows and use the row ranking values.

Permissions

FREETEXTTABLE can be invoked only by users with appropriate SELECT privileges for the specified table or the referenced columns of the table.

Examples

This example returns the category name and description of all categories that relate to sweet, candy, bread, dry, and meat.

USE Northwind

SELECT FT_TBL.CategoryName,

    FT_TBL.Description,

    KEY_TBL.RANK

FROM Categories AS FT_TBL INNER JOIN

    FREETEXTTABLE(Categories, Description,

    'sweetest candy bread and dry meat') AS KEY_TBL

    ON FT_TBL.CategoryID = KEY_TBL.[KEY]

GO

See Also
CONTAINS | SELECT
CONTAINSTABLE | WHERE
FREETEXT | Rowset Functions


FROM

Specifies the tables, views, derived tables, and joined tables used in DELETE, SELECT, and UPDATE statements.

Syntax

[ FROM {<table_source>} [,…n] ]

<table_source> ::=
 table_name [ [AS] table_alias ] [ WITH ( <table_hint> [,…n]) ]
| view_name [ [AS] table_alias ]
| rowset_function [ [AS] table_alias ]
| derived_table [AS] table_alias [ (column_alias [,…n] ) ]
| <joined_table>

<joined_table> ::=
<table_source> <join_type> <table_source> ON <search_condition>
| <table_source> CROSS JOIN <table_source>
| <joined_table>

<join_type> ::=
[ INNER | { { LEFT | RIGHT | FULL } [OUTER] } ]
[ <join_hint> ]
JOIN

Arguments
<table_source>
Specifies a table or view, both with or without an alias, to use in the Transact-SQL statement. Up to 256 tables can be used in the statement. If the table or view exists in another database on the same computer running Microsoft® SQL Server™, use a fully qualified name in the form database.owner.object_name. If the table or view exists outside the local server on a linked server, use a four-part name in the form linked_server.catalog.schema.object.
table_name
Is the name of a table. The order of the tables and views after the FROM keyword does not affect the result set returned. Errors are reported when duplicate names appear in the FROM clause.
view_name]
Is the name of a view. A view is a “virtual table,” usually created as a subset of columns from one or more tables.
rowset_function
Specifies one of the rowset functions, which return an object that can be used in place of a table reference. For more information about a list of rowset functions, see “Rowset Functions.”Rowset Functions.
[AS] table_alias
Is an alias for table_name, view_name, or rowset_function, used either for convenience or to distinguish a table or view in a self-join or subquery. An alias is often a shortened table name that is used to refer to specific columns of the tables in a join. If the same column name exists in more than one table in the join, SQL Server requires that the column name must be qualified by a table name or alias. (The table name cannot be used if an alias has been defined).
WITH (<table_hint>)
Specifies a table scan, one or more indexes to be used by the query optimizer, or a locking method to be used by the query optimizer with this table and for this statement. For syntax and other information, see Table Hints later in this topic.
derived_table
Is a subquery that retrieves rows from the database. derived_table is used as input to the outer query.
column_alias
Is an optional alias to replace a column name in the result set. Include one column alias for each column in the select list, and enclose the entire list of column aliases in parentheses.
<joined_table>
Is a result set that is the product of two or more tables, for example:

FROM tab1 LEFT OUTER JOIN tab1.c3 = tab2.c3
    RIGHT OUTER JOIN tab3 LEFT OUTER JOIN tab4
        ON tab3.c1
    ON tab2.c3 = tab4.c3

For multiple CROSS joins, use parentheses to change the natural order of the joins.

<join_type>
Specifies the type of join operation.
INNER
Specifies all matching pairs of rows are returned. Discards unmatched rows from both tables. This is the default if no join type is specified.
FULL [OUTER]
Specifies that a row from either the left or right table that does not meet the join condition is included in the result set, and output columns that correspond to the other table are set to NULL. This is in addition to all rows usually returned by the INNER JOIN.

Note It is possible to specify outer joins as specified here or by using the old nonstandard *= and =* operators in the WHERE clause. The two methods cannot both be used in the same statement.

LEFT [OUTER]
Specifies that all rows from the left table not meeting the join condition are included in the result set, and output columns from the other table are set to NULL in addition to all rows returned by the inner join.
RIGHT [OUTER]
Specifies all rows from the right table not meeting the join condition are included in the result set, and output columns that correspond to the other table are set to NULL, in addition to all rows returned by the inner join.
<join_hint>
Specifies that the SQL Server query optimizer use one join hint, or execution algorithm, per join specified in the query’s FROM clause. For more information, see Join Hints later in this topic.
JOIN
Indicates that the specified join operation should take place between the given tables or views.
ON <search_condition>
Specifies the condition on which the join is based. The condition can specify any predicate, although columns and comparison operators are often used, for example:

SELECT ProductID, Suppliers.SupplierID
    FROM Suppliers JOIN Products
    ON (Suppliers.SupplierID = Products.SupplierID)

When the condition specifies columns, the columns do not have to have the same name or same data type; however, if the data types are not identical, they must be either compatible or types that Microsoft SQL Server can implicitly convert. If the data types cannot be implicitly converted, the condition must explicitly convert the data type using the CAST function.

For more information about search conditions and predicates, see Search Condition.

CROSS JOIN
Specifies the cross-product of two tables. Returns the same rows as if no WHERE clause was specified in an old-style, non-SQL-92-style join.
Table Hints

A table hint specifies a table scan, one or more indexes to be used by the query optimizer, or a locking method to be used by the query optimizer with this table and for this SELECT. Although this is an option, the query optimizer can usually pick the best optimization method without hints being specified.

Caution Because the query optimizer of SQL Server usually selects the best execution plan for a query, it is recommended that <join_hint>, <query_hint>, and <table_hint> only be used as a last resort by experienced database administrators.

The use of commas between table hints is optional but encouraged. Separation of hints by spaces rather than commas is supported for backward compatibility.

The use of the WITH keyword is encouraged although it is not currently required. In future releases of SQL Server, WITH may be a required keyword.

If a table (including system tables) contains computed columns and the computed columns are computed by expressions or functions accessing columns in other tables, the table hints are not used on those tables (the table hints are not propagated). For example, a NOLOCK table hint is specified on a table in the query. This table has computed columns that are computed by a combination of expressions and functions (accessing columns in another table). The tables referenced by the expressions and functions do not use the NOLOCK table hint when accessed.

SQL Server does not allow more than one table hint from each of the following groups:

  • Granularity hints: PAGLOCK, NOLOCK, ROWLOCK, TABLOCK, or TABLOCKX.
  • Isolation level hints: HOLDLOCK, NOLOCK, READCOMMITTED, REPEATABLEREAD, SERIALIZABLE.

The NOLOCK, READUNCOMMITTED, and READPAST table hints are not allowed for tables that are targets of delete, insert, or update operations.

Syntax

<table_hint> ::=
{ INDEX(index_val [,…n])
| FASTFIRSTROW
| HOLDLOCK
| NOLOCK
| PAGLOCK
| READCOMMITTED
| READPAST
| READUNCOMMITTED
| REPEATABLEREAD
| ROWLOCK
| SERIALIZABLE
| TABLOCK
| TABLOCKX
| UPDLOCK
}

Arguments
INDEX(index_val [,…n])
Specifies the name or ID of the indexes to be used by SQL Server when processing the statement. Only one index hint per table can be specified.

If a clustered index exists, INDEX(0) forces a clustered index scan and INDEX(1) forces a clustered index scan or seek. If no clustered index exists, INDEX(0) forces a table scan and INDEX(1) is interpreted as an error.

Any index hints specified for a view are ignored, and SQL Server returns a warning message.

The alternative INDEX = syntax (which specifies a single index hint) is supported only for backward compatibility.

If multiple indexes are used in the single hint list, the duplicates are ignored and the rest of the listed indexes are used to retrieve the rows of the table. The order of the indexes in the index hint is significant. A multiple index hint also enforces index ANDing and SQL Server applies as many conditions as possible on each index accessed. If the collection of hinted indexes is not covering, a fetch is performed after retrieving all the indexed columns.

Note If an index hint referring to multiple indexes is used on the fact table in a star join, SQL Server ignores the index hint and returns a warning message. Also, index ORing is disallowed for a table with an index hint specified.

The maximum number of indexes in the table hint is 250 nonclustered indexes.

FASTFIRSTROW
Equivalent to OPTION (FAST 1). For more information, see FAST in the OPTION clause in SELECT.
HOLDLOCK
Equivalent to SERIALIZABLE. (See SERIALIZABLE for more information.) The HOLDLOCK option applies only to the table or view for which it is specified and only for the duration of the transaction defined by the statement in which it is used. HOLDLOCK cannot be used in a SELECT statement that includes the FOR BROWSE option.
NOLOCK
Equivalent to READUNCOMMITTED. (See READUNCOMMITTED for more information.)
PAGLOCK
Takes shared page locks where a single shared table lock is normally taken.
READCOMMITTED
Specifies that a scan is performed with the same locking semantics as a transaction running at READ COMMITTED isolation level. For more information about isolation levels, see SET TRANSACTION ISOLATION LEVEL.
READPAST
Specifies that locked rows are skipped (read past). For example, assume table T1 contains a single integer column with the values of 1, 2, 3, 4, 5. If transaction A changes the value of 3 to 8 but has not yet committed, a SELECT * FROM T1 (READPAST) yields values 1, 2, 4, 5. READPAST applies only to transactions operating at READ COMMITTED isolation and reads past only row-level locks. This lock hint is used primarily to implement a work queue on a SQL Server table.
READUNCOMMITTED
Specifies that dirty reads are allowed, which means that no shared locks are issued and no exclusive locks are honored. Allowing dirty reads can result in higher concurrency, but at the cost of lower consistency. If READUNCOMMITTED is specified, it is possible to read an uncommitted transaction or to read a set of pages rolled back in the middle of the read; therefore, error messages may result. For more information about isolation levels, see SET TRANSACTION ISOLATION LEVEL.

Note If you receive error messages 605, 606, 624, or 625 when READUNCOMMITTED is specified, resolve them as you would a deadlock error (1205), and retry your statement.

REPEATABLEREAD
Specifies that a scan is performed with the same locking semantics as a transaction running at REPEATABLE READ isolation level. For more information about isolation levels, see SET TRANSACTION ISOLATION LEVEL.
ROWLOCK
Specifies that a shared row lock is taken when a single shared page or table lock is normally taken.
SERIALIZABLE
Equivalent to HOLDLOCK. Makes shared locks more restrictive by holding them until the completion of a transaction (instead of releasing the shared lock as soon as the required table or data page is no longer needed, whether or not the transaction has been completed). The scan is performed with the same semantics as a transaction running at the SERIALIZABLE isolation level. For more information about isolation levels, see SET TRANSACTION ISOLATION LEVEL.
TABLOCK
Specifies that a shared lock is taken on the table held until the end-of-statement. If HOLDLOCK is also specified, the shared table lock is held until the end of the transaction.
TABLOCKX
Specifies that an exclusive lock is taken on the table held until the end-of-statement or end-of-transaction.
UPDLOCK
Specifies that update locks instead of shared locks are taken while reading the table, and that they are held until the end-of-statement or end-of-transaction.
Join Hints

Join hints, which are specified in a query's FROM clause, enforce a join strategy between two tables. If a join hint is specified for any two tables, the query optimizer automatically enforces the join order for all joined tables in the query, based on the position of the ON keywords. In the case of FULL OUTER JOINS, when the ON clauses are not used, parentheses can be used to indicate the join order.

Caution Because the SQL Server query optimizer usually selects the best execution plan for a query, it is recommended that <join_hint>, <query_hint>, and <table_hint> be used only as a last resort by experienced database administrators.

Syntax

<join_hint> ::=
{ LOOP | HASH | MERGE | REMOTE }

Arguments
LOOP | HASH | MERGE
Specifies that the join in the query should use looping, hashing, or merging. Using LOOP | HASH | MERGE JOIN enforces a particular join between two tables.
REMOTE
Specifies that the join operation is performed on the site of the right table. This is useful when the left table is a local table and the right table is a remote table. REMOTE should be used only when the left table has fewer rows than the right table.

If the right table is local, the join is performed locally. If both tables are remote but from different data sources, REMOTE causes the join to be performed on the right table's site. If both tables are remote tables from the same data source, REMOTE is not necessary.

Remarks

The FROM clause supports the SQL-92-SQL syntax for joined tables and derived tables. SQL-92 syntax provides the INNER, LEFT OUTER, RIGHT OUTER, and FULL OUTER join operators.

Although the outer join operators from earlier versions of SQL Server are supported, you cannot use both outer join operators and SQL-92-style joined tables in the same FROM clause.

UNION and JOIN within a FROM clause are supported within views as well as in derived tables and subqueries.

A self-join is a table that joins upon itself. Inserts or updates that are based on a self-join follow the order in the FROM clause.

Permissions

FROM permissions default to the permissions for the DELETE, SELECT, or UPDATE statement.

Examples
A. Use a simple FROM clause

This example retrieves the pub_id and pub_name columns from the publishers table.

USE pubs

SELECT pub_id, pub_name

FROM publishers

ORDER BY pub_id

Here is the result set:

pub_id pub_name

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

0736   New Moon Books

0877   Binnet & Hardley

1389   Algodata Infosystems

1622   Five Lakes Publishing

1756   Ramona Publishers

9901   GGG&G

9952   Scootney Books

9999   Lucerne Publishing

(8 row(s) affected)

B. Use the TABLOCK and HOLDLOCK optimizer hints

The following partial transaction shows how to place an explicit shared table lock on authors and how to read the index. The lock is held throughout the entire transaction.

USE pubs

BEGIN TRAN

SELECT COUNT(*)

FROM authors WITH (TABLOCK, HOLDLOCK)

C. Use the SQL-92 CROSS JOIN syntax

This example returns the cross product of the two tables authors and publishers. A list of all possible combinations of au_lname rows and all pub_name rows are returned.

USE pubs

SELECT au_lname, pub_name

FROM authors CROSS JOIN publishers

ORDER BY au_lname ASC, pub_name ASC

Here is the result set:

au_lname                                 pub_name

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

Bennet                                   Algodata Infosystems

Bennet                                   Binnet & Hardley

Bennet                                   Five Lakes Publishing

Bennet                                   GGG&G

Bennet                                   Lucerne Publishing

Bennet                                   New Moon Books

Bennet                                   Ramona Publishers

Bennet                                   Scootney Books

Blotchet-Halls                           Algodata Infosystems

Blotchet-Halls                           Binnet & Hardley

Blotchet-Halls                           Five Lakes Publishing

Blotchet-Halls                           GGG&G

Blotchet-Halls                           Lucerne Publishing

Blotchet-Halls                           New Moon Books

Blotchet-Halls                           Ramona Publishers

Blotchet-Halls                           Scootney Books

Carson                                   Algodata Infosystems

Carson                                   Binnet & Hardley

Carson                                   Five Lakes Publishing

…

Stringer                                 Scootney Books

White                                    Algodata Infosystems

White                                    Binnet & Hardley

White                                    Five Lakes Publishing

White                                    GGG&G

White                                    Lucerne Publishing

White                                    New Moon Books

White                                    Ramona Publishers

White                                    Scootney Books

Yokomoto                                 Algodata Infosystems

Yokomoto                                 Binnet & Hardley

Yokomoto                                 Five Lakes Publishing

Yokomoto                                 GGG&G

Yokomoto                                 Lucerne Publishing

Yokomoto                                 New Moon Books

Yokomoto                                 Ramona Publishers

Yokomoto                                 Scootney Books

(184 row(s) affected)

D. Use the SQL-92 FULL OUTER JOIN syntax

This example returns the book title and its corresponding publisher in the titles table. It also returns any publishers who have not published books listed in the titles table, and any book titles with a publisher other than the one listed in the publishers table.

USE pubs

-- The OUTER keyword following the FULL keyword is optional.

SELECT SUBSTRING(titles.title, 1, 10) AS Title,

    publishers.pub_name AS Publisher

FROM publishers FULL OUTER JOIN titles

    ON titles.pub_id = publishers.pub_id

WHERE titles.pub_id IS NULL

    OR publishers.pub_id IS NULL

ORDER BY publishers.pub_name

Here is the result set:

Title      Publisher

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

NULL       Five Lakes Publishing

NULL       GGG&G

NULL       Lucerne Publishing

NULL       Ramona Publishers

NULL       Scootney Books

(5 row(s) affected)

E. Use the SQL-92 LEFT OUTER JOIN syntax

This example joins two tables on au_id and preserves the unmatched rows from the left table. The authors table is matched with the titleauthor table on the au_id columns in each table. All authors, published and unpublished, appear in the result set.

USE pubs

-- The OUTER keyword following the LEFT keyword is optional.

SELECT SUBSTRING(authors.au_lname, 1, 10) AS Last,
    authors.au_fname AS First, titleauthor.title_id

FROM authors LEFT OUTER JOIN titleauthor
    ON authors.au_id = titleauthor.au_id

Here is the result set:

Last       First                title_id

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

White      Johnson              PS3333

Green      Marjorie             BU1032

Green      Marjorie             BU2075

Carson     Cheryl               PC1035

…                                …

McBadden   Heather              NULL

Ringer     Anne                 PS2091

Ringer     Albert               PS2091

Ringer     Albert               PS2106

(29 row(s) affected)

F. Use the SQL-92 INNER JOIN syntax

This example returns all publisher names with the corresponding book titles each publisher has published.

USE pubs

-- By default, SQL Server performs an INNER JOIN if only the JOIN

-- keyword is specified.

SELECT SUBSTRING(titles.title, 1, 30) AS Title, publishers.pub_name

FROM publishers INNER JOIN titles

    ON titles.pub_id = publishers.pub_id

ORDER BY publishers.pub_name

Here is the result set:

Title                          pub_name

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

The Busy Executive's Database  Algodata Infosystems

Cooking with Computers: Surrep Algodata Infosystems

Straight Talk About Computers  Algodata Infosystems

But Is It User Friendly?       Algodata Infosystems

Secrets of Silicon Valley      Algodata Infosystems

Net Etiquette                  Algodata Infosystems

Silicon Valley Gastronomic Tre Binnet & Hardley

The Gourmet Microwave          Binnet & Hardley

The Psychology of Computer Coo Binnet & Hardley

Computer Phobic AND Non-Phobic Binnet & Hardley

Onions, Leeks, and Garlic: Coo Binnet & Hardley

Fifty Years in Buckingham Pala Binnet & Hardley

Sushi, Anyone?                 Binnet & Hardley

You Can Combat Computer Stress New Moon Books

Is Anger the Enemy?            New Moon Books

Life Without Fear              New Moon Books

Prolonged Data Deprivation: Fo New Moon Books

Emotional Security: A New Algo New Moon Books

(18 row(s) affected)

G. Use the SQL-92 RIGHT OUTER JOIN syntax

This example joins two tables on pub_id and preserves the unmatched rows from the right table. The publishers table is matched with the titles table on the pub_id column in each table. All publishers appear in the result set, whether or not they have published any books.

USE pubs

SELECT SUBSTRING(titles.title, 1, 30) AS 'Title', publishers.pub_name

FROM titles RIGHT OUTER JOIN publishers

    ON titles.pub_id = publishers.pub_id

ORDER BY publishers.pub_name

Here is the result set:

Title                          pub_name

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

The Busy Executive's Database  Algodata Infosystems

Cooking with Computers: Surrep Algodata Infosystems

Straight Talk About Computers  Algodata Infosystems

But Is It User Friendly?       Algodata Infosystems

Secrets of Silicon Valley      Algodata Infosystems

Net Etiquette                  Algodata Infosystems

Silicon Valley Gastronomic Tre Binnet & Hardley

The Gourmet Microwave          Binnet & Hardley

The Psychology of Computer Coo Binnet & Hardley

Computer Phobic AND Non-Phobic Binnet & Hardley

Onions, Leeks, and Garlic: Coo Binnet & Hardley

Fifty Years in Buckingham Pala Binnet & Hardley

Sushi, Anyone?                 Binnet & Hardley

NULL                           Five Lakes Publishing

NULL                           GGG&G

NULL                           Lucerne Publishing

You Can Combat Computer Stress New Moon Books

Is Anger the Enemy?            New Moon Books

Life Without Fear              New Moon Books

Prolonged Data Deprivation: Fo New Moon Books

Emotional Security: A New Algo New Moon Books

NULL                           Ramona Publishers

NULL                           Scootney Books

(23 row(s) affected)

H. Use HASH and MERGE join hints

This example performs a three-table join among the authors, titleauthors, and titles tables to produce a list of authors and the books they have written. The query optimizer joins authors and titleauthors (A x TA) using a MERGE join. Next, the results of the authors and titleauthors MERGE join (A x TA) are HASH joined with the titles table to produce (A x TA) x T.

Important After a join hint is specified, the INNER keyword is no longer optional and must be explicitly stated for an INNER JOIN to be performed.

USE pubs

SELECT SUBSTRING((RTRIM(a.au_fname) + ' ' + LTRIM(a.au_lname)), 1, 25)
    AS Name, SUBSTRING(t.title, 1, 20) AS Title

FROM authors a INNER MERGE JOIN titleauthor ta

    ON a.au_id = ta.au_id INNER HASH JOIN titles t

    ON t.title_id = ta.title_id

ORDER BY au_lname ASC, au_fname ASC

Here is the result set:

Warning: The join order has been enforced because a local join hint is used.

Name                      Title

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

Abraham Bennet            The Busy Executive's

Reginald Blotchet-Halls   Fifty Years in Bucki

Cheryl Carson             But Is It User Frien

Michel DeFrance           The Gourmet Microwav

Innes del Castillo        Silicon Valley Gastr

…                         …

Johnson White             Prolonged Data Depri

Akiko Yokomoto            Sushi, Anyone?

(25 row(s) affected)

I. Use a derived table

This example uses a derived table, a SELECT statement after the FROM clause, to return all authors’ first and last names and the book numbers for each title the author has written.

USE pubs

SELECT RTRIM(a.au_fname) + ' ' + LTRIM(a.au_lname) AS Name, d1.title_id

FROM authors a, (SELECT title_id, au_id FROM titleauthor) AS d1

WHERE a.au_id = d1.au_id

ORDER BY a.au_lname, a.au_fname

Here is the result set:

Name                                                          title_id

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

Abraham Bennet                                                BU1032

Reginald Blotchet-Halls                                       TC4203

Cheryl Carson                                                 PC1035

Michel DeFrance                                               MC3021

Innes del Castillo                                            MC2222

Ann Dull                                                      PC8888

Marjorie Green                                                BU1032

Marjorie Green                                                BU2075

Burt Gringlesby                                               TC7777

Sheryl Hunter                                                 PC8888

Livia Karsen                                                  PS1372

Charlene Locksley                                             PC9999

Charlene Locksley                                             PS7777

Stearns MacFeather                                            BU1111

Stearns MacFeather                                            PS1372

Michael O'Leary                                               BU1111

Michael O'Leary                                               TC7777

Sylvia Panteley                                               TC3218

Albert Ringer                                                 PS2091

Albert Ringer                                                 PS2106

Anne Ringer                                                   MC3021

Anne Ringer                                                   PS2091

Dean Straight                                                 BU7832

Johnson White                                                 PS3333

Akiko Yokomoto                                                TC7777

(25 row(s) affected)

See Also
CONTAINSTABLE | OPENROWSET
DELETE | Operators
FREETEXTTABLE | UPDATE
INSERT | WHERE
OPENQUERY |


FULLTEXTCATALOGPROPERTY

Returns information about full-text catalog properties.

Syntaxt

FULLTEXTCATALOGPROPERTY(catalog_name, property)

Arguments
catalog_name
Is an expression containing the name of the full-text catalog.
property
Is an expression containing the name of the full-text catalog property. The table lists the properties and provides descriptions of the information that is returned.

Property | Description
PopulateStatus 0 = Idle
1 = Population in progress
2 = Paused
3 = Throttled
4 = Recovering
5 = Shutdown
6 = Incremental population in progress
7 = Updating index
ItemCount | Number of full-text indexed items currently in the full-text catalog.
IndexSize | Size of the full-text index in megabytes.
UniqueKeyCount | Number of unique words (keys) that make up the full-text index in this catalog. This is an approximation of the number of nonnoise words stored in the full-text catalog.
LogSize | Size, in bytes, of the combined set of error logs associated with a Microsoft Search Service full-text catalog.
PopulateCompletionAge | The difference in seconds between the completion of the last full-text index population and 01/01/1990 00:00:00.

Return Types

int

Remarks

It is important that applications do not wait in a tight loop, checking for the PopulateStatus property to become idle (indicating that population has completed) because this takes CPU cycles away from the database and full-text search processes and causes time outs.

Examples

This example returns the number of full-text indexed items in the Cat_Desc full-text catalog.

USE Northwind

GO

SELECT fulltextcatalogproperty('Cat_Desc', 'ItemCount')

Here is the result set:

-----------

9

See Also
FULLTEXTSERVICEPROPERTY | Metadata Functions
sp_help_fulltext_catalogs |


FULLTEXTSERVICEPROPERTY

Returns information about full-text service-level properties.

Syntaxt

FULLTEXTSERVICEPROPERTY(property)

Arguments
property
Is an expression containing the name of the full-text service-level property. The table lists the properties and provides descriptions of the information that is returned.

Property | Value
ResourceUsage | A value from 1 (background) through 5 (dedicated).
ConnectTimeout | The number of seconds that Microsoft Search Service will wait for all connections to the Microsoft® SQL Server™ database server for full-text index population before timing out.
IsFulltextInstalled 1 = Microsoft Search (Full-text) Service is installed on the computer.
0 = Otherwise.

Return Types

int

Examples

This example verifies that Microsoft Search Service is installed.

SELECT fulltextserviceproperty('IsFulltextInstalled')

Here is the result set:

-----------

1

See Also
FULLTEXTCATALOGPROPERTY | Metadata Functions
sp_fulltext_service |


Functions

The Transact-SQL programming language provides three types of functions:

  • Rowset functions

    Can be used like table references in an SQL statement. For more information about a list of these functions, see Rowset Functions.

  • Aggregate functions

    Operate on a collection of values but return a single, summarizing value. For more information about a list of these functions, see Aggregate Functions.

  • Scalar functions.

    Operate on a single value and then return a single value. Scalar functions can be used wherever an expression is valid. This table categorizes the scalar functions.

Function category | Explanation
Configuration Functions | Returns information about the current configuration.
Cursor Functions | Returns information about cursors.
Date and Time Functions | Performs an operation on a date and time input value and returns either a string, numeric, or date and time value.
Mathematical Functions | Performs a calculation based on input values provided as parameters to the function, and returns a numeric value.
Metadata Functions | Returns information about the database and database objects.
Security Functions | Returns information about users and roles.
String Functions | Performs an operation on a string (char or varchar) input value and returns a string or numeric value.
System Functions | Performs operations and returns information about values, objects, and settings in Microsoft® SQL Server™.
System Statistical Functions | Returns statistical information about the system.
Text and Image Functions | Performs an operation on a text or image input values or column, and returns information about the value.


Aggregate Functions

Aggregate functions perform a calculation on a set of values and return a single value. With the exception of COUNT, aggregate functions ignore null values. Aggregate functions are often used with the GROUP BY clause of the SELECT statement.

Aggregate functions are allowed as expressions only in:

  • The select list of a SELECT statement (either a subquery or an outer query)
  • A COMPUTE or COMPUTE BY clause
  • A HAVING clause

The Transact-SQL programming language provides these aggregate functions:

AVG | SUM
COUNT | STDEV
GROUPING | STDEVP
MAX | VAR
MIN | VARP

See Also

Functions


Configuration Functions

These scalar functions return information about current configuration option settings.

@@CONNECTIONS | @@OPTIONS
@@DATEFIRST | @@NESTLEVEL
@@DBTS | @@REMSERVER
@@LANGUAGE | @@SPID
@@LANGID | @@SERVERNAME
@@LOCK_TIMEOUT | @@SERVICENAME
@@MAX_CONNECTIONS | @@TEXTSIZE
@@MAX_PRECISION | @@VERSION

See Also

Functions


Cursor Functions

These scalar functions return information about cursors.

@@CURSOR_ROWS | @@FETCH_STATUS
CURSOR_STATUS |

See Also

Functions


Date and Time Functions

These scalar functions perform an operation on a date and time input value and return either a string, numeric, or date and time value.

DATEADD | DAY
DATEDIFF | GETDATE
DATENAME | MONTH
DATEPART | YEAR

See Also

Functions


Mathematical Functions

These scalar functions perform a calculation, usually based on input values provided as arguments, and return a numeric value.

ABS | LOG10
ACOS | PI
ASIN | POWER
ATAN | RADIANS
ATN2 | RAND
CEILING | ROUND
COS | SIGN
COT | SIN
DEGREES | SQUARE
EXP | SQRT
FLOOR | TAN
LOG |

Note Arithmetic functions, such as ABS, CEILING, DEGREES, FLOOR, POWER, RADIANS, and SIGN, return a value having the same data type as the input value. Trigonometric and other functions, including EXP, LOG, LOG10, SQUARE, and SQRT, cast their input values to float and return a float value.

See Also

Functions


Metadata Functions

These scalar functions return information about the database and database objects.

COL_LENGTH | FILEPROPERTY
COL_NAME | FULLTEXTCATALOGPROPERTY
COLUMNPROPERTY | FULLTEXTSERVICEPROPERTY
DATABASEPROPERTY | INDEX_COL
DB_ID | INDEXPROPERTY
DB_NAME | OBJECT_ID
FILE_ID | OBJECT_NAME
FILE_NAME | OBJECTPROPERTY
FILEGROUP_ID | @@PROCID
FILEGROUP_NAME | TYPEPROPERTY
FILEGROUPPROPERTY |

See Also

Functions


Security Functions

These scalar functions return information about users and roles.

IS_MEMBER | SUSER_SID
IS_SRVROLEMEMBER | SUSER_SNAME
SUSER_ID | USER_ID
SUSER_NAME | USER

See Also

Functions


String Functions

These scalar functions perform an operation on a string input value and return a string or numeric value.

ASCII | REPLICATE
CHAR | REVERSE
CHARINDEX | RIGHT
DIFFERENCE | RTRIM
LEFT | SOUNDEX
LEN | SPACE
LOWER | STR
LTRIM | STUFF
NCHAR | SUBSTRING
PATINDEX | UNICODE
REPLACE | UPPER
QUOTENAME |

See Also

Functions


System Functions

These scalar functions perform operations on and return information about values, objects, and settings in Microsoft® SQL Server™.

APP_NAME | IDENTITY (Function)
CASE | ISDATE
CAST and CONVERT | ISNULL
COALESCE | ISNUMERIC
CURRENT_TIMESTAMP | NEWID
CURRENT_USER | NULLIF
DATALENGTH | PARSENAME
@@ERROR | PERMISSIONS
FORMATMESSAGE | @@ROWCOUNT
GETANSINULL | SESSION_USER
HOST_ID | STATS_DATE
HOST_NAME | SYSTEM_USER
IDENT_INCR | @@TRANCOUNT
IDENT_SEED | USER_NAME
@@IDENTITY |

See Also

Functions


System Statistical Functions

These scalar functions return statistical information about the system.

@@CPU_BUSY | @@PACKET_ERRORS
@@IDLE | @@TIMETICKS
@@IO_BUSY | @@TOTAL_ERRORS
@@PACK_RECEIVED | @@TOTAL_READ
@@PACK_SENT | @@TOTAL_WRITE

See Also

Functions


Text and Image Functions

These scalar functions perform an operation on a text or image input value or column and return information about the value.

PATINDEX | TEXTVALID
TEXTPTR |

See Also

Functions


Rowset Functions

These rowset functions return an object that can be used in place of a table reference in a Transact-SQL statement.

CONTAINSTABLE | OPENQUERY
FREETEXTTABLE | OPENROWSET

See Also

Functions


GETANSINULL

Returns the default nullability for the database for this session.

Syntax

GETANSINULL(['database'])

Arguments
'database'
Is the name of the database for which to return nullability information. database is either char or nchar. If char, database is implicitly converted to nchar.
Return Types

int

Remarks

When the nullability of the given database allows null values and the column or data type nullability is not explicitly defined, GETANSINULL returns 1. This is the ANSI NULL default.

To activate the ANSI NULL default behavior, one of these conditions must be set:

  • sp_dboption ‘database_name’, ‘ANSI null default’, true
  • SET ANSI_NULL_DFLT_ON ON
  • SET ANSI_NULL_DFLT_OFF OFF
Examples

This example checks the default nullability for the pubs database.

USE pubs

GO

SELECT GETANSINULL('pubs')

GO

Here is the result set:

------

1

(1 row(s) affected)

See Also

System Functions


GETDATE

Returns the current system date and time in the Microsoft® SQL Server™ standard internal format for datetime values.

Syntax

GETDATE()

Return Types

datetime

Remarks

Date functions can be used in the SELECT statement select list or in the WHERE clause of a query.

In designing a report, GETDATE can be uses to print the current date and time every time the report is produced. GETDATE is also useful for tracking activity, such as logging the time a transaction occurred on an account.

Examples
A. Use GET DATE to return the current date and time

This example finds the current system date and time.

SELECT GETDATE()

GO

Here is the result set:

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

July 29 1998   2:50    PM

(1 row(s) affected)

B. Use GETDATE with CREATE TABLE

This example creates the employees table and uses GETDATE for a default value for the employee hire date.

USE pubs

GO

CREATE TABLE employees

(

 emp_id char(11) NOT NULL,

 emp_lname varchar(40) NOT NULL,

 emp_fname varchar(20) NOT NULL,

 emp_hire_date datetime DEFAULT GETDATE(),

 emp_mgr varchar(30)

)

GO

See Also

Date and Time Functions


GO

Signals the end of a batch of Transact-SQL statements to the Microsoft® SQL Server™ utilities.

Syntax

GO

Remarks

GO is not a Transact-SQL statement, it is a command recognized by the osql and isql utilities and SQL Server Query Analyzer.

SQL Server utilities interpret GO as a signal that they should send the current batch of Transact-SQL statements to SQL Server. The current batch of statements is composed of all statements entered since the last GO, or since the start of the ad hoc session or script if this is the first GO. SQL Server Query Analyzer and the osql and isql command-prompt utilities implement GO differently.

A Transact-SQL statement cannot occupy the same line as a GO command. However, the line can contain comments.

Users must follow the rules for batches. For example, any execution of a stored procedure after the first statement in a batch must include the EXECUTE keyword. The scope of local (user-defined) variables is limited to a batch, and cannot be referenced after a GO command.

USE pubs

GO

DECLARE @MyMsg VARCHAR(50)

SELECT @MyMsg = 'Hello, World.'

GO -- @MyMsg is not valid after this GO ends the batch.

-- Yields an error because @MyMsg not declared in this batch.

PRINT @MyMsg

GO

SELECT @@VERSION;

-- Yields an error: Must be EXEC sp_who if not first statement in

-- batch.

sp_who

GO

SQL Server applications can send multiple Transact-SQL statements to SQL Server for execution as a batch. The statements in the batch are then compiled into a single execution plan. Programmers executing ad hoc statements in the SQL Server utilities, or building scripts of Transact-SQL statements to run through the SQL Server utilities, use GO to signal the end of a batch.

Applications based on the DB-Library, ODBC, or OLE DB APIs receive a syntax error if they attempt to execute a GO command. The SQL Server utilities never send a GO command to the server.

Permissions

GO is a utility command that requires no permissions, it can be executed by any user.

Examples

This example creates two batches. The first batch contains only a USE pubs statement to set the database context. The remaining statements use a local variable, so all local variable declarations must be grouped in a single batch. This is done by not having a GO command until after the last statement that references the variable.

USE pubs

GO

DECLARE @NmbrAuthors int

SELECT @NmbrAuthors = COUNT(*)

FROM authors

PRINT 'The number of authors as of ' +

      CAST(GETDATE() AS char(20)) + ' is ' +

      CAST(@NmbrAuthors AS char (10))

GO


GOTO

Alters the flow of execution to a label. The Transact-SQL statement(s) following GOTO are skipped and processing continues at the label. GOTO statements and labels can be used anywhere within a procedure, batch, or statement block. GOTO statements can be nested.

Syntax

Define the label:

label:

Alter the execution:

GOTO label

Arguments
label
Is the point after which processing begins if a GOTO is targeted to that label. Labels must follow the rules for identifiers. A label can be used as a commenting method whether or not GOTO is used.
Remarks

GOTO can exist within conditional control-of-flow statements, statement blocks, or procedures, but it cannot go to a label outside of the batch. GOTO branching can go to a label defined before or after GOTO.

Permissions

GOTO permissions default to any valid user.

Examples

This example shows GOTO looping as an alternative to using WHILE.

Note The tnames_cursor cursor is not defined. This example is for illustration only.

USE pubs

GO

DECLARE @tablename sysname

SET @tablename = N'authors'

table_loop:

    IF (@@FETCH_STATUS <> -2)

    BEGIN

        SELECT @tablename = RTRIM(UPPER(@tablename))

        EXEC ("SELECT """ + @tablename + """ = COUNT(*) FROM "

                + @tablename )

        PRINT " "

    END

    FETCH NEXT FROM tnames_cursor INTO @tablename

IF (@@FETCH_STATUS <> -1) GOTO table_loop

GO

See Also
BEGIN…END | IF…ELSE
BREAK | WAITFOR
CONTINUE | WHILE
Control-of-Flow Language |


GRANT

Creates an entry in the security system that allows a user in the current database to work with data in the current database or execute specific Transact-SQL statements.

Syntax

Statement permissions:

GRANT {ALL | statement[,…n]}
TO security_account[,…n]

Object permissions:

GRANT
{ALL [PRIVILEGES] | permission[,…n]}
{
[(column[,…n])] ON {table | view}
| ON {table | view}[(column[,…n])]
| ON {stored_procedure | extended_procedure}
}
TO security_account[,…n]
[WITH GRANT OPTION]
[AS {group | role}]

Arguments
ALL
Specifies that all applicable permissions are being granted. For statement permissions, ALL can be used only by members of the sysadmin role. For object permissions, ALL can be used by members of the sysadmin and db_owner roles, and database object owners.
statement
Is the statement for which permission is being granted. The statement list can include:
  • CREATE DATABASE
  • CREATE DEFAULT
  • CREATE PROCEDURE
  • CREATE RULE
  • CREATE TABLE
  • CREATE VIEW
  • BACKUP DATABASE
  • BACKUP LOG
n
A placeholder indicating that the item can be repeated in a comma-separated list.
TO
Specifies the security account list.
security_account
Is the security account to which the permissions are applied. The security account can be a:
  • Microsoft® SQL Server™ user.
  • SQL Server role.
  • Microsoft Windows NT® user.
  • Windows NT group.

When a permission is granted to a SQL Server user or Windows NT user account, the specified security_account is the only account affected by the permission. If a permission is granted to a SQL Server role or a Windows NT group, the permission affects all users in the current database who are members of the group or role. If there are permission conflicts between a group or role and its members, the most restrictive permission (DENY) takes precedence. security_account must exist in the current database; permissions cannot be granted to a user, role, or group in another database, unless the user has already been created or given access to the current database.

Two special security accounts can be used with GRANT. Permissions granted to the public role are applied to all users in the database. Permissions granted to the guest user are used by all users who do not have a user account in the database.

When granting permissions to a Windows NT local or global group, specify the domain or computer name the group is defined on, followed by a backslash, then the group name. However, to grant permissions to a Windows NT built-in local group, specify BUILTIN instead of the domain or computer name.

PRIVILEGES
Is an optional keyword that can be included for SQL-92 compliance.
permission
Is an object permission that is being granted. When permissions are granted on a table or a view, the permission list can include one or more of these statements: SELECT, INSERT, DELETE, or UPDATE.

Object permissions granted on a table can also include REFERENCES, and object permissions granted on a procedure can include EXECUTE. When permissions are granted on columns, the permissions list can include SELECT or UPDATE. When permissions are granted on stored procedures, the permissions list can include only EXECUTE.

When a user adds a row to a table with a FOREIGN KEY constraint, or changes data in a column with a FOREIGN KEY constraint, SQL Server must validate the data in the column with the data referenced in the FOREIGN KEY constraint. If the user does not have SELECT permissions on the referenced column or table, the REFERENCES permission for the column must be granted to the user. The REFERENCES permission cannot be granted for a system table.

column
Is the name of a column in the current database for which permissions are being granted.
table
Is the name of the table in the current database for which permissions are being granted.
view
Is the name of the view in the current database for which permissions are being granted.
stored_procedure
Is the name of the stored procedure in the current database for which permissions are being granted.
extended_procedure
Is the name of the extended stored procedure for which permissions are being granted.
WITH GRANT OPTION
Specifies that the security_account is given the ability to grant the specified object permission to the other security accounts. The WITH GRANT OPTION clause is valid only with object permissions.
AS {group | role}
Specifies the optional name of the security account in the current database that has the authority to execute the GRANT statement. AS is used when permissions on an object are granted to a group or role, and the object permissions need to be further granted to users who are not members of the group or role. Because only a user, rather than a group or role, can execute a GRANT statement, a specific member of the group or role grants permissions on the object under the authority of the group or role.
Remarks

Cross-database permissions are not allowed; permissions can be granted only to users in the current database for objects and statements in the current database. If a user needs permissions to objects in another database, create the user account in the other database, or grant the user account access to the other database, as well as the current database.

Note System stored procedures are the exception because EXECUTE permissions are already granted to the public role, allowing everyone to execute them. However, after a system stored procedure is executed, it checks the user’s role membership. If the user is not a member of the appropriate fixed server or database role necessary to run the stored procedure, the stored procedure does not continue.

The REVOKE statement can be used to remove granted permissions, and the DENY statement can be used to prevent a user from gaining permissions through a GRANT to their user account.

A granted permission removes the denied or revoked permission at the level granted (user, group, or role). The same permission denied at another level such as group or role containing the user takes precedence. However, although the same permission revoked at another level still applies, it does not prevent the user from accessing the object.

If a user activates an application role, the effect of GRANT is null for any objects the user accesses using the application role. Therefore, although a user may be granted access to a specific object in the current database, if the user uses an application role that does not have access to the object, the user also does not have access while the application role is activated.

The sp_helprotect system stored procedure reports permissions on a database object or user.

Permissions

GRANT permissions depend on the statement permissions being granted and the object involved in the permissions. The members of the sysadmin and db_securityadmin roles can grant any permissions in any database. Object owners can grant permissions for the objects they own. The db_owner role can grant any permissions on any object in the database it owns.

Statements that require permissions are those that add objects in the database or perform administrative activities with the database. Each statement that requires permissions has a certain set of roles that automatically have permissions to execute the statement. For example, the CREATE TABLE permission defaults to members of the sysadmin and db_owner and db_ddladmin roles. The permissions to execute the SELECT statement for a table default to the sysadmin and db_owner roles, and the owner of the object.

There are some Transact-SQL statements that cannot be granted as permissions; the ability to execute these statements require membership in a fixed role that has implied permissions to execute special statements. For example, to execute the SHUTDOWN statement, the user must be added as member of the serveradmin role.

Members of the dbcreator, processadmin, securityadmin, and serveradmin fixed server roles have permissions to execute only these Transact-SQL statements.

Statement | dbcreator | process admin | security admin | server admin
ALTER DATABASE | X |  |  |
CREATE DATABASE | X |  |  |
DBCC |  |  |  | X (1)
DENY |  |  | X (2) |
GRANT |  |  | X (2) |
KILL |  | X |  |
RECONFIGURE |  |  |  | X
RESTORE | X |  |  |
REVOKE |  |  | X (2) |
SHUTDOWN |  |  |  | X
(1) For more information, see the DBCC statement.
(2) Applies to the CREATE DATABASE statement only.

Note Members of the diskadmin and setupadmin fixed server roles do not have permissions to execute any Transact-SQL statements, only certain system stored procedures. Members of the sysadmin fixed server role, however, have permissions to execute all Transact-SQL statements.

Members of the following fixed database roles have permissions to execute the specified Transact-SQL statements.

Statement | db_ owner | db_ data reader | db_ data writer | db_ ddl admin | db_ backup operator | db_ securityadmin
ALTER DATABASE | X |  |  | X |  |
ALTER PROCEDURE | X |  |  | X |  |
ALTER TABLE | X (1) |  |  | X |  |
ALTER TRIGGER | X |  |  | X |  |
ALTER VIEW | X (1) |  |  | X |  |
BACKUP | X |  |  |  | X |
CHECKPOINT | X |  |  |  | X |
CREATE DEFAULT | X |  |  | X |  |
CREATE INDEX | X (1) |  |  | X |  |
CREATE PROCEDURE | X |  |  | X |  |
CREATE RULE | X |  |  | X |  |
CREATE SCHEMA | X |  |  | X |  |
CREATE TABLE | X |  |  | X |  |
CREATE TRIGGER | X (1) |  |  | X |  |
CREATE VIEW | X |  |  | X |  |
DBCC | X |  |  |  | X (2) |
DELETE | X (1) |  | X |  |  |
DENY | X |  |  |  |  | X
DENY on object | X |  |  |  |  |
DROP | X (1) |  |  | X |  |
EXECUTE | X (1) |  |  |  |  |
GRANT | X |  |  |  |  | X
GRANT on object | X (1) |  |  |  |  |
INSERT | X (1) |  | X |  |  |
READTEXT | X (1) | X |  |  |  |
REFERENCES | X (1) |  |  | X |  |
RESTORE | X |  |  |  |  |
REVOKE | X |  |  |  |  | X
REVOKE on object | X (1) |  |  |  |  |
SELECT | X (1) | X |  |  |  |
SETUSER | X |  |  |  |  |
TRUNCATE TABLE | X (1) |  | X |  |  |
UPDATE | X (1) |  | X |  |  |
UPDATE STATISTICS | X (1) |  |  |  |  |
UPDATETEXT | X (1) |  | X |  |  |
WRITETEXT | X (1) |  | X |  |  |
1 Permission applies to the object owner as well.
2 For more information, see the DBCC statement.

Note Members of the db_accessadmin fixed database role do not have permissions to execute any Transact-SQL statements, only certain system stored procedures.

The Transact-SQL statements that do not require permissions to be executed (automatically granted to public) are:

BEGIN TRANSACTION | COMMIT TRANSACTION
PRINT | RAISERROR
ROLLBACK TRANSACTION | SAVE TRANSACTION
SET |

For more information about the permissions required to execute the system stored procedures, see the appropriate system stored procedure.

Examples
A. Grant statement permissions

This example grants multiple statement permissions to the users Mary and John, and the Corporate\BobJ Windows NT group.

GRANT CREATE DATABASE, CREATE TABLE

TO Mary, John, [Corporate\BobJ]

B. Grant object permissions within the permission hierarchy

This example shows the preferred ordering of permissions. First, SELECT permissions are granted to the public role. Then, specific permissions are granted to users Mary, John, and Tom. These users then have all permissions to the authors table.

USE pubs

GO

GRANT SELECT

ON authors

TO public

GO

GRANT INSERT, UPDATE, DELETE

ON authors

TO Mary, John, Tom

GO

C. Grant permissions to a SQL Server role

This example grants CREATE TABLE permissions to all members of the Accounting role.

GRANT CREATE TABLE TO Accounting

D. Grant permissions using the AS option

The Plan_Data table is owned by the user Jean. Jean grants SELECT permissions, specifying the WITH GRANT OPTION clause, on Plan_Data to the Accounting role. The user Jill, who is member of Accounting, wants to grant SELECT permissions on the Plan_Data table to the user Jack, who is not a member of Accounting.

Because the permission to GRANT other users SELECT permissions to the Plan_Data table were granted to the Accounting role and not Jill explicitly, Jill cannot grant permissions for the table based on the permissions granted through being a member of the Accounting role. Jill must use the AS clause to assume the grant permissions of the Accounting role.

/* User Jean */

GRANT SELECT ON Plan_Data TO Accounting WITH GRANT OPTION

/* User Jill */

GRANT SELECT ON Plan_Data TO Jack AS Accounting

See Also
REVOKE | DENY
sp_addgroup | sp_dropgroup
sp_addlogin | sp_dropuser
sp_adduser | sp_helpgroup
sp_changedbowner | sp_helprotect
sp_changegroup | sp_helpuser


GROUP BY

Divides a table into groups. Groups can consist of column names or results or computed columns. For more information, see SELECT.


GROUPING

Is an aggregate function that causes an additional column to be output with a value of 1 when the row is added by either the CUBE or ROLLUP operator, or 0 when the row is not the result of CUBE or ROLLUP.

Grouping is allowed only in the select list associated with a GROUP BY clause that contains either the CUBE or ROLLUP operator.

Syntax

GROUPING(column_name)

Arguments
column_name
Is a column in a GROUP BY clause to check for CUBE or ROLLUP null values.
Return Types

int

Remarks

Grouping is used to distinguish the null values returned by CUBE and ROLLUP from standard null values. The NULL returned as the result of a CUBE or ROLLUP operation is a special use of NULL. It acts as a column placeholder in the result set and means “all.”

Examples

This example groups royalty and aggregate advance amounts. The GROUPING function is applied to the royalty column.

USE pubs

SELECT royalty, SUM(advance) 'total advance',
    GROUPING(royalty) 'grp'
    FROM titles
    GROUP BY royalty WITH ROLLUP

The result set shows two null values under royalty. The first NULL represents the group of null values from this column in the table. The second NULL is in the summary row added by the ROLLUP operation. The summary row shows the total advance amounts for all royalty groups and is indicated by 1 in the grp column.

Here is the result set:

royalty        total advance               grp

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

NULL           NULL                     0

10             57000.0000               0

12             2275.0000                0

14             4000.0000                0

16             7000.0000                0

24             25125.0000               0

NULL           95400.0000               1

See Also
SELECT Aggregate Functions


HAVING

Specifies a search condition for a group or an aggregate. HAVING can be used only with the SELECT statement. It is usually used in a GROUP BY clause. When GROUP BY is not used, HAVING behaves like a WHERE clause. For more information, see SELECT.


HOST_ID

Returns the workstation identification number.

Syntax

HOST_ID( )

Return Types

char(8)

Remarks

When the parameter to a system function is optional, the current database, host computer, server user, or database user is assumed. Built-in functions must always be followed by parentheses.

System functions can be used in the select list, in the WHERE clause, and anywhere an expression is allowed.

Examples

This example creates a table that uses HOST_ID() in a DEFAULT definition to record the terminal ID of computers that insert rows into a table recording orders.

CREATE TABLE Orders

    (OrderID     INT       PRIMARY KEY,

     CustomerID  NCHAR(5)  REFERENCES Customers(CustomerID),

     TerminalID  CHAR(8)   NOT NULL DEFAULT HOST_ID(),

     OrderDate   DATETIME  NOT NULL,

     ShipDate    DATETIME  NULL,

     ShipperID   INT       NULL REFERENCES Shippers(ShipperID))

GO

See Also
Expressions System Functions


HOST_NAME

Returns the workstation name.

Syntax

HOST_NAME( )

Return Types

nchar

Remarks

When the parameter to a system function is optional, the current database, host computer, server user, or database user is assumed. Built-in functions must always be followed by parentheses.

System functions can be used in the select list, in the WHERE clause, and anywhere an expression is allowed.

Examples

This example creates a table that uses HOST_NAME() in a DEFAULT definition to record the workstation name of computers that insert rows into a table recording orders.

CREATE TABLE Orders

    (OrderID     INT        PRIMARY KEY,

     CustomerID  NCHAR(5)   REFERENCES Customers(CustomerID),

     Workstation NCHAR(30)  NOT NULL DEFAULT HOST_NAME(),

     OrderDate   DATETIME   NOT NULL,

     ShipDate    DATETIME   NULL,

     ShipperID   INT        NULL REFERENCES Shippers(ShipperID))

See Also
Expressions System Functions


IDENT_INCR

Returns the increment value (returned as numeric(@@MAXPRECISION,0)) specified during the creation of an identity column in a table or view that has an identity column.

Syntax

IDENT_INCR('table_or_view')

Arguments
'table_or_view'
Is an expression specifying the table or view to check for a valid identity increment value. table_or_view can be a character string constant enclosed in quotation marks, a variable, a function, or a column name. table_or_view is char, nchar, varchar, or nvarchar.
Return Types

numeric

Examples

This example returns 1 for the jobs table in the pubs database because the jobs table includes an identity column with an increment value of 1.

USE pubs

SELECT TABLE_NAME, IDENT_INCR(TABLE_NAME) AS IDENT_INCR

FROM INFORMATION_SCHEMA.TABLES

WHERE IDENT_INCR(TABLE_NAME) IS NOT NULL

Here is the result set:

TABLE_NAME                                                  IDENT_INCR

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

jobs                                                         1

(1 row(s) affected)

See Also
Expressions System Functions


IDENT_SEED

Returns the seed value (returned as numeric(@@MAXPRECISION,0)) specified during the creation of an identity column in a table or a view that has an identity column.

Syntax

IDENT_SEED('table_or_view')

Arguments
'table_or_view'
Is an expression specifying the table or view to check for a valid identity seed value. table_or_view can be a character string constant enclosed in quotation marks, a variable, a function, or a column name. table_or_view is char, nchar, varchar, or nvarchar.
Return Types

numeric

Examples

This example returns 1 for the jobs table in the pubs database because the jobs table includes an identity column with a seed value of 1.

USE pubs

SELECT TABLE_NAME, IDENT_SEED(TABLE_NAME) AS IDENT_SEED

FROM INFORMATION_SCHEMA.TABLES

WHERE IDENT_SEED(TABLE_NAME) IS NOT NULL

Here is the result set:

TABLE_NAME                                                   IDENT_SEED

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

jobs                                                         1

(1 row(s) affected)

See Also
Expressions System Functions


IDENTITY (Property)

Creates an identity column in a table. This property is used with the CREATE TABLE and ALTER TABLE Transact-SQL statements.

Note The IDENTITY property is not the same as the SQL-DMO Identity property that exposes the row identity property of a column.

Syntax

IDENTITY [(seed, increment )

Arguments
seed
Is the value that is used for the very first row loaded into the table.
increment
Is the incremental value that is added to the identity value of the previous row that was loaded.

You must specify both the seed and increment or neither. If neither is specified, the default is (1,1).

Remarks

If an identity column exists for a table with frequent deletions, gaps can occur between identity values. If this is a concern, do not use the IDENTITY property. However, to ensure that no gaps have been created or to fill an existing gap, evaluate the existing identity values before explicitly entering one with SET IDENTITY_INSERT ON.

If you are reusing a removed identity value, use the sample code in Example B to check for the next available identity value. Replace tablename, column_type, and max(column_type) - 1 with your table name, identity column data type, and numeric value of the maximum allowable value (for that data type) -1.

Use DBCC CHECKIDENT to check the current identity value and compare it with the maximum value in the identity column.

When the IDENTITY property is used with CREATE TABLE, Microsoft® SQL Server™ uses the NOT FOR REPLICATION option of CREATE TABLE to override the automatic incrementing of an identity column. Usually, SQL Server assigns each new row inserted in a table a value that is some increment greater than the previous highest value. However, if the new rows are replicated from another data source, the identity values must remain exactly as they were at the data source.

Examples
A. Use the IDENTITY property with CREATE TABLE

This example creates a new table using the IDENTITY property for an automatically incrementing identification number.

USE pubs

IF EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES

        WHERE TABLE_NAME = 'new_employees')

    DROP TABLE new_employees

GO

CREATE TABLE new_employees

(

 id_num int IDENTITY(1,1),

 fname varchar (20),

 minit char(1),

 lname varchar(30)

)

INSERT new_employees

    (fname, minit, lname)

VALUES

    ('Karin', 'F', 'Josephs')

INSERT new_employees

    (fname, minit, lname)

VALUES

    ('Pirkko', 'O', 'Koskitalo')

B. Use generic syntax for finding gaps in identity values

This example shows generic syntax for finding gaps in identity values when data is removed.

Note The first part of the following Transact-SQL script is designed for illustration purposes only. You can run the Transact-SQL script that starts with the comment: - - Create the img table.

-- Here is the generic syntax for finding identity value gaps in data.

-- This is the beginning of the illustrative example.

SET IDENTITY_INSERT tablename ON

DECLARE @minidentval column_type

DECLARE @nextidentval column_type

SELECT @minidentval = MIN(IDENTITYCOL) FROM tablename

IF @minidentval = IDENT_SEED('tablename')

SELECT @nextidentval = MIN(IDENTITYCOL) + IDENT_INCR('tablename')

FROM tablename t1

WHERE IDENTITYCOL BETWEEN IDENT_SEED('tablename') AND

MAX(column_type) AND

NOT EXISTS (SELECT * FROM tablename t2

WHERE t2.IDENTITYCOL = t1.IDENTITYCOL +

IDENT_INCR('tablename'))

ELSE

SELECT @nextidentval = IDENT_SEED('tablename')

SET IDENTITY_INSERT tablename OFF

-- Here is an example to find gaps in the actual data.

-- The table is called img and has two columns: the first column

-- called id_num, which is an increasing identification number, and the

-- second column called company_name.

-- This the end of the illustration example.

-- Create the img table.

-- If the img table already exists, drop it.

-- Create the img table.

IF EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES

        WHERE TABLE_NAME = 'img')

    DROP TABLE img

GO

CREATE TABLE img (id_num int IDENTITY(1,1), company_name sysname)

INSERT img(company_name) VALUES ('New Moon Books')

INSERT img(company_name) VALUES ('Lucerne Publishing')

-- SET IDENTITY_INSERT ON and use in img table.

SET IDENTITY_INSERT img ON

DECLARE @minidentval smallint

DECLARE @nextidentval smallint

SELECT @minidentval = MIN(IDENTITYCOL) FROM img

 IF @minidentval = IDENT_SEED('img')

     SELECT @nextidentval = MIN(IDENTITYCOL) + IDENT_INCR('img')

     FROM img t1

     WHERE IDENTITYCOL BETWEEN IDENT_SEED('img') AND 32766 AND

        NOT     EXISTS (SELECT * FROM img t2

             WHERE t2.IDENTITYCOL = t1.IDENTITYCOL + IDENT_INCR('img'))

 ELSE

     SELECT @nextidentval = IDENT_SEED('img')

SET IDENTITY_INSERT img OFF

See Also
ALTER TABLE | @@IDENTITY
CREATE TABLE | IDENTITY (Function)
DBCC CHECKIDENT | SELECT
IDENT_INCR | SET IDENTITY_INSERT
IDENT_SEED |


IDENTITY (Function)

Is used only in a SELECT statement with an INTO table clause to insert an identity column into a new table.

Although similar, the IDENTITY function is not the IDENTITY property that is used with CREATE TABLE and ALTER TABLE.

Syntax

IDENTITY(data_type[, seed, increment]) AS column_name

Arguments
data_type
Is the data type of the identity column. Valid data types for an identity column are any data types of the integer data type category (except for the bit data type), or decimal data type.
seed
Is the value to be assigned to the first row in the table. Each subsequent row is assigned the next identity value, which is equal to the last IDENTITY value plus the increment value. If neither seed nor increment is specified, both default to 1.
increment
Is the increment to add to the seed value for successive rows in the table.
column_name
Is the name of the column that is to be inserted into the new table.
Return Types

Returns the same as data_type.

Remarks

Because this function creates a column in a table, a name for the column must be specified in the select list in one of these ways:

--(1)

SELECT IDENTITY(int, 1,1) AS ID_Num
INTO NewTable
FROM OldTable

--(2)

SELECT ID_Num = IDENTITY(int, 1, 1)
INTO NewTable

FROM OldTable

Examples

This example inserts all rows from the employee table from the pubs database into a new table called employees. The IDENTITY function is used to start identification numbers at 100 instead of 1 in the employees table.

USE pubs

IF EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES

        WHERE TABLE_NAME = 'employees')

    DROP TABLE employees

GO

EXEC sp_dboption 'pubs', 'select into/bulkcopy', 'true'

SELECT emp_id AS emp_num,

    fname AS first,

    minit AS middle,

    lname AS last,

    IDENTITY(smallint, 100, 1) AS job_num,

    job_lvl AS job_level,

    pub_id,

    hire_date

INTO employees

FROM employee

GO

USE pubs

EXEC sp_dboption 'pubs', 'select into/bulkcopy', 'false'

See Also
CREATE TABLE | IDENTITY (Property)
@@IDENTITY | SELECT @local_variable


IF…ELSE

Imposes conditions on the execution of a Transact-SQL statement. The Transact-SQL statement following an IF keyword and its condition is executed if the condition is satisfied (when the Boolean expression returns TRUE). The optional ELSE keyword introduces an alternate Transact-SQL statement that is executed when the IF condition is not satisfied (when the Boolean expression returns FALSE).

Syntax

IF Boolean_expression
{sql_statement | statement_block}
[ELSE
{sql_statement | statement_block}]

Arguments
Boolean_expression
Is an expression that returns TRUE or FALSE. If the Boolean expression contains a SELECT statement, the SELECT statement must be enclosed in parentheses.
{sql_statement | statement_block}
Is any Transact-SQL statement or statement grouping as defined with a statement block. Unless a statement block is used, the IF or ELSE condition can affect the performance of only one Transact-SQL statement. To define a statement block, use the control-of-flow keywords BEGIN and END. CREATE TABLE or SELECT INTO statements must refer to the same table name if the CREATE TABLE or SELECT INTO statements are used in both the IF and ELSE areas of the IF…ELSE block.
Remarks

IF…ELSE constructs can be used in batches, in stored procedures (in which these constructs are often used to test for the existence of some parameter), and in ad hoc queries.

IF tests can be nested, either after another IF or following an ELSE. There is no limit to the number of nested levels.

Examples
A. Use one IF…ELSE block

This example shows an IF condition with a statement block. If the average price of the title is not less than $15, it prints the text: Average title price is more than $15.

USE pubs

IF (SELECT AVG(price) FROM titles WHERE type = 'mod_cook') < $15

BEGIN

    PRINT 'The following titles are excellent mod_cook books:'

    PRINT ' '

    SELECT SUBSTRING(title, 1, 35) AS Title

    FROM titles

    WHERE type = 'mod_cook'

END

ELSE

    PRINT 'Average title price is more than $15.'

Here is the result set:

The following titles are excellent mod_cook books:

Title

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

Silicon Valley Gastronomic Treats

The Gourmet Microwave

(2 row(s) affected)

B. Use more than one IF…ELSE block

This example uses two IF blocks. If the average price of the title is not less than $15, it prints the text: Average title price is more than $15. If the average price of modern cookbooks is more than $15, the statement that the modern cookbooks are expensive is printed.

USE pubs

IF (SELECT AVG(price) FROM titles WHERE type = 'mod_cook') < $15

BEGIN

    PRINT 'The following titles are excellent mod_cook books:'

    PRINT ' '

    SELECT SUBSTRING(title, 1, 35) AS Title

    FROM titles

    WHERE type = 'mod_cook'

END

ELSE

    IF (SELECT AVG(price) FROM titles WHERE type = 'mod_cook') > $15

BEGIN

    PRINT 'The following titles are expensive mod_cook books:'

    PRINT ' '

    SELECT SUBSTRING(title, 1, 35) AS Title

    FROM titles

    WHERE type = 'mod_cook'

END

See Also
SELECT | CREATE TABLE
CREATE TRIGGER | ALTER TRIGGER
ELSE (IF…ELSE) | BEGIN…END
END (BEGIN…END) | WHILE


image

For information about the image data type, see ntext, text, and image.

See Also
Data Types


IN

Determines if a given value matches any value in a subquery or a list.

Syntax

test_expression [NOT] IN
(
subquery
| expression [,…n]
)

Arguments
test_expression
Is any valid Microsoft® SQL Server™ expression.
subquery
Is a subquery that has a result set of one column. This column must have the same data type as test_expression.
expression [,…n]
Is a list of expressions to test for a match. All expressions must be of the same type as test_expression.
Result Type

Boolean

Result Value

If the value of test_expression is equal to any value returned by subquery or is equal to any expression from the comma separated list, the result value is TRUE. Otherwise, the result value is FALSE.

Using NOT IN negates the returned value.

Examples
A. Compare OR and IN

This example selects a list of the names and states of all authors who live in California, Indiana, or Maryland.

USE pubs

SELECT au_lname, state

FROM authors

WHERE state = 'CA' OR state = 'IN' OR state = 'MD'

However, you get the same results using IN:

USE pubs

SELECT au_lname, state

FROM authors

WHERE state IN ('CA', 'IN', 'MD')

Here is the result set from either query:

au_lname    state

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

White       CA

Green       CA

Carson       CA

O'Leary       CA

Straight       CA

Bennet       CA

Dull       CA

Gringlesby       CA

Locksley       CA

Yokomoto       CA

DeFrance       IN

Stringer       CA

MacFeather       CA

Karsen       CA

Panteley               MD

Hunter               CA

McBadden               CA

(17 row(s) affected)

B. Use IN with a subquery

This example finds all au_ids in the titleauthor table for authors who make less than 50 percent of the royalty on any one book, and then selects from the authors table all author names with au_ids that match the results from the titleauthor query. The results show that several authors fall into the less-than-50-percent category.

USE pubs

SELECT au_lname, au_fname

FROM authors

WHERE au_id IN

    (SELECT au_id

    FROM titleauthor

    WHERE royaltyper < 50)

Here is the result set:

au_lname                                 au_fname

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

Green                                    Marjorie

O'Leary                                  Michael

Gringlesby                               Burt

Yokomoto                                 Akiko

MacFeather                               Stearns

Ringer                                   Anne

(6 row(s) affected)

C. Use NOT IN with a subquery

NOT IN finds the authors who do not match the items in the values list. This example finds the names of authors who do not make less than 50 percent of the royalties on at least one book.

USE pubs

SELECT au_lname, au_fname

FROM authors

WHERE au_id NOT IN

    (SELECT au_id

    FROM titleauthor

    WHERE royaltyper < 50)

Here is the result set:

au_lname                                 au_fname

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

White                                    Johnson

Carson                                   Cheryl

Straight                                 Dean

Smith                                    Meander

Bennet                                   Abraham

Dull                                     Ann

Locksley                                 Charlene

Greene                                   Morningstar

Blotchet-Halls                           Reginald

del Castillo                             Innes

DeFrance                                 Michel

Stringer                                 Dirk

Karsen                                   Livia

Panteley                                 Sylvia

Hunter                                   Sheryl

McBadden                                 Heather

Ringer                                   Albert

(17 row(s) affected)

See Also
CASE | Operators
Expressions | SELECT
Functions | WHERE


INDEXPROPERTY

Returns the named index property value given a table identification number, index name, and property name.

Syntax

INDEXPROPERTY(table_ID, index, property)

Arguments
table_ID
Is an expression containing the identification number of the table for which to provide index property information. table_ID is int.
index
Is an expression containing the name of the index for which to return property information. index is nvarchar(128).
property
Is an expression containing the name of the database property to return. property is varchar(128), and can be one of these values.

Value | Description | Value returned
IndexDepth | Depth of the index. | Number of levels the index has.
IsAutoStatistics Index was generated by the auto create statistics option of sp_dboption. 1 = True
0 = False
NULL = Invalid input
IsClustered Index is clustered. 1 = True
0 = False
NULL = Invalid input
IsStatistics Index was created by the CREATE STATISTICS statement or by the auto create statistics option of sp_dboption. Statistics indexes are used as a placeholder for column-level statistics. 1 = True
0 = False
NULL = Invalid input
IsUnique Index is unique. 1 = True
0 = False
NULL = Invalid input
IndexFillFactor | Index specifies its own fill factor. | Fill factor used when the index was created or last rebuilt.
IsPadIndex Index specifies space to leave open on each interior node. 1 = True
0 = False
NULL = Invalid input
IsFulltextKey Index is the full-text key for a table. 1 = True
0 = False
NULL = Invalid input
IsHypothetical Index is hypothetical and cannot be used directly as a data access path. Hypothetical indexes hold column level statistics. 1 = True
0 = False
NULL = Invalid input

Return Types

int

Examples

This example returns the setting for the IsPadIndex property for the UPKCL_auidind index of the authors table.

USE pubs

SELECT INDEXPROPERTY(OBJECT_ID('authors'), 'UPKCL_auidind',

    'IsPadIndex')

See Also
Control-of-Flow Language Operators (Logical Operators)


INDEX_COL

Returns the indexed column name.

Syntax

INDEX_COL('table', index_id, key_id)

Arguments
'table'
Is the name of the table.
index_id
Is the ID of the index.
key_id
Is the ID of the key.
Return Types

nchar

Examples

This example produces a list of indexes in the authors table.

USE pubs

-- Declare variables to use in this example.

DECLARE @id int, @type char(2),@msg varchar(80),

    @indid smallint, @indname sysname, @status int,

    @indkey int, @name varchar(30)

-- Obtain the identification number for the authors table to look up

-- its indexes in the sysindexes table.

SET NOCOUNT ON

SELECT @id = id, @type = type

FROM sysobjects

WHERE name = 'authors' and type = 'U'

-- Start printing the output information.

print 'Index information for the authors table'

print '---------------------------------------'

-- Loop through all indexes in the authors table.

-- Declare a cursor.

DECLARE i cursor

FOR

SELECT indid, name, status

FROM sysindexes

WHERE id = @id

-- Open the cursor and fetch next set of index information.

OPEN i

FETCH NEXT FROM i INTO @indid, @indname, @status

    IF @@FETCH_STATUS = 0

    PRINT ' '

    -- While there are still rows to retrieve from the cursor,

    -- find out index information and print it.

    WHILE @@FETCH_STATUS = 0

     BEGIN

     SET @msg = NULL

     -- Print the index name and the index number.

          SET @msg = ' Index number '  + CONVERT(varchar, @indid)+

        ' is '+@indname

     SET @indkey = 1

     -- @indkey (equivalent to key_id in the syntax diagram of

     -- INDEX_COL) can be from 1 to 16.

        WHILE @indkey <= 16 and INDEX_COL(@name, @indid, @indkey)

        IS NOT NULL

        BEGIN

        -- Print different information if @indkey <> 1.

         IF @indkey = 1

            SET @msg = @msg + ' on '

                + index_col(@name, @indid, @indkey)

         ELSE

            SET @msg = @msg + ', '

                + index_col(@name, @indid, @indkey)

         SET @indkey = @indkey + 1

        END

      PRINT @msg

      SET @msg = NULL

      FETCH NEXT FROM i INTO @indid, @indname, @status

   END

   CLOSE i

   DEALLOCATE i

SET NOCOUNT OFF

Here is the result set:

Index information for the authors table

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

 Index number 1 is UPKCL_auidind

 Index number 2 is aunmind

See Also
Expressions | Metadata Functions
WHERE |


Information Schema Views

Microsoft® SQL Server™ provides two methods for obtaining metadata: system stored procedures or information schema views.

Note To obtain metadata, use system stored procedures, system functions, or these system-supplied views only. Querying the system tables directly may not provide accurate information if system tables are changed in future releases.

These views provide an internal, system table-independent view of the SQL Server metadata. Information schema views allow applications to work properly even though significant changes have been made to the system tables. The information schema views included in SQL Server conform to the SQL-92 Standard definition for the INFORMATION_SCHEMA.

SQL Server supports a three-part naming convention when referring to the current server. The SQL-92 standard also supports a three-part naming convention. However, the names used in both naming conventions are different. These views are defined in a special schema named INFORMATION_SCHEMA, which is contained in each database. Each INFORMATION_SCHEMA view contains metadata for all data objects stored in that particular database. This table describes the relationships between the SQL Server names and the SQL-92-standard names.

SQL Server name | Maps to this equivalent SQL-92 name
database | catalog
owner | schema
object | object
user-defined data type | domain

This naming convention mapping applies to these SQL Server SQL-92-compatible views. These views are defined in a special schema named INFORMATION_SCHEMA, which is contained in each database. Each INFORMATION_SCHEMA view contains metadata for all data objects stored in that particular database.

  • CHECK_CONSTRAINTS
  • COLUMN_DOMAIN_USAGE
  • COLUMN_PRIVILEGES
  • COLUMNS
  • CONSTRAINT_COLUMN_USAGE
  • CONSTRAINT_TABLE_USAGE
  • DOMAIN_CONSTRAINTS
  • DOMAINS
  • KEY_COLUMN_USAGE
  • REFERENTIAL_CONSTRAINTS
  • SCHEMATA
  • TABLE_CONSTRAINTS
  • TABLE_PRIVILEGES
  • TABLES
  • VIEW_COLUMN_USAGE
  • VIEW_TABLE_USAGE
  • VIEWS

In addition, some views contain references to different classes of data such as character data or binary data.

See Also
Data Types System Stored Procedures


CHECK_CONSTRAINTS

Contains one row for each CHECK constraint owned by the current user in the current database. The INFORMATION_SCHEMA.CHECK_CONSTRAINTS view is based on the sysobjects and syscomments system tables.

To retrieve information from these views, specify the fully qualified name of INFORMATION_SCHEMA view_name.

Column name | Data type | Description
CONSTRAINT_CATALOG | nvarchar(128) | Constraint qualifier
CONSTRAINT_SCHEMA | nvarchar(128) | Constraint owner
CONSTRAINT_NAME | sysname | Constraint name
CHECK_CLAUSE | nvarchar(4000) | Actual text of the Transact-SQL definition statement

See Also
syscomments sysobjects


COLUMN_DOMAIN_USAGE

Contains one row for each column owned by the current user in the current database that has a user-defined data type. The INFORMATION_SCHEMA.COLUMN_DOMAIN_USAGE view is based on the sysobjects, syscolumns, and systypes system tables.

To retrieve information from these views, specify the fully qualified name of INFORMATION_SCHEMA view_name.

Column name | Data type | Description
DOMAIN_CATALOG | nvarchar(128) | Database in which the user-defined data type exists.
DOMAIN_SCHEMA | nvarchar(128) | Username that created the user-defined data type.
DOMAIN_NAME | sysname | User-defined data type.
TABLE_CATALOG | nvarchar(128) | Table qualifier.
TABLE_SCHEMA | nvarchar(128) | Table owner.
TABLE_NAME | sysname | Table in which the user-defined data type is used.
COLUMN_NAME | sysname | Column using the user-defined data type.

See Also
syscomments | systypes
sysobjects |


COLUMN_PRIVILEGES

Contains one row for each column with a privilege either granted to or by the current user in the current database. The INFORMATION_SCHEMA.COLUMN_PRIVILEGES view is based on the sysprotects, sysobjects, and syscolumns system tables.

To retrieve information from these views, specify the fully qualified name of INFORMATION_SCHEMA view_name.

Column name | Data type | Description
GRANTOR | nvarchar(128) | Privilege grantor.
GRANTEE | nvarchar(128) | Privilege grantee.
TABLE_CATALOG | nvarchar(128) | Table qualifier.
TABLE_SCHEMA | nvarchar(128) | Table owner.
TABLE_NAME | sysname | Table name.
COLUMN_NAME | sysname | Column name.
PRIVILEGE_TYPE | varchar(10) | Type of privilege.
IS_GRANTABLE | varchar(3) | Specifies whether the grantee has the ability to grant permissions to others.

See Also
syscomments | sysprotects
sysobjects |


COLUMNS

Contains one row for each column accessible to the current user in the current database. The INFORMATION_SCHEMA.COLUMNS view is based on the sysobjects, spt_data type_info, systypes, syscolumns, syscomments, sysconfigures, and syscharsets system tables.

To retrieve information from these views, specify the fully qualified name of INFORMATION_SCHEMA view_name.

Column name | Data type | Description
TABLE_CATALOG | nvarchar(128) | Table qualifier.
TABLE_SCHEMA | nvarchar(128) | Table owner.
TABLE_NAME | nvarchar(128) | Table name.
COLUMN_NAME | nvarchar(128) | Column name.
ORDINAL_POSITION | smallint | Column identification number.
COLUMN_DEFAULT | nvarchar(4000) | Default value of the column.
IS_NULLABLE | varchar(3) | Nullability of the column. If this column allows NULL, this column returns YES. Otherwise, NO is returned.
DATA_TYPE | nvarchar(128) | System-supplied data type.
CHARACTER_ MAXIMUM_LENGTH | smallint | Maximum length, in characters, for binary data, character data, or text and image data. Otherwise, NULL is returned. For more information, see Data Types.
CHARACTER_ OCTET_LENGTH | smallint | Maximum length, in bytes, for binary data, character data, or text and image data. Otherwise, NULL is returned.
NUMERIC_PRECISION | tinyint | Precision of approximate numeric data, exact numeric data, integer data, or monetary data. Otherwise, NULL is returned.
NUMERIC_ PRECISION_RADIX | smallint | Precision radix of approximate numeric data, exact numeric data, integer data, or monetary data. Otherwise, NULL is returned.
NUMERIC_SCALE | tinyint | Scale of approximate numeric data, exact numeric data, integer data, or monetary data. Otherwise, NULL is returned.
DATETIME_PRECISION | smallint | Subtype code for datetime and SQL-92 interval data types. For other data types, NULL is returned.
CHARACTER_ SET_CATALOG | varchar(6) | Returns master, indicating the database in which the character set is located, if the column is character data or text data type. Otherwise, NULL is returned.
CHARACTER_ SET_SCHEMA | varchar(3) | Returns DBO, indicating the owner name of the character set, if the column is character data or text data type. Otherwise, NULL is returned.
CHARACTER_ SET_NAME | nvarchar(128) | Returns the unique name for the character set if this column is character data or text data type. Otherwise, NULL is returned.
COLLATION_CATALOG | varchar(6) | Returns master, indicating the database in which the sort order is defined, if the column is character data or text data type. Otherwise, this column is NULL.
COLLATION_SCHEMA | varchar(3) | Returns DBO, indicating the owner of the sort order for character data or text data type. Otherwise, NULL is returned.
COLLATION_NAME | nvarchar(128) | Returns the unique name for the sort order if the column is character data or text data type. Otherwise, NULL is returned.
DOMAIN_CATALOG | nvarchar(128) | If the column is a user-defined data type, this column is the database name in which the user-defined data type was created. Otherwise, NULL is returned.
DOMAIN_SCHEMA | nvarchar(128) | If the column is a user-defined data type, this column is the creator of the user-defined data type. Otherwise, NULL is returned.
DOMAIN_NAME | nvarchar(128) | If the column is a user-defined data type, this column is the name of the user-defined data type. Otherwise, NULL is returned.

See Also
syscharsets | sysconfigures
syscolumns | sysobjects
syscomments | systypes


CONSTRAINT_COLUMN_USAGE

Contains one row for each column, owned by the current user in the current database, that has a constraint defined on it. The INFORMATION_SCHEMA.CONSTRAINT_COLUMN_USAGE view is based on the sysobjects, syscolumns, and systypes system tables.

To retrieve information from these views, specify the fully qualified name of INFORMATION_SCHEMA view_name.

Column name | Data type | Description
TABLE_CATALOG | nvarchar(128) | Table qualifier
TABLE_SCHEMA | nvarchar(128) | Table owner
TABLE_NAME | nvarchar(128) | Table name
COLUMN_NAME | nvarchar(128) | Column name
CONSTRAINT_CATALOG | nvarchar(128) | Constraint qualifier
CONSTRAINT_SCHEMA | nvarchar(128) | Constraint owner
CONSTRAINT_NAME | nvarchar(128) | Constraint name

See Also
syscolumns | systypes
sysobjects |


CONSTRAINT_TABLE_USAGE

Contains one row for each table, owned by the current user in the current database, that has a constraint defined on it. The INFORMATION_SCHEMA.CONSTRAINT_TABLE_USAGE view is based on the sysobjects system table.

To retrieve information from these views, specify the fully qualified name of INFORMATION_SCHEMA view_name.

Column name | Data type | Description
TABLE_CATALOG | nvarchar(128) | Table qualifier
TABLE_SCHEMA | nvarchar(128) | Table owner
TABLE_NAME | sysname | Table name
CONSTRAINT_CATALOG | nvarchar(128) | Constraint qualifier
CONSTRAINT_SCHEMA | nvarchar(128) | Constraint owner
CONSTRAINT_NAME | sysname | Constraint name

See Also
sysobjects


DOMAIN_CONSTRAINTS

Contains one row for each user-defined data type, accessible to the current user in the current database, with a rule bound to it. The INFORMATION_SCHEMA.DOMAIN_CONSTRAINTS view is based on the sysobjects and systypes system tables.

To retrieve information from these views, specify the fully qualified name of INFORMATION_SCHEMA view_name.

Column name | Data type | Description
CONSTRAINT_CATALOG | nvarchar(128) | Database in which the rule exists.
CONSTRAINT_SCHEMA | nvarchar(128) | Rule owner.
CONSTRAINT_NAME | sysname | Rule name.
DOMAIN_CATALOG | nvarchar(128) | Database in which the user-defined data type exists.
DOMAIN_SCHEMA | nvarchar(128) | User that created the user-defined data type.
DOMAIN_NAME | sysname | User-defined data type.
IS_DEFERRABLE | varchar(2) | Specifies whether constraint checking is deferrable. Always returns NO.
INITIALLY_DEFERRED | varchar(2) | Specifies whether constraint checking is initially deferred. Always returns NO.

See Also
sysobjects systypes


DOMAINS

Contains one row for each user-defined data type accessible to the current user in the current database. The INFORMATION_SCHEMA.DOMAINS view is based on the spt_data type_info, systypes, syscomments, sysconfigures, and syscharsets system tables.

To retrieve information from these views, specify the fully qualified name of INFORMATION_SCHEMA view_name.

Column name | Data type | Description
DOMAIN_CATALOG | nvarchar(128) | Database in which the user-defined data type exists.
DOMAIN_SCHEMA | nvarchar(128) | User that created the user-defined data type.
DOMAIN_NAME | sysname | User-defined data type.
DATA_TYPE | sysname | System-supplied data type .
CHARACTER_ MAXIMUM_LENGTH | smallint | Maximum length, in characters, for binary data, character data, or text and image data. Otherwise, NULL is returned. For more information, see Data Types.
CHARACTER_ OCTET_LENTH | smallint | Maximum length, in bytes, for binary data, character data, or text and image data. Otherwise, NULL is returned.
COLLATION_CATALOG | varchar(6) | Returns master, indicating the database in which the sort order is defined, if the column is character data or text data type. Otherwise, this column is NULL.
COLLATION_SCHEMA | varchar(3) | Returns DBO, indicating the owner of the sort order for character data or text data type. Otherwise, NULL is returned.
COLLATION_NAME | nvarchar(128) | Returns the unique name for the sort order if the column is character data or text data type. Otherwise, NULL is returned.
CHARACTER_ SET_CATALOG | varchar(6) | Returns master, indicating the database in which the character set is located, if the column is character data or text data type. Otherwise, NULL is returned.
CHARACTER_ SET_SCHEMA | varchar(3) | Returns DBO, indicating the owner name of the character set, if the column is character data or text data type. Otherwise, NULL is returned.
CHARACTER_ SET_NAME | nvarchar(128) | Returns the unique name for the character set if this column is character data or text data type. Otherwise, NULL is returned.
NUMERIC_PRECISION | tinyint | Precision of approximate numeric data, exact numeric data, integer data, or monetary data. Otherwise, NULL is returned.
NUMERIC_ PRECISION_RADIX | smallint | Precision radix of approximate numeric data, exact numeric data, integer data, or monetary data. Otherwise, NULL is returned.
NUMERIC_SCALE | tinyint | Scale of approximate numeric data, exact numeric data, integer data, or monetary data. Otherwise, NULL is returned.
DATETIME_PRECISION | smallint | Subtype code for datetime and SQL-92 interval data type. For other data types, this column returns a NULL.
DOMAIN_DEFAULT | nvarchar(4000) | Actual text of the definition Transact-SQL statement.

See Also
syscharsets | sysconfigures
syscomments | systypes


KEY_COLUMN_USAGE

Contains one row for each column, owned by the current user in the current database, that is constrained as a key. The INFORMATION_SCHEMA.KEY_COLUMN_USAGE view is based on the sysobjects, syscolumns, sysreferences, spt_values, and sysindexes system tables.

To retrieve information from these views, specify the fully qualified name of INFORMATION_SCHEMA view_name.

Column name | Data type | Description
CONSTRAINT_CATALOG | nvarchar(128) | Constraint qualifier
CONSTRAINT_SCHEMA | nvarchar(128) | Constraint owner name
CONSTRAINT_NAME | nvarchar(128) | Constraint name
TABLE_CATALOG | nvarchar(128) | Table qualifier
TABLE_SCHEMA | nvarchar(128) | Table owner name
TABLE_NAME | nvarchar(128) | Table name
COLUMN_NAME | nvarchar(128) | Column name
ORIGINAL_POSTION | smallint | Column ordinal position

See Also
syscolumns | sysobjects
sysindexes | sysreferences


REFERENTIAL_CONSTRAINTS

Contains one row for each foreign constraint owned by the current user in the current database. The INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS view is based on the sysreferences, sysindexes, and sysobjects system tables.

To retrieve information from these views, specify the fully qualified name of INFORMATION_SCHEMA view_name.

Column name | Data type | Description
CONSTRAINT_CATALOG | nvarchar(128) | Constraint qualifier.
CONSTRAINT_SCHEMA | nvarchar(128) | Constraint owner.
CONSTRAINT_NAME | sysname | Constraint name.
UNIQUE_CONSTRAINT_ CATALOG | nvarchar(128) | Unique constraint qualifier.
UNIQUE_CONSTRAINT_ SCHEMA | nvarchar(128) | Unique constraint owner.
UNIQUE_CONSTRAINT_ NAME | sysname | Unique constraint.
MATCH_OPTION | varchar(7) | Referential constraint-matching conditions. Always returns PARTIAL, which means that a row in the foreign key table columns matches if every value in the foreign key columns is NULL, or every value that is not NULL in the foreign key table columns matches a value in the primary key table columns.
UPDATE_RULE | varchar(9) | The action that is taken if a Transact-SQL statement violates referential integrity between tables. Always returns NO ACTION, which means that no action is performed for referential integrity actions and the Transact-SQL statement to perform changes does not execute.
DELETE_RULE | varchar(9) | The action that is taken if a Transact-SQL statement violates referential integrity between tables. Always returns NO ACTION, which means that no action is performed for referential integrity actions and the Transact-SQL statement to perform changes does not execute.

See Also
sysindexes | sysreferences
sysobjects |


SCHEMATA

Contains one row for each database that has permissions for the current user. The INFORMATION_SCHEMA.SCHEMATA view is based on the sysdatabases, sysconfigures, and syscharsets system tables.

To retrieve information from these views, specify the fully qualified name of INFORMATION_SCHEMA view_name.

Column name | Data type | Description
CATALOG_NAME | sysname | Name of the database where the current user has permissions.
SCHEMA_NAME | nvarchar(128) | Returns the name of the schema owner of object.
SCHEMA_OWNER | nvarchar(128) | Schema owner name.
DEFAULT_CHARACTER _SET_CATALOG | varchar(6) | Returns master, indicating the database where the default character set is defined.
DEFAULT_CHARACTER _SET_SCHEMA | varchar(3) | Returns DBO, indicating the name of the default character set owner.
DEFAULT_CHARACTER _SET_NAME | sysname | Returns the name of the default character set.

See Also
syscharsets | sysdatabases
sysconfigures |


TABLE_CONSTRAINTS

Contains one row for each table constraint owned by the current user in the current database. The INFORMATION_SCHEMA.TABLE_CONSTRAINTS view is based on the sysobjects system table.

To retrieve information from these views, specify the fully qualified name of INFORMATION_SCHEMA view_name.

Column name | Data type | Description
CONSTRAINT_CATALOG | nvarchar(128) | Constraint qualifier.
CONSTRAINT_SCHEMA | nvarchar(128) | Constraint owner.
CONSTRAINT_NAME | sysname | Constraint name.
TABLE_CATALOG | nvarchar(128) | Table qualifier.
TABLE_SCHEMA | nvarchar(128) | Table owner.
TABLE_NAME | sysname | Table name.
CONSTRAINT_TYPE | varchar(11) | Type of constraint. Can be either CHECK, UNIQUE, PRIMARY KEY, or FOREIGN KEY.
IS_DEFERRABLE | varchar(2) | Specifies whether constraint checking is deferrable. Always returns NO.
INITIALLY_DEFERRED | varchar(2) | Specifies whether constraint checking is initially deferred. Always returns NO.

See Also
sysobjects


TABLE_PRIVILEGES

Contains one row for each table privilege granted to or by the current user in the current database. The INFORMATION_SCHEMA.TABLE_PRIVILEGES view is based on the sysprotects and sysobjects system tables.

To retrieve information from these views, specify the fully qualified name of INFORMATION_SCHEMA view_name.

Column name | Data type | Description
GRANTOR | nvarchar(128) | Privilege grantor.
GRANTEE | nvarchar(128) | Privilege grantee.
TABLE_CATALOG | nvarchar(128) | Table qualifier.
TABLE_SCHEMA | nvarchar(128) | Table owner.
TABLE_NAME | sysname | Table name.
PRIVILEGE_TYPE | varchar(10) | Type of privilege.
IS_GRANTABLE | varchar(3) | Specifies whether the grantee has the ability to grant permissions to others.

See Also
sysobjects sysprotects


TABLES

Contains one row for each table in the current database for which the current user has permissions. The INFORMATION_SCHEMA.TABLES view is based on the sysobjects system table.

To retrieve information from these views, specify the fully qualified name of INFORMATION_SCHEMA view_name.

Column name | Data type | Description
TABLE_CATALOG | nvarchar(128) | Table qualifier.
TABLE_SCHEMA | nvarchar(128) | Table owner.
TABLE_NAME | sysname | Table name.
TABLE_TYPE | varchar(10) | Type of table. Can be VIEW or BASE TABLE.

See Also
sysobjects


VIEW_COLUMN_USAGE

Contains one row for each column owned by the current user in the current database and used in a view definition. The INFORMATION_SCHEMA.VIEW_COLUMN_USAGE is based on the sysobjects and sysdepends system tables.

To retrieve information from these views, specify the fully qualified name of INFORMATION_SCHEMA view_name.

Column name | Data type | Description
VIEW_CATALOG | nvarchar(128) | View qualifier
VIEW_SCHEMA | nvarchar(128) | View owner
VIEW_NAME | sysname | View name
TABLE_CATALOG | nvarchar(128) | Table qualifier
TABLE_SCHEMA | nvarchar(128) | Table owner
TABLE_NAME | sysname | Base table
COLUMN_NAME | sysname | Column name

See Also
sysdepends sysobjects


VIEW_TABLE_USAGE

Contains one row for each table, owned by the current user in the current database, used in a view. The INFORMATION_SCHEMA.VIEW_TABLE_USAGE view is based on the sysobjects and sysdepends system tables.

To retrieve information from these views, specify the fully qualified name of INFORMATION_SCHEMA view_name.

Column name | Data type | Description
VIEW_CATALOG | nvarchar(128) | View qualifier
VIEW_SCHEMA | nvarchar(128) | View owner
VIEW_NAME | sysname | View name
TABLE_CATALOG | nvarchar(128) | Table qualifier
TABLE_SCHEMA | nvarchar(128) | Base table owner
TABLE_NAME | sysname | Base table that the view is based on

See Also
sysdepends sysobjects


VIEWS

Contains one row for views accessible to the current user in the current database. The INFORMATION_SCHEMA.VIEWS is based on the sysobjects and syscomments system tables.

To retrieve information from these views, specify the fully qualified name of INFORMATION_SCHEMA view_name.

Column name | Data type | Description
TABLE_CATALOG | nvarchar(128) | View qualifier.
TABLE_SCHEMA | nvarchar(128) | View owner.
TABLE_NAME | nvarchar(128) | View name.
VIEW_DEFINITION | nvarchar(4000) | If the length of definition is greater than nvarchar(4000), this column is NULL; otherwise, this column is the view definition text.
CHECK_OPTION | varchar(7) | Type of WITH CHECK OPTION. Is CASCADE if the original view was created using the WITH CHECK OPTION. Otherwise, NONE is returned.
IS_UPDATABLE | varchar(2) | Specifies whether the view is updatable. Always returns NO.

See Also
syscomments


INSERT

Adds a new row to a table or a view.

Syntax

INSERT [INTO]
{
table_name [ [AS] table_alias] WITH ( <table_hint_limited> […n])
| view_name [ [AS] table_alias]
 | rowset_function_limited
}

{ [(column_list)]
{ VALUES ( { DEFAULT
| NULL
| expression
}[,…n]
)
| derived_table
| execute_statement
}
}
| DEFAULT VALUES

<table_hint_limited> ::=
{ INDEX(index_val [,…n])
| FASTFIRSTROW
| HOLDLOCK
| PAGLOCK
| READCOMMITTED
| REPEATABLEREAD
| ROWLOCK
| SERIALIZABLE
| TABLOCK
| TABLOCKX
}

Arguments
[INTO]
Is an optional keyword that can be used between INSERT and the target table.
table_name [ [AS] table_alias ]
Is the name of a table that is to receive the data.
WITH (<table_hint_limited> […n])
Specifies one or more table hints that are allowed for a target table. The WITH keyword and the parentheses are required. READPAST, NOLOCK, READUNCOMMITTED, and UPDLOCK are not allowed. For information about table hints, see FROM.
view_name [ [AS] table_alias ]
Is the name and optional alias of a view. The view referenced by view_name must be updatable. The modifications made by the INSERT statement cannot affect more than one of the base tables referenced in the FROM clause of the view. For example, an INSERT into a multi table view must use a column_list that references only columns from one base table. For more information on updatable views, see CREATE VIEW.
rowset_function_limited
Is either the OPENQUERY or OPENROWSET function. For more information, see OPENQUERY and OPENROWSET.
(column_list)
Is a list of one or more columns in which to insert data. column_list must be enclosed in parentheses and delimited by commas.

If a column is not in column_list, Microsoft® SQL Server™ must be able to provide a value based on the definition of the column; otherwise, the row cannot be loaded. SQL Server automatically provides a value for the column if the column:

  • Has an IDENTITY property. The next incremental identity value is used.
  • Has a default. The default value for the column is used.
  • Has a timestamp data type. The current timestamp value is used.
  • Is nullable. A null value is used.

column_list and VALUES list must be used when inserting explicit values into an identity column, and the SET IDENTITY_INSERT option must be ON for the table.

VALUES
Introduces the list of data values to be inserted. There must be one data value for each column in column_list (if specified) or in the table. The values list must be enclosed in parentheses.

If the values in the VALUES list are not in the same order as the columns in the table or do not have a value for each column in the table, column_list must be used to explicitly specify the column that stores each incoming value.

DEFAULT
Forces SQL Server to load the default value defined for a column. If a default does not exist for the column and the column allows NULLs, NULL is inserted. For a column defined with the timestamp data type, the next timestamp value is inserted. DEFAULT is not valid for an identity column.
expression
Is a constant, a variable, or an expression. The expression cannot contain a SELECT or EXECUTE statement.
derived_table
Is any valid SELECT statement that returns rows of data to be loaded into the table.
execute_statement
Is any valid EXECUTE statement that returns data with SELECT or READTEXT statements.

If execute_statement is used with INSERT, each result set must be compatible with the columns in the table or in column_list. execute_statement can be used to execute stored procedures on the same server or a remote server. The procedure in the remote server is executed, and the result sets are returned to the local server and loaded into the table in the local server. If execute_statement returns data with the READTEXT statement, each individual READTEXT statement can return a maximum of 1 megabyte (MB)
(1024 KB) of data. execute_statement can also be used with extended procedures, and inserts the data returned by the main thread of the extended procedure. Output from threads other than the main thread are not inserted.

DEFAULT VALUES
Forces the new row to contain the default values defined for each column.
Remarks

INSERT appends new rows to a table. To replace data in a table, the DELETE or TRUNCATE TABLE statements must be used to clear existing data before loading new data with INSERT. To modify column values in existing rows, use UPDATE. To create a new table and load it with data in one step, use the INTO option of the SELECT statement.

Columns created with the uniqueidentifier data type store specially formatted 16-byte binary values. Unlike with identity columns, SQL Server does not automatically generate values for columns with the uniqueidentifier data type. During an insert operation, variables with a data type of uniqueidentifier and string constants in the form xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx (36 characters including hyphens, where x is a hexadecimal digit in the range 0-9 or a-f) can be used for uniqueidentifier columns. For example, 6F9619FF-8B86-D011-B42D-00C04FC964FF is a valid value for a uniqueidentifier variable or column. Use the NEWID() function to obtain a globally unique ID (GUID).

When you insert rows, these rules apply:

  • If a value is being loaded into columns with a char, varchar, or varbinary data type, the padding or truncation of trailing blanks (spaces for char and varchar, zeros for varbinary) is determined by the SET ANSI_PADDING setting defined for the column when the table was created. For more information, see SET ANSI_PADDING.
    • This table shows the default operation when SET ANSI_PADDING is OFF.
Data type | Default operation
char | Pad value with spaces to the defined width of column.
varchar | Remove trailing spaces to the last nonspace character or to a single space character for strings consisting of only spaces.
varbinary | Remove trailing zeros.

  • If an empty string (‘ ‘) is loaded into a column with a varchar or text data type, the default operation is to load a zero-length string. If the compatibility level for the database is less than 70, the value is converted to a single space. For more information, see sp_dbcmptlevel.
  • If an INSERT statement violates a constraint or rule, or if it has a value incompatible with the data type of the column, the statement fails and SQL Server displays an error message.
  • Inserting a null value into a text or image column does not create a valid text pointer, nor does it preallocate an 8 KB text page.
  • If INSERT is loading multiple rows with SELECT or EXECUTE, any violation of a rule or constraint that occurs from the values being loaded causes the entire statement to be terminated, and no rows are loaded.

When an INSERT statement encounters an arithmetic error (overflow, divide by zero, or a domain error) occurring during expression evaluation, SQL Server handles these errors as if SET ARITHABORT is ON. The remainder of the batch is halted, and an error message is returned.

Permissions

INSERT permissions default to members of the sysadmin fixed server role, members of the db_owner fixed database role, and the table owner, who can transfer permissions to other users.

Examples
A. Use a simple INSERT

This example creates the table T1 and inserts one row.

IF EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES

        WHERE TABLE_NAME = 'T1')

    DROP TABLE T1

GO

CREATE TABLE T1 ( column_1 int, column_2 varchar(30))

INSERT T1 VALUES (1, 'Row #1')

B. Insert data that is not in the same order as the columns

This example uses column_list and VALUES list to explicitly specify the values that are inserted into each column.

IF EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES

        WHERE TABLE_NAME = 'T1')

    DROP TABLE T1

GO

CREATE TABLE T1 ( column_1 int, column_2 varchar(30))

INSERT T1 (column_2, column_1) VALUES ('Row #1',1)

C. Insert data with fewer values than columns

This example creates a table that has four columns. The INSERT statements insert rows that contain values for some of the columns, but not all of them.

IF EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES

        WHERE TABLE_NAME = 'T1')

    DROP TABLE T1

GO

CREATE TABLE T1

( column_1 int identity,

  column_2 varchar(30)

    CONSTRAINT default_name DEFAULT ('column default'),

  column_3 int NULL,

  column_4 varchar(40)

)

INSERT INTO T1 (column_4)

    VALUES ('Explicit value')

INSERT INTO T1 (column_2,column_4)

    VALUES ('Explicit value', 'Explicit value')

INSERT INTO T1 (column_2,column_3,column_4)

    VALUES ('Explicit value',-44,'Explicit value')

SELECT *

FROM T1

D. Load data into a table with an identity column

The first two INSERT statements allow identity values to be generated for the new rows. The third INSERT statement overrides the IDENTITY property for the column with the SET IDENTITY_INSERT statement, and inserts an explicit value into the identity column.

IF EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES

        WHERE TABLE_NAME = 'T1')

    DROP TABLE T1

GO

CREATE TABLE T1 ( column_1 int IDENTITY, column_2 varchar(30))

INSERT T1 VALUES ('Row #1')

INSERT T1 (column_2) VALUES ('Row #2')

SET IDENTITY_INSERT T1 ON

INSERT INTO T1 (column_1,column_2)

    VALUES (-99,'Explicit identity value')

SELECT *

FROM T1

E. Load data into a table through a view

The INSERT statement in this example specifies a view name; however, the new row is inserted in the view's underlying table. The order of VALUES list in the INSERT statement must match the column order of the view.

IF EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES

        WHERE TABLE_NAME = 'T1')

    DROP TABLE T1

GO

IF EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS

        WHERE TABLE_NAME = 'V1')

    DROP VIEW V1

GO

CREATE TABLE T1 ( column_1 int, column_2 varchar(30))

GO

CREATE VIEW V1 AS SELECT column_2, column_1

FROM T1

GO

INSERT INTO V1

    VALUES ('Row 1',1)

SELECT *

FROM T1

F. Load data using the DEFAULT VALUES option

The CREATE TABLE statement in this example defines each column with a value that can be used when no explicit value for the column is specified in the INSERT statement. The DEFAULT VALUES option of the INSERT statement is used to add rows without supplying explicit values.

IF EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES

        WHERE TABLE_NAME = 'T1')

    DROP TABLE T1

GO

CREATE DEFAULT bound_default AS 'Bound default value'

GO

CREATE TABLE T1

( column_1 int identity,

  column_2 varchar(30)

    CONSTRAINT default_name DEFAULT ('column default'),

  column_3 timestamp,

  column_4 varchar(30),

  column_5 int NULL)

GO

USE master

EXEC sp_bindefault 'bound_default','T1.column_4'

INSERT INTO T1 DEFAULT VALUES

SELECT *

FROM T1

G. Load data using the SELECT and EXECUTE options

This example demonstrates three different methods for getting data from one table and loading it into another. Each is based on a multitable SELECT statement that includes an expression and a literal value in the column list.

The first INSERT statement uses a SELECT statement directly to retrieve data from the source table, authors, and store the result set in the author_sales table. The second INSERT executes a procedure that contains the SELECT statement, and the third INSERT executes the SELECT statement as a literal string.

IF EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES

        WHERE TABLE_NAME = 'author_sales')

    DROP TABLE author_sales

GO

IF EXISTS(SELECT name FROM sysobjects

        WHERE name = 'get_author_sales' AND type = 'P')

    DROP PROCEDURE get_author_sales

GO

USE pubs

CREATE TABLE author_sales

( data_source   varchar(20),

  au_id         varchar(11),

  au_lname      varchar(40),

  sales_dollars smallmoney

)

GO

CREATE PROCEDURE get_author_sales

AS

    SELECT 'PROCEDURE', authors.au_id, authors.au_lname,

        SUM(titles.price * sales.qty)

    FROM authors INNER JOIN titleauthor

        ON authors.au_id = titleauthor.au_id INNER JOIN titles

        ON titleauthor.title_id = titles.title_id INNER JOIN sales

        ON titles.title_id = sales.title_id

    WHERE authors.au_id like '8%'

    GROUP BY authors.au_id, authors.au_lname

GO

--INSERT…SELECT example

USE pubs

INSERT author_sales

    SELECT 'SELECT', authors.au_id, authors.au_lname,

        SUM(titles.price * sales.qty)

    FROM authors INNER JOIN titleauthor

        ON authors.au_id = titleauthor.au_id INNER JOIN titles

        ON titleauthor.title_id = titles.title_id INNER JOIN sales

        ON titles.title_id = sales.title_id

    WHERE authors.au_id LIKE '8%'

    GROUP BY authors.au_id, authors.au_lname

--INSERT…EXECUTE procedure example

INSERT author_sales EXECUTE get_author_sales

--INSERT…EXECUTE('string') example

INSERT author_sales

EXECUTE

('

SELECT ''EXEC STRING'', authors.au_id, authors.au_lname,

    SUM(titles.price * sales.qty)

    FROM authors INNER JOIN titleauthor

        ON authors.au_id = titleauthor.au_id INNER JOIN titles

        ON titleauthor.title_id = titles.title_id INNER JOIN sales

        ON titles.title_id = sales.title_id

    WHERE authors.au_id like ''8%''

    GROUP BY authors.au_id, authors.au_lname

')

--Show results.

SELECT * FROM author_sales

H. Insert data using the TOP clause in a SELECT statement

Because a SELECT statement can be specified in an INSERT statement, the TOP clause can also be used within the SELECT statement. The example inserts the top 10 authors from the authors table into a new table called new_authors.

IF EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES

        WHERE TABLE_NAME = 'new_authors')

    DROP TABLE new_authors

GO

USE pubs

CREATE TABLE new_authors

(

 au_id    id,

 au_lname varchar(40),

 au_fname varchar(20),

 phone    char(12),

 address  varchar(40),

 city     varchar(20),

 state    char(2),

 zip          char(5),

 contract bit

)

INSERT INTO new_authors

SELECT TOP 10 *

FROM authors

See Also
CREATE TABLE | IDENTITY (Property)
EXECUTE | SELECT
FROM | SET ROWCOUNT
NEWID |


int, smallint, and tinyint

Exact number data types that use integer data.

int
Integer (whole number) data from -2^31 (-2,147,483,648) through 2^31 - 1 (2,147,483,647). Storage size is 4 bytes. The SQL-92 synonym for int is integer.
smallint
Integer data from -2^15 (-32,768) through 2^15 - 1 (32,767). Storage size is 2 bytes.
tinyint
Integer data from 0 through 255. Storage size is 1 byte.
See Also
ALTER TABLE | DELETE
CAST and CONVERT | INSERT
CREATE TABLE | SET @local_variable
Data Types | UPDATE
DECLARE @local_variable |


IS_MEMBER

Indicates whether the current user is a member of the specified Microsoft® Windows NT® group or Microsoft SQL Server™ role.

Syntax

IS_MEMBER ({'group' | 'role' })

Arguments
'group'
Is the name of the Windows NT group being checked; must be in the format Domain\Group. group is sysname.
'role'
Is the name of the SQL Server role being checked. role is sysname and can include the database fixed roles or user-defined roles but not server roles.
Return Types

int

Remarks

IS_MEMBER returns these values.

Return value | Description
0 | Current user is not a member of group or role.
1 | Current user is a member of group or role.
NULL | Either group or role is not valid.

This function can be useful to programmatically detect whether the current user can perform an activity that depends on the permissions applied to a group or role.

Examples

This example indicates whether the current user is a member of the db_owner fixed database role.

IF IS_MEMBER ('db_owner') = 1

print 'Current user is a member of the db_owner role'

ELSE IF IS_MEMBER ('db_owner') = 0

print 'Current user is NOT a member of the db_owner role'

ELSE IF IS_MEMBER ('db_owner') IS NULL

print 'ERROR: Invalid group / role specified'

See Also
IS_SRVROLEMEMBER Security Functions


IS_SRVROLEMEMBER

Indicates whether the current user login is a member of the specified server role.

Syntax

IS_SRVROLEMEMBER ( 'role' [,'login'])

Arguments
'role'
Is the name of the server role being checked. role is sysname.

Valid values for role are:

  • sysadmin
  • dbcreator
  • diskadmin
  • processadmin
  • serveradmin
  • setupadmin

· securityadmin

'login'
Is the optional name of the login to check. login is sysname, with a default of NULL. If not specified, the login account for the current user is used.
Return Types

int

Remarks

IS_SRVROLEMEMBER returns these values.

Return value | Description
0 | login is not a member of role.
1 | login is a member of role.
NULL | role or login is not valid.

This function can be useful to programmatically detect whether the current user can perform an activity requiring the server role’s permissions.

If a Windows NT user, such as London\JoeB, is specified for login, IS_SRVROLEMEMBER returns NULL if the user has not previously been granted or denied direct access to Microsoft SQL Server using sp_grantlogin or sp_denylogin.

Examples

This example indicates whether the current user is a member of the sysadmin fixed server role.

IF IS_SRVROLEMEMBER ('sysadmin') = 1

   print 'Current user''s login is a member of the sysadmin role'

ELSE IF IS_SRVROLEMEMBER ('sysadmin') = 0

   print 'Current user''s login is NOT a member of the sysadmin role'

ELSE IF IS_SRVROLEMEMBER ('sysadmin') IS NULL

   print 'ERROR: Invalid server role specified'

See Also
IS_MEMBER Security Functions


ISDATE

Determines whether an input expression is a valid date.

Syntax

ISDATE(expression)

Arguments
expression
Is an expression to be validated as a date. expression is any expression that returns a varchar data type.
Return Types

int

Remarks

ISDATE returns 1 if the input expression is a valid date; otherwise, it returns 0. This table shows the return values for a selection of examples.

Column value (varchar) | ISDATE return value
NULL | 0
abc | 0
100, -100, 100 a, or 100.00 | 0
.01 | 0
-100.1234e-123 | 0
.231e90 | 0
$100.12345, - $100.12345, or $-1000.123 | 0
as100 or 1a00 | 0
1995-10-1,1/20/95,1995-10-1 12:00pm, Feb 7 1995 11:00pm, or 1995-10-1, or 1/23/95 | 1
13/43/3425 or 1995-10-1a | 0
$1000, $100, or $100 a | 0

Examples
A. Use ISDATE to check a variable

This example checks the @datestring local variable for valid date data.

DECLARE @datestring varchar(8)

SET @datestring = '12/21/98'

SELECT ISDATE(@datestring)

Here is the result set:

-----------

1

B. Use ISDATE to check a column for dates

This example creates the test_dates table and inserts two values. ISDATE is used to determine whether the values in the columns are dates.

USE tempdb

CREATE TABLE test_dates (Col_1 varchar(15), Col_2 datetime)

GO

INSERT INTO test_dates VALUES ('abc', 'July 13, 1998')

GO

SELECT ISDATE(Col_1) AS Col_1, ISDATE(Col_2) AS Col_2
    FROM test_dates

Here is the result set:

Col_1                     Col_2

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

0                         1

See Also
char and varchar System Functions


IS [NOT] NULL

Determines whether or not a given expression is NULL.

Syntax

expression IS [NOT] NULL

Arguments
expression
Is any valid Microsoft® SQL Server™ expression.
NOT
Specifies that the Boolean expression specified by the predicate is negated.
Result Types

Boolean

Return Code Values

If the value of expression is NULL, IS[NOT]NULL returns TRUE; otherwise, it returns FALSE.

Remarks

To determine if an expression is NULL, use IS NULL rather than comparison operators (such as = or !=). Comparison operators return UNKNOWN if either or both arguments are NULL.

Examples

This example returns the title number and the advance amount for all books in which either the advance amount is less than $5,000 or the advance is unknown (or NULL). Note that the results shown are those returned after Example C has been executed.

USE pubs

SELECT title_id, advance

FROM titles

WHERE advance < $5000 OR advance IS NULL

ORDER BY title_id

Here is the result set:

title_id advance

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

MC2222   0.0000

MC3026   NULL

PC9999   NULL

PS2091   2275.0000

PS3333   2000.0000

PS7777   4000.0000

TC4203   4000.0000

(7 row(s) affected)

See Also
CASE | LIKE
CREATE PROCEDURE | Operators (Logical Operators)
CREATE TABLE | SELECT
Data Types | sp_help
Expressions | UPDATE
INSERT | WHERE


ISNULL

Replaces NULL with the specified replacement value.

Syntax

ISNULL(check_expression, replacement_value)

Arguments
check_expression
Is the expression to be checked for NULL. check_expression can be of any type.
replacement_value
Is the expression to be returned if check_expression is NULL. replacement_value must have the same type as check_expresssion.
Return Types

Returns the same type as check_expression.

Remarks

The value of check_expression is returned if it is not NULL; otherwise, replacement_value is returned.

Examples
A. Use ISNULL with AVG

This example finds the average of the prices of all titles, substituting the value $10.00 for all NULL entries in the price column of the titles table.

USE pubs

GO

SELECT AVG(ISNULL(price, $10.00))

FROM titles

GO

Here is the result set:

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

14.24

(1 row(s) affected)

B. Use ISNULL

This example selects the title, type, and price for all books in the titles table. If the price for a given title is NULL, the price shown in the result set is 0.00.

USE pubs

GO

SELECT SUBSTRING(title, 1, 15) AS Title, type AS Type,
    ISNULL(price, 0.00) AS Price

FROM titles

GO

Here is the result set:

Title           Type         Price

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

The Busy Execut business     19.99

Cooking with Co business     11.95

You Can Combat  business     2.99

Straight Talk A business     19.99

Silicon Valley  mod_cook     19.99

The Gourmet Mic mod_cook     2.99

The Psychology  UNDECIDED    0.00

But Is It User  popular_comp 22.95

Secrets of Sili popular_comp 20.00

Net Etiquette   popular_comp 0.00

Computer Phobic psychology   21.59

Is Anger the En psychology   10.95

Life Without Fe psychology   7.00

Prolonged Data  psychology   19.99

Emotional Secur psychology   7.99

Onions, Leeks,  trad_cook    20.95

Fifty Years in  trad_cook    11.95

Sushi, Anyone?  trad_cook    14.99

(18 row(s) affected)

See Also
Expressions | WHERE
IS [NOT] NULL | System Functions


ISNUMERIC

Determines whether an expression is a valid numeric type.

Syntax

ISNUMERIC(expression)

Arguments
expression
Is an expression to be evaluated.
Return Types

int

Remarks

ISNUMERIC returns 1 when the input expression evaluates to a valid integer, floating point number, money or decimal type; otherwise it returns 0. A return value of 1 guarantees that expression can be converted to one of these numeric types.

Examples
A. Use ISNUMERIC

This example returns 1 because the zip column contains valid numeric values.

USE pubs

SELECT ISNUMERIC(zip)

FROM authors

GO

B. Use ISNUMERIC and SUBSTRING

This example returns 0 for all titles in the titles table because none of the titles are valid numeric values.

USE pubs

GO

-- Because the title column is all character data, expect a result of 0

-- for the ISNUMERIC function.

SELECT SUBSTRING(title, 1, 15) type, price, ISNUMERIC(title)

FROM titles

GO

Here is the result set:

type            price

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

The Busy Execut 19.99                      0

Cooking with Co 11.95                      0

You Can Combat  2.99                       0

Straight Talk A 19.99                      0

Silicon Valley  19.99                      0

The Gourmet Mic 2.99                       0

The Psychology  (null)                     0

But Is It User  22.95                      0

Secrets of Sili 20.00                      0

Net Etiquette   (null)                     0

Computer Phobic 21.59                      0

Is Anger the En 10.95                      0

Life Without Fe 7.00                       0

Prolonged Data  19.99                      0

Emotional Secur 7.99                       0

Onions, Leeks,  20.95                      0

Fifty Years in  11.95                      0

Sushi, Anyone?  14.99                      0

(18 row(s) affected)

See Also
Expressions System Functions


KILL

Terminates a user process based on the system process ID (SPID). If the specified SPID has a lot of work to undo, the KILL may take some time to complete.

Syntax

KILL {spid}

Arguments
spid
Is the SPID of the process to terminate. The SPID value is a unique integer (smallint) assigned to each user connection when the connection is made, but the assignment is not permanent.
Remarks

KILL is commonly used to terminate a process that is blocking other important processes with locks, or to terminate a process that is executing a query that is using necessary system resources. System processes and processes running an extended stored procedure cannot be terminated.

Use KILL very carefully, especially when critical processes are running. You cannot kill your own process. Other processes not to kill are:

  • AWAITING COMMAND
  • CHECKPOINT SLEEP
  • LAZY WRITER
  • LOCK MONITOR
  • SELECT
  • SIGNAL HANDLER

Execute sp_who to get a report on valid SPID values. Use @@SPID to display the SPID value for the current session.

Permissions

KILL permissions default to the members of the sysadmin fixed database role, and are not transferable.

Examples

This example shows how to terminate SPID 10.

KILL 10

See Also
Functions | sp_who
SHUTDOWN | @@SPID
sp_lock |


LEFT

Returns the number of characters from the left of the specified character string.

Syntax

LEFT(character_expression, integer_expression)

Arguments
character_expression
Is an expression of character or binary data. character_expression can be a constant, variable, or column. character_expression must be of a data type that can be implicitly convertible to varchar. Otherwise, use the CAST function to explicitly convert character_expression.
integer_expression
Is a positive whole number. If integer_expression is negative, a null string is returned.
Return Types

varchar

Remarks

Note Compatibility levels can affect return values. For more information about compatibility levels, see sp_dbcmptlevel.

Examples
A. Use LEFT with a column

This example returns the five leftmost characters of each book title.

USE pubs

GO

SELECT LEFT(title, 5)

FROM titles

ORDER BY title_id

GO

Here is the result set:

-----

The B

Cooki

You C

Strai

Silic

The G

The P

But I

Secre

Net E

Compu

Is An

Life

Prolo

Emoti

Onion

Fifty

Sushi

(18 row(s) affected)

B. Use LEFT with a character string

This example uses LEFT to return the two leftmost characters of the character string abcdefg.

SELECT LEFT('abcdefg',2)

GO

Here is the result set:

--

ab

(1 row(s) affected)

See Also
Data Types String Functions


LEN

Returns the number of characters, rather than the number of bytes, of the given string expression, excluding trailing blanks.

Syntax

LEN(string_expression)

Arguments
string_expression
Is the string expression to be evaluated.
Return Types

int

Examples

This example selects the number of characters and the data in CompanyName for companies located in Finland.

USE Northwind

GO

SELECT LEN(CompanyName) AS 'Length', CompanyName
FROM Customers

WHERE Country = 'Finland'

Here is the result set.

Length       CompanyName

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

14           Wartian Herkku

11           Wilman Kala

See Also
Data Types String Functions


LIKE

Determines whether or not a given character string matches a specified pattern. A pattern can include regular characters and wildcard characters. During pattern matching, regular characters must exactly match the characters specified in the character string; wildcard characters, however, can be matched with arbitrary fragments of the character string. Using wildcard characters makes the LIKE operator more flexible than using the = and != string comparison operators. If any of the arguments are not of character string data type, Microsoft® SQL Server™ converts them to character string data type, if possible.

Syntax

match_expression [NOT] LIKE pattern [ESCAPE escape_character]

Arguments
match_expression
Is any valid SQL Server expression of character string data type.
pattern
Is the pattern to search for in match_expression, and can include these valid SQL Server wildcard characters.

Wildcard character | Description | Example
% Any string of zero or more characters. WHERE title LIKE ‘%computer%’ finds all book titles with the word ‘computer’ anywhere in the book title.
_ (underscore) | Any single character. | WHERE au_fname LIKE ‘_ean’ finds all four-letter first names that end with ean (Dean, Sean, and so on).
[ ] Any single character within the specified range ([a-f]) or set ([abcdef]). WHERE au_lname LIKE ‘[C-P]arsen’ finds author last names ending with arsen and beginning with any single character between C and P, for example Carsen, Larsen, Karsen, and so on.
[^] Any single character not within the specified range ([^a-f]) or set ([^abcdef]). WHERE au_lname LIKE ‘de[^l]%’ all author last names beginning with de and where the following letter is not l.

escape_character
Is any valid SQL Server expression of any of the data types of the character string data type category. escape_character has no default and must consist of only one character.
Result Types

Boolean

Result Value

LIKE returns TRUE if the match_expression matches the specified pattern.

Remarks

When you perform string comparisons with LIKE, all characters in the pattern string are significant, including leading or trailing spaces. If a comparison in a query is to return all rows with a string LIKE ‘abc ‘ (abc followed by a single space), a row in which the value of that column is abc (abc without a space) is not returned. However, trailing blanks, in the expression to which the pattern is matched, are ignored. If a comparison in a query is to return all rows with the string LIKE ‘abc’ (abc without a space), all rows that start with abc and have zero or more trailing blanks are returned.

A string comparison using a pattern containing char and varchar data may not pass a LIKE comparison because of how the data is stored. It is important to understand the storage for each data type and where a LIKE comparison may fail. The following example passes a local char variable to a stored procedure and then uses pattern matching to find all of the books by a certain author. In this procedure, the author’s last name is passed as a variable.

CREATE PROCEDURE find_books @AU_LNAME char(20)

AS

SELECT @AU_LNAME = RTRIM(@AU_LNAME) + '%'

SELECT t.title_id, t.title

FROM authors a, titleauthor ta, titles t

WHERE a.au_id = ta.au_id AND ta.title_id = t.title_id

    AND a.au_lname LIKE @AU_LNAME

In the find_books procedure, no rows are returned because the char variable (@AU_LNAME) contains trailing blanks whenever the name contains fewer than 20 characters. Because the au_lname column is varchar, there are no trailing blanks. This procedure fails because the trailing blanks are significant.

However, this example succeeds because trailing blanks are not added to a varchar variable:

USE pubs

GO

CREATE PROCEDURE find_books2 @au_lname varchar(20)

AS

SELECT t.title_id, t.title

FROM authors a, titleauthor ta, titles t

WHERE a.au_id = ta.au_id AND ta.title_id = t.title_id

    AND a.au_lname LIKE @au_lname + '%'

EXEC find_books2 'ring'

Here is the result set:

title_id title

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

MC3021   The Gourmet Microwave

PS2091   Is Anger the Enemy?

PS2091   Is Anger the Enemy?

PS2106   Life Without Fear

(4 row(s) affected)

Pattern Matching with LIKE

It is recommended that LIKE be used when you search for datetime values, because datetime entries can contain a variety of dateparts. For example, if you insert the value 19981231 9:20 into a column named arrival_time, the clause WHERE arrival_time = 9:20 cannot find an exact match for the 9:20 string because SQL Server converts it to Jan 1, 1900 9:20AM. However, the clause WHERE arrival_time LIKE ‘%9:20%’ does find it.

LIKE supports ASCII pattern matching and Unicode pattern matching. When all arguments (match_expression, pattern, and escape_character, if present) are ASCII character data types, ASCII pattern matching is performed. If any of the arguments are of Unicode data type, all arguments are converted to Unicode and Unicode pattern matching is performed. When you use Unicode data (nchar or nvarchar data types) with LIKE, trailing blanks are significant; however, for non-Unicode data, trailing blanks are not significant. Unicode LIKE is compatible with the SQL-92 standard. ASCII LIKE is compatible with earlier versions of SQL Server.

Here is a series of examples that show the differences in rows returned between ASCII and Unicode LIKE pattern matching:

-- ASCII pattern matching with char column

CREATE TABLE t (col1 char(30))

INSERT INTO t VALUES ('Robert King')

SELECT *

FROM t

WHERE col1 LIKE '% King'    -- returns 1 row

-- Unicode pattern matching with nchar column

CREATE TABLE t (col1 nchar(30))

INSERT INTO t VALUES ('Robert King')

SELECT *

FROM t

WHERE col1 LIKE '% King'    -- no rows returned

-- Unicode pattern matching with nchar column and RTRIM

CREATE TABLE t (col1 nchar (30))

INSERT INTO t VALUES ('Robert King')

SELECT *

FROM t

WHERE RTRIM(col1) LIKE '% King'    -- returns 1 row

Note When you perform string comparisons with LIKE, all characters in the pattern string are significant, including every leading or trailing blank (space).

Using the % Wildcard Character

If the LIKE ‘5%’ symbol is specified, SQL Server searches for the number 5 followed by any string of zero or more characters.

For example, this query shows all system tables in a database, because they all begin with the letters sys:

SELECT TABLE_NAME

FROM INFORMATION_SCHEMA.TABLES

WHERE TABLE_NAME LIKE 'sys%'

Note Be aware that system tables can change from version to version. It is recommended that you use the Information Schema Views or applicable stored procedures to work with SQL Server system tables.

To see all objects that are not system tables, use NOT LIKE ‘sys%’. If you have a total of 32 objects and LIKE finds 13 names that match the pattern, NOT LIKE finds the 19 objects that do not match the LIKE pattern.

You may not always find the same names with a pattern such as LIKE ‘[^s][^y][^s]%’. Instead of 19 names, you may get only 14, with all the names that begin with s or have y as the second letter or have s as the third letter eliminated from the results as well as the system table names. This is because match strings with negative wildcards are evaluated in steps, one wildcard at a time. If the match fails at any point in the evaluation, it is eliminated.

Using Wildcard Characters as Literals

You can use the wildcard pattern matching characters as literal characters. To use a wildcard character as a literal character, enclose the wildcard character in brackets. The table shows several examples of using the LIKE keyword and the [ ] wildcard characters.

Symbol | Meaning
LIKE ‘'5[%]’ | 5%
LIKE ‘[_]n’ | _n
LIKE ‘[a-cdf]’ | a, b, c, d, or f
LIKE ‘[-acdf]’ | -, a, c, d, or f
LIKE ‘[ [ ]’ | [
LIKE ‘]’ | ]
LIKE ‘abc[_]d%’ | abc_d and abc_de
LIKE ‘abc[def]’ | abcd, abce, and abcf

Pattern Matching with the ESCAPE Clause

You can search for character strings that include one or more of the special wildcard characters. For example, the discounts table in the customers database may store discount values that include a percent sign (%). To search for the percent sign as a character instead of as a wildcard character, the ESCAPE keyword and escape character must be provided. For example, a sample database contains a column named comment that contains the text 30%. To search for any rows containing the string 30% anywhere in the comment column, specify a WHERE clause of WHERE comment LIKE ‘%30!%%’ ESCAPE ‘!’. Unless ESCAPE and the escape character are specified, SQL Server returns any rows with the string 30.

This example shows how to search for the string “50% off when 100 or more copies are purchased” in the notes column of the titles table in the pubs database:

USE pubs

GO

SELECT notes

FROM titles

WHERE notes LIKE '50%% off when 100 or more copies are purchased'

    ESCAPE '%'

GO

Examples
A. Use LIKE with the % wildcard character

This example finds all phone numbers that have area code 415 in the authors table.

USE pubs

GO

SELECT phone

FROM authors

WHERE phone LIKE '415%'

ORDER by au_lname

GO

Here is the result set:

phone

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

415 658-9932

415 548-7723

415 836-7128

415 986-7020

415 836-7128

415 534-9219

415 585-4620

415 354-7128

415 834-2919

415 843-2991

415 935-4228

(11 row(s) affected)

B. Use NOT LIKE with the % wildcard character

This example finds all phone numbers in the authors table that have area codes other than 415.

USE pubs

GO

SELECT phone

FROM authors

WHERE phone NOT LIKE '415%'

ORDER BY au_lname

GO

Here is the result set:

phone

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

503 745-6402

219 547-9982

615 996-8275

615 297-2723

707 938-6445

707 448-4982

408 286-2428

301 946-8853

801 826-0752

801 826-0752

913 843-0462

408 496-7223

(12 row(s) affected)

C. Use the ESCAPE clause

This example uses the ESCAPE clause and the escape character to find the exact character string 10-15% in column c1 of the mytbl2 table.

USE pubs

GO

IF EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES

        WHERE TABLE_NAME = 'mytbl2')

    DROP TABLE mytbl2

GO

USE pubs

GO

CREATE TABLE mytbl2

(

 c1 sysname

)

GO

INSERT mytbl2 VALUES ('Discount is 10-15% off')

INSERT mytbl2 VALUES ('Discount is .10-.15 off')

GO

SELECT c1

FROM mytbl2

WHERE c1 LIKE '%10-15!% off%' ESCAPE '!'

GO

D. Use the [ ] wildcard characters

This example finds authors with the first name of with Cheryl or Sheryl.

USE pubs

GO

SELECT au_lname, au_fname, phone

FROM authors

WHERE au_fname LIKE '[CS]heryl'

ORDER BY au_lname ASC, au_fname ASC

GO

This example finds the rows for authors with last names of Carson, Carsen, Karson, or Karsen.

USE pubs

GO

SELECT au_lname, au_fname, phone

FROM authors

WHERE au_lname LIKE '[CK]ars[eo]n'

ORDER BY au_lname ASC, au_fname ASC

GO

See Also
Expressions | SELECT
Functions | WHERE


LOAD

Loads a backup copy of one of the following:

  • User database (LOAD DATABASE)
  • Transaction log (LOAD TRANSACTION)
  • Header information about the dump (LOAD HEADERONLY)

Important The LOAD statement is included in Microsoft® SQL Server™ version 7.0 for backward compatibility. The LOAD statement is identical to the RESTORE statement. It is recommended that the RESTORE statement be used instead of the LOAD statement. In a future version of SQL Server, LOAD will not be supported.

See Also
BACKUP | RESTORE
CREATE DATABASE | sp_helpdevice


LOG

Returns the natural logarithm of the given float expression.

Syntax

LOG(float_expression)

Arguments
float_expression
Is an expression of the float data type.
Return Types

float

Examples

This example calculates the LOG for the given float expression.

DECLARE @var float

SET @var = 5.175643

SELECT 'The LOG of the variable is: ' + CONVERT(varchar,LOG(@var))

GO

Here is the result set:

The LOG of the variable is: 1.64396

(1 row(s) affected)

See Also

Mathematical Functions


LOG10

Returns the base-10 logarithm of the given float expression.

Syntax

LOG10(float_expression)

Arguments
float_expression
Is an expression of the float data type.
Return Types

float

Examples

This example calculates the LOG10 of the given variable.

DECLARE @var float

SET @var = 145.175643

SELECT 'The LOG10 of the variable is: ' + CONVERT(varchar,LOG10(@var))

GO

Here is the result set:

The LOG10 of the variable is: 2.16189

(1 row(s) affected)

See Also

Mathematical Functions


LOWER

Returns a character expression after converting uppercase character data to lowercase.

Syntax

LOWER(character_expression)

Arguments
character_expression
Is an expression of character or binary data. character_expression can be a constant, variable, or column. character_expression must be of a data type that is implicitly convertible to varchar. Otherwise, use CAST to explicitly convert character_expression.
Return Types

varchar

Examples

This example uses the LOWER function, the UPPER function, and nests the UPPER function inside the LOWER function in selecting book titles that have prices between $11 and $20.

USE pubs

GO

SELECT LOWER(SUBSTRING(title, 1, 20)) AS Lower,

    UPPER(SUBSTRING(title, 1, 20)) AS Upper,

    LOWER(UPPER(SUBSTRING(title, 1, 20))) As LowerUpper

FROM titles

WHERE price between 11.00 and 20.00

GO

Here is the result set:

Lower                Upper                LowerUpper

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

the busy executive's THE BUSY EXECUTIVE'S the busy executive's

cooking with compute COOKING WITH COMPUTE cooking with compute

straight talk about  STRAIGHT TALK ABOUT  straight talk about

silicon valley gastr SILICON VALLEY GASTR silicon valley gastr

secrets of silicon v SECRETS OF SILICON V secrets of silicon v

prolonged data depri PROLONGED DATA DEPRI prolonged data depri

fifty years in bucki FIFTY YEARS IN BUCKI fifty years in bucki

sushi, anyone?       SUSHI, ANYONE?       sushi, anyone?

(8 row(s) affected)

See Also
Data Types String Functions


LTRIM

Returns a character expression after removing leading blanks.

Syntax

LTRIM(character_expression)

Arguments
character_expression
Is an expression of character or binary data. character_expression can be a constant, variable or column. character_expression must be of a data type that is implicitly convertible to varchar. Otherwise, use CAST to explicitly convert character_expression.
Return Type

varchar

Remarks

Compatibility levels can affect return values. For more information about compatibility levels, see sp_dbcmptlevel.

Examples

This example uses LTRIM to remove leading spaces from a character variable.

DECLARE @string_to_trim varchar(60)

SET @string_to_trim = '     Five spaces are at the beginning of this
    string.'

SELECT 'Here is the string without the leading spaces: ' +
    LTRIM(@string_to_trim)

GO

Here is the result set:

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

Here is the string without the leading spaces: Five spaces are at the beginning of this string.

(1 row(s) affected)

See Also
Data Types String Functions


MAX

Returns the maximum value in the expression.

Syntax

MAX([ALL | DISTINCT] expression)

Arguments
ALL
Applies the aggregate function to all values. ALL is the default.
DISTINCT
Specifies that each unique value is considered. DISTINCT is not meaningful with MAX and is available for SQL-92 compatibility only.
expression
Is a constant, column name, or function, and any combination of arithmetic, bitwise, and string operators. MAX can be used with numeric, character, and datetime columns, but not with bit columns. Aggregate functions and subqueries are not permitted.
Return Types

Returns a value same as expression.

Important Distinct aggregates, for example AVG(DISTINCT column_name), COUNT(DISTINCT column_name), MAX(DISTINCT column_name), MIN(DISTINCT column_name), and SUM(DISTINCT column_name), are not supported when using CUBE or ROLLUP. If used, Microsoft® SQL Server™ returns an error message and cancels the query.

Remarks

MAX ignores any null values.

For character columns, MAX finds the highest value in the collating sequence.

Examples

This example returns the book with the highest (maximum) year-to-date sales.

USE pubs

GO

SELECT MAX(ytd_sales)

FROM titles

GO

Here is the result set:

-----------

22246

(1 row(s) affected)

Warning, null value eliminated from aggregate.

See Also

Aggregate Functions


MIN

Returns the minimum value in the expression.

Syntax

MIN([ALL | DISTINCT] expression)

Arguments
ALL
Applies the aggregate function to all values. ALL is the default.
DISTINCT
Specifies that each unique value is considered. DISTINCT is not meaningful with MIN and is available for SQL-92 compatibility only.
expression
Is a constant, column name, or function, and any combination of arithmetic, bitwise, and string operators. MIN can be used with numeric, char, varchar, or datetime columns, but not with bit columns. Aggregate functions and subqueries are not permitted.
Return Types

Returns a value same as expression.

Important Distinct aggregates, for example AVG(DISTINCT column_name), COUNT(DISTINCT column_name), MAX(DISTINCT column_name), MIN(DISTINCT column_name), and SUM(DISTINCT column_name), are not supported when using CUBE or ROLLUP. If used, Microsoft® SQL Server™ returns an error message and ends the query.

Remarks

MIN ignores any null values.

With character data columns, MIN finds the value that is lowest in the sort sequence.

Examples

This example returns the book with the lowest (minimum) year-to-date sales.

USE pubs

GO

SELECT min(ytd_sales)

FROM titles

GO

Here is the result set:

-----------

111

(1 row(s) affected)

See Also

Aggregate Functions


money and smallmoney

Monetary data types for representing monetary or currency values.

money
Monetary data values from -2^63 (-922,337,203,685,477.5808) through 2^63 - 1 (+922,337,203,685,477.5807), with accuracy to a ten-thousandth of a monetary unit. Storage size is 8 bytes.
smallmoney
Monetary data values from - 214,748.3648 through +214,748.3647, with accuracy to a ten-thousandth of a monetary unit. Storage size is 4 bytes.
See Also
ALTER TABLE | DELETE
CAST and CONVERT | INSERT
CREATE TABLE | SET @local_variable
Data Types | UPDATE
DECLARE @local_variable |


MONTH

Returns an integer that represents the month part of a specified date.

Syntax

MONTH(date)

Arguments
date
Is an expression returning a datetime or smalldatetime value, or a character string in a date format. Use the datetime data type only for dates after January 1, 1753.
Return Types

int

Remarks

MONTH is equivalent to DATEPART(mm, date).

Always enclose datetime values in quotation marks. For earlier dates, store dates as character data.

Microsoft® SQL Server™ recognizes a variety of date styles. For more information about date and time data, see CAST and CONVERT.

Examples

This example returns the number of the month from the date 03/12/1998.

SELECT "Month Number" = MONTH('03/12/1998')

GO

Here is the result set:

Month Number
------------
3

This example specifies the date as a number. Notice that SQL Server interprets 0 as January 1, 1900.

SELECT MONTH(0), DAY(0), YEAR(0)

Here is the result set.

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

1     1      1900

See Also
Data Types | Date and Time Functions
datetime and smalldatetime |


NCHAR

Returns the Unicode character with the given integer code, as defined by the Unicode standard.

Syntax

NCHAR(integer_expression)

Arguments
integer_expression
Is a positive whole number from 0 through 65535. If a value outside this range is specified, NULL is returned.
Return Types

nchar(1)

Examples
A. Use NCHAR and UNICODE

This example uses the UNICODE and NCHAR functions to print the UNICODE value and the NCHAR (Unicode character) of the second character of the København character string, and to print the actual second character, ø.

DECLARE @nstring nchar(8)

SET @nstring = N'København'

SELECT UNICODE(SUBSTRING(@nstring, 2, 1)),

    NCHAR(UNICODE(SUBSTRING(@nstring, 2, 1)))

GO

Here is the result set:

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

248         ø

(1 row(s) affected)

B.Use SUBSTRING, UNICODE, CONVERT, and NCHAR

This example uses the SUBSTRING, UNICODE, CONVERT, and NCHAR functions to print the character number, the Unicode character, and the UNICODE value of each of the characters in the string København.

-- The @position variable holds the position of the character currently

-- being processed. The @nstring variable is the Unicode character

-- string to process.

DECLARE @position int, @nstring nchar(9)

-- Initialize the current position variable to the first character in

-- the string.

SET @position = 1

-- Initialize the character string variable to the string to process.

-- Notice that there is an N before the start of the string, which

-- indicates that the data following the N is Unicode data.

SET @nstring = N'København'

-- Print the character number of the position of the string you're at,

-- the actual Unicode character you're processing, and the UNICODE value -- for this particular character.

PRINT 'Character #' + ' ' + 'Unicode Character' + ' ' + 'UNICODE Value'

WHILE @position <= DATALENGTH(@nstring)

    BEGIN

    SELECT @position,

        NCHAR(UNICODE(SUBSTRING(@nstring, @position, 1))),

        CONVERT(NCHAR(17), SUBSTRING(@nstring, @position, 1)),

        UNICODE(SUBSTRING(@nstring, @position, 1))

    SELECT @position = @position + 1

    END

GO

Here is the result set:

Character # Unicode Character UNICODE Value

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

1           K                 75

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

2           ø                 248

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

3           b                 98

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

4           e                 101

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

5           n                 110

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

6           h                 104

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

7           a                 97

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

8           v                 118

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

9           n                 110

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

10          (null)            (null)

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

11          (null)            (null)

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

12          (null)            (null)

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

13          (null)            (null)

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

14          (null)            (null)

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

15          (null)            (null)

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

16          (null)            (null)

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

17          (null)            (null)

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

18          (null)            (null)

See Also
Data Types | String Functions
UNICODE |


nchar and nvarchar

Character data types that are either fixed-length (nchar) or variable-length (nvarchar) Unicode data and use the UNICODE UCS-2 character set.

nchar(n)
Fixed-length Unicode character data of n characters. n must be a value from 1 through 4,000. Storage size is two times n bytes. The SQL-92 synonyms for nchar are national char and national character.
nvarchar(n)
Variable-length Unicode character data of n characters. n must be a value from 1 through 4,000. Storage size, in bytes, is two times the number of characters entered. The data entered can be 0 characters in length. The SQL-92 synonyms for nvarchar are national char varying and national character varying.
Remarks

When n is not specified in a data definition or variable declaration statement, the default length is 1. When n is not specified with the CAST function, the default length is 30.

Use nchar when the data entries in a column are expected to be consistently close to the same size.

Use nvarchar when the data entries in a column are expected to vary considerably in size.

SET ANSI_PADDING OFF does not apply to nchar or nvarchar. SET ANSI_PADDING is always ON for nchar and nvarchar.

See Also
ALTER TABLE | LIKE
CAST and CONVERT | SET @local_variable
CREATE TABLE | SET ANSI_PADDING
Data Types | sp_dbcmptlevel
DECLARE @local_variable | UPDATE
DELETE | WHERE
INSERT |


NEWID

Creates a unique value of type uniqueidentifier.

Syntax

NEWID()

Return Types

uniqueidentifier

Examples
A. Use the NEWID function with a variable

This example uses NEWID to assign a value to a variable declared as the uniqueidentifier data type. The value of the uniqueidentifier data type variable is printed before the value is tested.

-- Creating a local variable with DECLARE/SET syntax.

DECLARE @myid uniqueidentifier

SET @myid = NEWID()

PRINT 'Value of @myid is: '+ CONVERT(varchar(255), @myid)

Here is the result set:

Note The value returned by NEWID is different for each computer. This number is shown only for illustration.

Value of @myid is: 6F9619FF-8B86-D011-B42D-00C04FC964FF

B. Use NEWID in a CREATE TABLE statement

This example creates cust table with a uniqueidentifier data type, and uses NEWID to fill the table with a default value. In assigning the default value of NEWID(), each new and existing row has a unique value for the cust_id column.

-- Creating a table using NEWID for uniqueidentifier data type.

CREATE TABLE cust

(

 cust_id uniqueidentifier NOT NULL

    DEFAULT newid(),

 company varchar(30) NOT NULL,

 contact_name varchar(60) NOT NULL,

 address varchar(30) NOT NULL,

 city varchar(30) NOT NULL,

 state_province varchar(10) NULL,

 postal_code varchar(10) NOT NULL,

 country varchar(20) NOT NULL,

 telephone varchar(15) NOT NULL,

 fax varchar(15) NULL

)

GO

-- Inserting data into cust table.

INSERT cust

(cust_id, company, contact_name, address, city, state_province,

 postal_code, country, telephone, fax)

VALUES

(newid(), 'Wartian Herkku', 'Pirkko Koskitalo', 'Torikatu 38', 'Oulu', NULL,

 '90110', 'Finland', '981-443655', '981-443655')

INSERT cust

(cust_id, company, contact_name, address, city, state_province,

postal_code, country, telephone, fax)

VALUES

(newid(), 'Wellington Importadora', 'Paula Parente', 'Rua do Mercado, 12', 'Resende', 'SP',

 '08737-363', 'Brazil', '(14) 555-8122', '')

INSERT cust

(cust_id, company, contact_name, address, city, state_province,

 postal_code, country, telephone, fax)

VALUES

(newid(), 'Cactus Comidas para Ilevar', 'Patricio Simpson', 'Cerrito 333', 'Buenos Aires', NULL,

 '1010', 'Argentina', '(1) 135-5555', '(1) 135-4892')

INSERT cust

(cust_id, company, contact_name, address, city, state_province,

 postal_code, country, telephone, fax)

VALUES

(newid(), 'Ernst Handel', 'Roland Mendel', 'Kirchgasse 6', 'Graz', NULL,

 '8010', 'Austria', '7675-3425', '7675-3426')

INSERT cust

(cust_id, company, contact_name, address, city, state_province,

 postal_code, country, telephone, fax)

VALUES

(newid(), 'Maison Dewey', 'Catherine Dewey', 'Rue Joseph-Bens 532', 'Bruxelles', NULL,

 'B-1180', 'Belgium', '(02) 201 24 67', '(02) 201 24 68')

GO

C. Use uniqueidentifier and variable assignment

This example declares a local variable called @myid as a variable of uniqueidentifier data type. Then, the variable is assigned a value using the SET statement.

DECLARE @myid uniqueidentifier

SET @myid = 'A972C577-DFB0-064E-1189-0154C99310DAAC12'

GO

See Also
ALTER TABLE | Data Types
CAST and CONVERT | uniqueidentifier
CREATE TABLE | System Functions


Northwind Sample Database

The Northwind Traders sample database contains the sales data for a fictitious company called Northwind Traders, which imports and exports specialty foods from around the world.

If you have made changes to the Northwind database, you can reinstall it by running a script from the Install directory of your Microsoft® SQL Server™ installation.

  1. At the command prompt, change to the Mssql7\Install directory.
  2. Use the osql utility to run the Instnwnd.sql script:

    osql/Usa /Psapassword /Sservername /iinstnwnd.sql /oinstnwnd.rpt

  3. Check Instnwnd.rpt for reported errors.

The database is created in the Data directory of your SQL Server installation.

Instnwnd.sql is a large file. If you want to view Instnwnd.sql using Notepad, first turn off the Notepad Word Wrap option. If Word Wrap is on, opening the file and each scrolling operation will take a long time. Even turning Word Wrap off after the file has been opened takes a long time.

Note The Northwind database contains the table Northwind.dbo.dtproperties that stores a diagram of the database. To view the diagram in SQL Server Enterprise Manager, open the Diagrams folder in the Northwind folder and double-click Relationships.


Categories

Column_name | Data type | Nullable | Default | Check | Key/index
CategoryID | int | no | IDENTITY(1,1) |  | PK clust.
CategoryName | nvarchar(15) | no |  |  | Nonclust.
Description | ntext | yes |  |  |
Picture | image | yes |  |  |


Customers

Column_name | Data type | Nullable | Default | Check | Key/index
CustomerID | nchar(5) | no |  |  | PK clust.
CompanyName | nvarchar(40) | no |  |  | Nonclust.
ContactName | nvarchar(30) | yes |  |  |
ContactTitle | nvarchar(30) | yes |  |  |
Address | nvarchar(60) | yes |  |  |
City | nvarchar(15) | yes |  |  | Nonclust.
Region | nvarchar(15) | yes |  |  | Nonclust.
PostalCode | nvarchar(10) | yes |  |  | Nonclust.
Country | nvarchar(15) | yes |  |  |
Phone | nvarchar(24) | yes |  |  |
Fax | nvarchar(24) | yes |  |  |


CustomerCustomerDemo

Column_name | Data type | Nullable | Default | Check | Key/index
CustomerID | nchar(5) | no |  |  | Composite PK nonclust. (1) , FK Customers(CustomerID)
CustomerTypeID | nchar(10) | no |  |  | Composite PK nonclust. (1) , FK CustomerDemographics (CustomerTypeID)
(1) The composite primary key is defined on CustomerID, CustomerTypeID.


CustomerDemographics

Column_name | Data type | Nullable | Default | Check | Key/index
CustomerTypeID | nchar(10) | no |  |  | PK nonclust.
CustomerDesc | ntext | yes |  |  |


Employees

Column_name | Data type | Nullable | Default | Check | Key/index
EmployeeID | int | no | IDENTITY (1,1) |  | PK clust.
LastName | nvarchar(20) | no |  |  | Nonclust.
FirstName | nvarchar(10) | no |  |  |
Title | nvarchar(30) | yes |  |  |
TitleOfCourtesy | nvarchar(25) | yes |  |  |
BirthDate | datetime | yes |  | yes (1) |
HireDate | datetime | yes |  |  |
Address | nvarchar(60) | yes |  |  |
City | nvarchar(15) | yes |  |  |
Region | nvarchar(15) | yes |  |  |
PostalCode | nvarchar(10) | yes |  |  | Nonclust.
Country | nvarchar(15) | yes |  |  |
HomePhone | nvarchar(24) | yes |  |  |
Extension | nvarchar(4) | yes |  |  |
Photo | image | yes |  |  |
Notes | ntext | yes |  |  |
ReportsTo | int | yes |  |  | FK Employees (EmployeeID)
Photopath | nvarchar(255) | yes |  |  |
(1) The BirthDate CHECK constraint is defined as (BirthDate < GETDATE()).

Note Some entries in the Address column of the Employees table contain newline characters that may affect the format of the result set columns.


EmployeeTerritories

Column_name | Data type | Nullable | Default | Check | Key/index
EmployeeID | int | no |  |  | Composite PK nonclust.
TerritoryID | nvarchar(20) | no |  |  | Composite PK nonclust.


Order Details

Column_name | Data type | Nullable | Default | Check | Key/index
OrderID | int | no |  |  | Composite PK, clust. (1) , FK Orders(OrderID) (2)
ProductID | int | no |  |  | Composite PK, clust. (1) , FK Products(ProductID) (3)
UnitPrice | money | no | 0 | yes (4) |
Quantity | smallint | no | 1 | yes (5) |
Discount | real | no | 0 |  |
(1) The composite, primary key, clustered index is defined on OrderID and ProductID. (2) There are also two nonclustered indexes on OrderID. (3) There are also two nonclustered indexes on ProductID. (4) The UnitPrice CHECK constraint is defined as (UnitPrice >= 0). (5) The Quantity CHECK constraint is defined as (Quantity > 0). The table-level CHECK constraint is defined as (Discount >= 0 and Discount < = 1).


Orders

Column_name | Data type | Nullable | Default | Check | Key/index
OrderID | int | no | IDENTITY (1,1) |  | PK, clust.
CustomerID | nchar(5) | yes |  |  | FK Customers (CustomerID) (1)
EmployeeID | int | yes |  |  | FK Employees (EmployeeID) (2)
OrderDate | datetime | yes | GETDATE() |  | Nonclust.
RequiredDate | datetime | yes |  |  |
ShippedDate | datetime | yes |  |  | Nonclust.
ShipVia | int | yes |  |  | FK Shippers (ShipperID) (3)
Freight | money | yes | 0 |  |
ShipName | nvarchar(40) | yes |  |  |
ShipAddress | nvarchar(60) | yes |  |  |
ShipCity | nvarchar(15) | yes |  |  |
ShipRegion | nvarchar(15) | yes |  |  |
ShipPostalCode | nvarchar(10) | yes |  |  | Nonclust.
ShipCountry | nvarchar(15) | yes |  |  |
(1) There are also two nonclustered indexes on CustomerID. (2) There are also two nonclustered indexes on EmployeeID. (3) There is also a nonclustered index on ShipVia.


Products

Column_name | Data type | Nullable | Default | Check | Key/index
ProductID | int | no | IDENTITY (1,1) |  | PK, clust.
ProductName | nvarchar(40) | no |  |  | Nonclust.
SupplierID | int | yes |  |  | FK Suppliers (SupplierID), nonclust. (1)
CategoryID | int | yes |  |  | FK Categories (CategoryID), nonclust. (2)
QuantityPerUnit | nvarchar(20) | yes |  |  |
UnitPrice | money | yes | 0 | yes (3) |
UnitsInStock | smallint | yes | 0 | yes (4) |
UnitsOnOrder | smallint | yes | 0 | yes (5) |
ReorderLevel | smallint | yes | 0 | yes (6) |
Discontinued | bit | no | 0 |  |
(1) There are two nonclustered indexes on SupplierID. (2) There are two nonclustered indexes on CategoryID. (3) The UnitPrice CHECK constraint is defined as (UnitPrice >=). (4) The UnitsInStock CHECK constraint is defined as (UnitsInStock >=). (5) The UnitsOnOrder CHECK constraint is defined as (UnitsOnOrder >=). (6) The ReorderLevel CHECK constraint is defined as (ReorderLevel >=).


Region

Column_name | Data type | Nullable | Default | Check | Key/index
RegionID | int | no |  |  | PK nonclust.
RegionDescription | nchar(50) | no |  |  |


Shippers

Column_name | Data type | Nullable | Default | Check | Key/index
ShipperID | int | no | IDENTITY (1,1) |  | PK clust.
CompanyName | nvarchar(40) | no |  |  |
Phone | nvarchar(24) | yes |  |  |


Suppliers

Column_name | Data type | Nullable | Default | Check | Key/index
SupplierID | int | no | IDENTITY (1,1) |  | PK clust.
CompanyName | nvarchar(40) | no |  |  | Nonclust.
ContactName | nvarchar(30) | yes |  |  |
ContactTitle | nvarchar(30) | yes |  |  |
Address | nvarchar(60) | yes |  |  |
City | nvarchar(15) | yes |  |  |
Region | nvarchar(15) | yes |  |  |
PostalCode | nvarchar(10) | yes |  |  | Nonclust.
Country | nvarchar(15) | yes |  |  |
Phone | nvarchar(24) | yes |  |  |
Fax | nvarchar(24) | yes |  |  |
HomePage | ntext | yes |  |  |


Territories

Column_name | Data type | Nullable | Default | Check | Key/index
TerritoryID | nvarchar(20) | no |  |  | PK nonclust.
TerritoryDescription | nchar(50) | no |  |  |
RegionID | int | no |  |  | FK Region (RegionID)


NOT

Negates a Boolean input.

Syntax

[NOT] boolean_expression

Arguments
boolean_expression
Is any valid Microsoft® SQL Server™ Boolean expression.
Result Type

Boolean

Result Value

NOT reverses the value of any Boolean expression.

Remarks

The use of NOT negates an expression.

This table shows the results of comparing TRUE and FALSE values using the NOT operator.

 | NOT
TRUE | FALSE
FALSE | TRUE
UNKNOWN | UNKNOWN

Examples

This example finds all business and psychology books that do not have an advance over $5,500.

USE pubs

GO

SELECT title_id, type, advance

FROM titles

WHERE (type = 'business' OR type = 'psychology')

    AND NOT advance > $5500

ORDER BY title_id ASC

GO

Here is the result set:

title_id type         advance

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

BU1032   business     5000.0000

BU1111   business     5000.0000

BU7832   business     5000.0000

PS2091   psychology   2275.0000

PS3333   psychology   2000.0000

PS7777   psychology   4000.0000

(6 row(s) affected)

See Also
Expressions | SELECT
Functions | WHERE
Operators (Logical Operators) |


ntext, text, and image

Fixed and variable-length data types for storing large non-Unicode and Unicode character and binary data. Unicode data uses the UNICODE UCS-2 character set.

ntext
Variable-length Unicode data with a maximum length of 230 - 1 (1,073,741,823) characters. Storage size, in bytes, is two times the number of characters entered. The SQL-92 synonym for ntext is national text.
text
Variable-length non-Unicode data in the code page of the server and with a maximum length of 231-1 (2,147,483,647) characters. When the server code page uses double-byte characters, the storage is still 2,147,483,647 bytes. Depending on the character string, the storage size may be less than 2,147,483,647 bytes.
image
Variable-length binary data from 0 through 231-1 (2,147,483,647) bytes.
Remarks

These functions and statements can be used with ntext, text, or image data.

Functions | Statements
DATALENGTH | READTEXT
PATINDEX | SET TEXTSIZE
SUBSTRING | UPDATETEXT
TEXTPTR | WRITETEXT
TEXTVALID |

See Also
ALTER TABLE | DELETE
CAST and CONVERT | INSERT
CREATE TABLE | LIKE
Data Types | SET @local_variable
DECLARE @local_variable | UPDATE


NULLIF

Returns a null value if the two specified expressions are equivalent.

Syntax

NULLIF(expression, expression)

Arguments
expression
Is a constant, column name, function, subquery, or any combination of arithmetic, bitwise, and string operators.
Return Types

Returns the same type as the first expression.

NULLIF returns the first expression if the two expressions are not equivalent. If the expressions are equivalent, NULLIF returns a null value of the type of the first expression.

Remarks

NULLIF is equivalent to a searched CASE function in which the two expressions are equal and the resulting expression is NULL.

Examples

This example creates a budgets table to show a department (dept) its current budget (current_year) and its previous budget (previous_year). For the current year, NULL is used for departments with budgets that have not changed from the previous year, and 0 is used for budgets that have not yet been determined. To find out the average of only those departments that receive a budget as well as to include the budget value from the previous year (use the previous_year value, where the current_year is 0), combine the NULLIF and COALESCE functions.

USE pubs

IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES

        WHERE TABLE_NAME = 'budgets')

    DROP TABLE budgets

GO

SET NOCOUNT ON

CREATE TABLE budgets

(

    dept                tinyint    IDENTITY,

    current_year        decimal    NULL,

    previous_year    decimal    NULL

)

INSERT budgets VALUES(100000, 150000)

INSERT budgets VALUES(NULL, 300000)

INSERT budgets VALUES(0, 100000)

INSERT budgets VALUES(NULL, 150000)

INSERT budgets VALUES(300000, 250000)

GO

SET NOCOUNT OFF

SELECT AVG(NULLIF(COALESCE(current_year,

    previous_year), 0.00)) AS 'Average Budget'

FROM budgets

GO

Here is the result set:

Average Budget

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

212500.000000

(1 row(s) affected)

See Also
CASE | System Functions
decimal and numeric |


numeric

For information about the numeric data type, see decimal and numeric.

See Also
Data Types


OBJECT_ID

Returns the database object identification number.

Syntax

OBJECT_ID('object')

Arguments
'object'
Is the object to be used. object is either char or nchar. If object is char, it is implicitly converted to nchar.
Return Types

int

Remarks

When the parameter to a system function is optional, the current database, host computer, server user, or database user is assumed. Built-in functions must always be followed by parentheses.

Important When specifying a temporary table name, the database name must precede the temporary table name, for example:

SELECT OBJECT_ID('tempdb..#mytemptable')

System functions can be used in the select list, in the WHERE clause, and anywhere an expression is allowed. For more information, see Expressions and WHERE.

Examples

This example returns the object ID for the authors table in the pubs database.

USE master

SELECT OBJECT_ID('pubs..authors')

Here is the result set:

-----------

117575457

(1 row(s) affected)

See Also

Metadata Functions


OBJECT_NAME

Returns the database object name.

Syntax

OBJECT_NAME(object_id)

Arguments
object_id
Is the ID of the object to be used. object_id is int.
Return Types

nchar

Remarks

When the parameter to a system function is optional, the current database, host computer, server user, or database user is assumed. Built-in functions must always be followed by parentheses.

System functions can be used in the select list, in the WHERE clause, and anywhere an expression is allowed. For more information, see Expressions and “WHERE.”WHERE.

Examples

This example returns the OBJECT_NAME for the authors table in the pubs database.

USE pubs

SELECT TABLE_CATALOG, TABLE_NAME

FROM INFORMATION_SCHEMA.TABLES

WHERE TABLE_NAME = OBJECT_NAME(117575457)

Here is the result set:

TABLE_CATALOG                  TABLE_NAME

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

pubs                           authors

(1 row(s) affected)

See Also

Metadata Functions


OBJECTPROPERTY

Returns information about objects in the current database.

Syntax

OBJECTPROPERTY(id, property)

Arguments
id
Is an expression containing the ID of the object in the current database. id is int.
property
Is an expression containing the information to be returned for the object specified by id. property can be one of these values.

Value | Object type | Description
CnstIsClustKey | Constraint | Primary key with a clustered index.
CnstIsColumn | Constraint | COLUMN constraint.
CnstIsDisabled | Constraint | Disabled constraint.
CnstIsNonclustKey | Constraint | Primary key with a nonclustered index.
CnstIsNotRepl | Constraint | Constraint defined with the NOT FOR REPLICATION keywords.
ExecIsAnsiNullsOn | Procedure, Trigger, View | Setting of ANSI_NULLS at creation time.
ExecIsDeleteTrigger | Trigger | A DELETE trigger.
ExecIsInsertTrigger | Trigger | An INSERT trigger.
ExecIsQuotedIdentOn | Procedure, Trigger, View | Setting of QUOTED_IDENTIFIER at creation time.
ExecIsStartup | Procedure | Startup procedure.
ExecIsTriggerDisabled | Trigger | Disabled trigger.
ExecIsUpdateTrigger | Trigger | UPDATE trigger.
IsCheckCnst | Any | CHECK constraint.
IsConstraint | Any | Constraint.
IsDefault | Any | Bound default.
IsDefaultCnst | Any | DEFAULT constraint.
IsExecuted | Any | How this object can be executed (view, procedure, or trigger).
IsExtendedProc | Any | Extended procedure.
IsForeignKey | Any | FOREIGN KEY constraint.
IsMSShipped | Any | Object created during installation of Microsoft® SQL Server™.
IsPrimaryKey | Any | PRIMARY KEY constraint.
IsProcedure | Any | Procedure.
IsReplProc | Any | Replication procedure.
IsRule | Any | Bound rule.
IsSystemTable | Table | System table.
IsTable | Table | Table.
IsTrigger | Any | Trigger.
IsUniqueCnst | Any | UNIQUE constraint.
IsUserTable | Table | User-defined table.
IsView | View | View.
OwnerId | Any | Owner of the object.
TableDeleteTrigger | Table | Table has a DELETE trigger.
TableDeleteTrigger
Count 		Table Table has the specified number of DELETE triggers.
TableFulltextCatalogId | Table | ID of the full-text catalog in which the full-text index data for the table resides.
TableFulltextKeyColumn | Table | ID of the column associated with the single-column unique index that is participating in the full-text index definition.
TableHasActiveFulltext
Index 		Tables Table is full-text indexed.
TableHasCheckCnst | Table | Table has a CHECK constraint.
TableHasClustIndex | Table | Table has a clustered index.
TableHasDefaultCnst | Table | Table has a DEFAULT constraint.
TableHasDeleteTrigger | Table | Table has a DELETE trigger.
TableHasForeignKey | Table | Table has a FOREIGN KEY constraint.
TableHasForeignRef | Table | Table is referenced by a FOREIGN KEY constraint.
TableHasIdentity | Table | Table has an identity column.
TableHasIndex | Table | Table has an index of any type.
TableHasInsertTrigger | Table | Table has an INSERT trigger.
TableHasNonclustIndex | Table | Table has a nonclustered index.
TableHasPrimaryKey | Table | Table has a primary key.
TableHasRowGuidCol | Table | Table has a ROWGUIDCOL for a uniqueidentifier column.
TableHasTextImage | Table | Table has a text column.
TableHasTimestamp | Table | Table has a timestamp column.
TableHasUniqueCnst | Table | Table has a UNIQUE constraint.
TableHasUpdateTrigger | Table | Table has an UPDATE trigger.
TableInsertTrigger | Table | Table has an INSERT trigger.
TableInsertTrigger
Count 		Table Table has the specified number of INSERT triggers.
TableIsFake | Table | Table is not real. It is materialized internally on demand by SQL Server.
TableIsPinned | Table | Table is pinned to be held in the data cache.
TableUpdateTrigger | Table | Table has an UPDATE trigger.
TableUpdateTrigger
Count 		Table Table has the specified number of UPDATE triggers.
TriggerDeleteOrder | Table | Firing order of this DELETE trigger.
TriggerInsertOrder | Table | Firing order of this INSERT trigger.
TriggerUpdateOrder | Table | Firing order of this UPDATE trigger.

The table shows the values that can be returned for the types of properties.

Property names Values returned
CnstIsClustKey
CnstIsColumn
CnstIsDisabled
CnstIsNonclustKey
CnstIsNotRepl 		1 = True
0 = False
NULL = Invalid input.
ExecIsAnsiNullsOn
ExecIsDeleteTrigger
ExecIsGlobalProc
ExecIsInsertTrigger
ExecIsQuotedIdentOn
ExecIsStartup
ExecIsDisabledTrigger
ExecIsUpdateTrigger 		1 = True
0 = False
NULL = Invalid input.
IsCheckCnst
IsConstraint
IsDefault
IsDefaultCnst
IsExecuted
IsExtendedProc
IsForeignKey
IsMSShipped
IsPrimaryKey
IsProcedure
IsReplProc
IsRule
IsSystemTable
IsTable
IsTrigger
IsUniqueCnst
IsUserTable
IsView 		1 = True
0 = False
NULL = Invalid input.
OwnerId Nonnull = The database user ID of the object owner.
NULL = Invalid input.
TableDeleteTrigger
TableDeleteTriggerCount
TableInsertTrigger
TableInsertTriggerCount
TableUpdateTrigger
TableUpdateTriggerCount 		>1 = ID of first trigger with given type.
NULL = Invalid input.
TableHasCheckCnst
TableHasActiveFulltextIndex
TableHasClustIndex
TableHasDefaultCnst
TableHasDeleteTrigger
TableHasForeignKey
TableHasForeignRef
TableHasIdentity
TableHasIndex
TableHasInsertTrigger
TableHasNonclustIndex
TableHasPrimaryKey
TableHasRowGuidCol
TableHasTextImage
TableHasTimestamp
TableHasUniqueCnst
TableHasUpdateTrigger
TableIsFake
TableIsPinned
TriggerDeleteOrder
TriggerInsertOrder
TriggerUpdateOrder 		1 = True
0 = False
NULL = Invalid input.
TableFulltextCatalogId
TableFulltextKeyColumn 		Nonzero = Full-text catalog ID.
Nonzero = ID associated with the unique index that identifies the rows in a full-text indexed table.
0 = Table is not full-text indexed.
NULL = Invalid input.

Return Types

int

Examples

This example tests whether authors is a table.

IF OBJECTPROPERTY ( object_id('authors'),'ISTABLE') = 1

    print 'Authors is a table'

ELSE IF OBJECTPROPERTY ( object_id('authors'),'ISTABLE') = 0

    print 'Authors is not a table'

ELSE IF OBJECTPROPERTY ( object_id('authors'),'ISTABLE') IS NULL

    print 'ERROR: Authors is not an object'

See Also
COLUMNPROPERTY | Metadata Functions
TYPEPROPERTY |


OPEN

Opens a Transact-SQL server cursor and populates the cursor by executing the Transact-SQL statement specified on the DECLARE CURSOR or SET cursor_variable statement.

Syntax

OPEN { { [GLOBAL] cursor_name } | cursor_variable_name}

Arguments
GLOBAL
Specifies that cursor_name refers to a global cursor.
cursor_name
Is the name of a declared cursor. If both a global and a local cursor exist with cursor_name as their name, cursor_name refers to the global cursor if GLOBAL is specified; otherwise, cursor_name refers to the local cursor.
cursor_variable_name
Is the name of a cursor variable that references a cursor.
Remarks

If the cursor is declared with the INSENSITIVE or STATIC option, OPEN creates a temporary table to hold the result set. OPEN fails if the size of any row in the result set exceeds the maximum row size for Microsoft® SQL Server™ tables. If the cursor is declared with the KEYSET option, OPEN creates a temporary table to hold the keyset. The temporary tables are stored in tempdb.

After a cursor has been opened, use the @@CURSOR_ROWS function to receive the number of qualifying rows in the last opened cursor. Depending on the number of rows expected in the result set, SQL Server may choose to populate a keyset-driven cursor asynchronously on a separate thread. This allows fetches to proceed immediately, even if the keyset is not fully populated.

To set the threshold at which SQL Server generates keysets asynchronously, set the cursor threshold configuration option. For more information, see sp_configure.

Examples

This example opens a cursor and fetches all the rows.

DECLARE Employee_Cursor CURSOR FOR

SELECT LastName, FirstName

FROM Northwind.dbo.Employees

WHERE LastName like 'B%'

OPEN Employee_Cursor

FETCH NEXT FROM Employee_Cursor

WHILE @@FETCH_STATUS = 0

BEGIN

    FETCH NEXT FROM Employee_Cursor

END

CLOSE Employee_Cursor

DEALLOCATE Employee_Cursor

See Also
CLOSE | DECLARE CURSOR
@@CURSOR_ROWS | FETCH
DEALLOCATE |


OPENQUERY

Executes the specified pass-through query on the given linked server, which is an OLE DB data source. The OPENQUERY function can be referenced in the FROM clause of a query as though it is a table name. The OPENQUERY function can also be referenced as the target table of an INSERT, UPDATE, or DELETE statement, subject to the capabilities of the OLE DB provider. Although the query may return multiple result sets, OPENQUERY returns only the first one.

Syntax

OPENQUERY(linked_server, 'query')

Arguments
linked_server
Is an identifier representing the name of the linked server.
'query'
Is the query string executed in the linked server.
Examples

This example creates a linked server named OracleSvr against an Oracle database using the Microsoft OLE DB Provider for Oracle. Then this example uses a pass-through query against this linked server.

Note This example assumes that an Oracle database alias called ORCLDB has been created.

EXEC sp_addlinkedserver 'OracleSvr',

    'Oracle 7.3’,

    'MSDAORA',

    'ORCLDB'

GO

SELECT *

FROM OPENQUERY(OracleSvr, 'SELECT name, id FROM joe.titles')

GO

See Also
DELETE | sp_addlinkedserver
FROM | sp_serveroption
INSERT | UPDATE
OPENROWSET | WHERE
SELECT | Rowset Functions


OPENROWSET

Includes all connection information necessary to access remote data from an OLE DB data source. This method is an alternative to accessing tables in a linked server and is a one-time, ad hoc method of connecting and accessing remote data using OLE DB. The OPENROWSET function can be referenced in the FROM clause of a query as though it is a table name. The OPENROWSET function can also be referenced as the target table of an INSERT, UPDATE, or DELETE statement, subject to the capabilities of the OLE DB provider. Although the query may return multiple result sets, OPENROWSET returns only the first one.

Syntax

OPENROWSET('provider_name'
{
'datasource';'user_id';'password'
| 'provider_string'
 },
{
[catalog.][schema.]object
| 'query'
})

Arguments
'provider_name'
Is a character string that represents the friendly name of the OLE DB provider as specified in the registry. provider_name has no default value.
'datasource'
Is a string constant that corresponds to a particular OLE DB data source. datasource is the DBPROP_INIT_DATASOURCE property to be passed to the provider’s IDBProperties interface to initialize the provider. Typically, this string includes the name of the database file, the name of a database server, or a name that the provider understands to locate the database(s).
'user_id'
Is a string constant that is the username that is passed to the specified OLE DB provider. user_id specifies the security context for the connection and is passed in as the DBPROP_AUTH_USERID property to initialize the provider.
'password'
Is a string constant that is the user password to be passed to the OLE DB provider. password is passed in as the DBPROP_AUTH_PASSWORD property when initializing the provider.
'provider_string'
Is a provider-specific connection string that is passed in as the DBPROP_INIT_PROVIDERSTRING property to initialize the OLE DB provider. provider_string typically encapsulates all the connection information needed to initialize the provider.
catalog
Is the name of the catalog or database in which the specified object resides.
schema
Is the name of the schema or object owner for the specified object.
object
Is the object name that uniquely identifies the object to manipulate.
'query'
Is a string constant that is sent to and executed by the provider. Microsoft® SQL Server™ does not process this query, but processes query results returned by the provider (a pass-through query). Pass-through queries are useful when used on providers that do not expose their tabular data through table names, but only through a command language. Pass-through queries are supported on the remote server, as long as the query provider supports the OLE DB Command object and its mandatory interfaces.
Remarks

Catalog and schema names are required if the OLE DB provider supports multiple catalogs and schemas in the specified data source. Values for catalog and schema can be omitted if the OLE DB provider does not support them.

If the provider supports only schema names, a two-part name of the form schema.object must be specified. If the provider supports only catalog names, a three-part name of the form catalog.schema.object must be specified.

Permissions

OPENROWSET permissions are determined by the permissions of the username being passed to the OLE DB provider.

Examples

A. Use OPENROWSET with a SELECT and the Microsoft OLE DB Provider for SQL Server

This example uses the Microsoft OLE DB Provider for SQL Server to access the authors table in the pubs database on a remote server named seattle1. The provider is initialized from the datasource, user_id, and password, and a SELECT is used to define the row set returned.

USE pubs

GO

SELECT a.*

FROM OPENROWSET('SQLOLEDB','seattle1';'sa';'MyPass',

    'SELECT * FROM pubs.dbo.authors ORDER BY au_lname, au_fname') AS a

GO

B. Use OPENROWSET with an object and the OLE DB Provider for ODBC

This example uses the OLE DB Provider for ODBC and the SQL Server ODBC driver to access the authors table in the pubs database on a remote server named seattle1. The provider is initialized with a provider_string specified in the ODBC syntax used by the ODBC provider, and the catalog.schema.object syntax is used to define the row set returned.

USE pubs

GO

SELECT a.*

FROM OPENROWSET('MSDASQL',

    'DRIVER={SQL Server};SERVER=seattle1;UID=sa;PWD=MyPass',

    pubs.dbo.authors) AS a

ORDER BY a.au_lname, a.au_fname

GO

C. Use the Microsoft OLE DB Provider for Jet

This example accesses the orders table in the Microsoft Access Northwind database through the Microsoft OLE DB Provider for Jet.

Note This example assumes that Access is installed.

USE pubs

GO

SELECT a.*

FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',
    'c:\MSOffice\Access\Samples\northwind.mdb';'admin';'mypwd', Orders)     AS a

GO

D. Use OPENROWSET and another table in an INNER JOIN

This example selects all data from the customers table from the local SQL Server Northwind database and from the orders table from the Access Northwind database stored on the same computer.

Note This example assumes that Access is installed.

USE pubs

GO

SELECT c.*, o.*

FROM Northwind.dbo.Customers AS c INNER JOIN
    OPENROWSET('Microsoft.Jet.OLEDB.4.0',
    'c:\MSOffice\Access\Samples\northwind.mdb';'admin';'mypwd', Orders)
    AS o
    ON c.CustomerID = o.CustomerID

GO

See Also
DELETE | sp_addlinkedserver
FROM | sp_serveroption
INSERT | UPDATE
OPENQUERY | WHERE
SELECT | Rowset Functions


Operators

An operator is a symbol specifying an action that is performed on one or more expressions. Microsoft® SQL Server™ uses these operator categories:

  • Arithmetic operators
  • Assignment operator
  • Bitwise operators
  • Comparison operators
  • Logical operators
  • String concatenation operator
  • Unary operators
Arithmetic Operators

Arithmetic operators perform mathematical operations on two expressions of any of the data types of the numeric data type category. For more information about data type categories, see Transact-SQL Syntax Conventions.

Operator | Meaning
+ (Add) | Addition.
- (Subtract) | Subtraction.
* (Multiply) | Multiplication.
/ (Divide) | Division.
% (Modulo) | Returns the integer remainder of a division. For example, 12 % 5 = 2 because the remainder of 12 divided by 5 is 2.

The + and - operators can also be used to perform arithmetic operations on datetime and smalldatetime values.

For information about the precision and scale of the result of an arithmetic operation, see Precision, Scale, and Length.

Assignment Operator

Transact-SQL has one assignment operator, the equals sign (=). In this example, the @MyCounter variable is created. Then, the assignment operator sets @MyCounter to a value returned by an expression.

DECLARE @MyCounter INT

SET @MyCounter = 1

The assignment operator (=) can also be used to establish the relationship between a column heading and the expression defining the values for the column. This example displays two column headings named FirstColumnHeading and SecondColumnHeading. The string xyz is displayed in the FirstColumnHeading column heading for all rows. Then, each product ID from the Products table is listed in the SecondColumnHeading column heading.

USE Northwind

GO

SELECT FirstColumnHeading = 'xyz',

       SecondColumnHeading = ProductID

FROM Products

GO

Bitwise Operators

Bitwise operators perform bit manipulations between two expressions of any of the data types of the integer data type category.

Operator | Meaning
& (Bitwise AND) | Bitwise AND (two operands).
| (Bitwise OR) | Bitwise OR (two operands).
^ (Bitwise Exclusive OR) | Bitwise exclusive OR (two operands).

The operands for bitwise operators can be any of the data types of the integer or binary string data type categories (except for the image data type), with the exception that both operands cannot be any of the data types of the binary string data type category. The table shows the supported operand data types.

Left operand | Right operand
binary | int, smallint, or tinyint
bit | int, smallint, tinyint, or bit
int | int, smallint, tinyint, binary, or varbinary
smallint | int, smallint, tinyint, binary, or varbinary
tinyint | int, smallint, tinyint, binary, or varbinary
varbinary | int, smallint, or tinyint

Comparison Operators

Comparison operators test whether or not two expressions are the same. Comparison operators can be used on all expressions except expressions of the text, ntext, or image data types.

Operator | Meaning
= (Equals) | Equal to.
> (Greater Than) | Greater than.
< (Less Than) | Less than.
>= (Greater Than or Equal To) | Greater than or equal to.
<= (Less Than or Equal To) | Less than or equal to.
<> (Not Equal To) | Not equal to.
!= (Not Equal To) | Not equal to (not SQL-92 standard).
!< (Not Less Than) | Not less than (not SQL-92 standard).
!> (Not Greater Than) | Not greater than (not SQL-92 standard).

The result of a comparison operator has the Boolean data type, which has three values: TRUE, FALSE, and UNKNOWN. Expressions that return a Boolean data type are known as Boolean expressions.

Unlike other SQL Server data types, a Boolean data type cannot be specified as the data type of a table column or variable, and cannot be returned in a result set.

When SET ANSI_NULLS is ON, an operator that has one or two NULL expressions returns UNKNOWN. When SET ANSI_NULLS is OFF, the same rules apply, except an equals operator returns TRUE if both expressions are NULL. For example, NULL = NULL returns TRUE if SET ANSI_NULLS is OFF.

Expressions with Boolean data types are used in the WHERE clause to filter the rows that qualify for the search conditions and in control-of-flow language statements such as IF and WHILE, for example:

USE Northwind

GO

DECLARE @MyProduct int

SET @MyProduct = 10

IF (@MyProduct <> 0)

    SELECT *

    FROM Products

    WHERE ProductID = @MyProduct

GO

Logical Operators

Logical operators test for the truth of some condition. Logical operators, like comparison operators, return a Boolean data type with a value of TRUE or FALSE.

Operator | Meaning
ALL | TRUE if all of a set of comparisons are TRUE.
AND | TRUE if both Boolean expressions are TRUE.
ANY | TRUE if any one of a set of comparisons are TRUE.
BETWEEN | TRUE if the operand is within a range.
EXISTS | TRUE if a subquery contains any rows.
IN | TRUE if the operand is equal to one of a list of expressions.
LIKE | TRUE if the operand matches a pattern.
NOT | Reverses the value of any other Boolean operator.
OR | TRUE if either Boolean expression is TRUE.
SOME | TRUE if some of a set of comparisons are TRUE.

For more information about logical operators, see the specific logical operator topic.

String Concatenation Operator

The string concatenation operator allows string concatenation with the addition sign (+), which is also known as the string concatenation operator. All other string manipulation is handled through string functions such as SUBSTRING.

By default, an empty string is interpreted as an empty string in INSERT or assignment statements on data of the varchar data type. In concatenating data of either the varchar, char, or text data types, the empty string is interpreted as an empty string. For example, ‘abc’ + ‘‘ + ‘def’ is stored as ‘abcdef’. However, if the sp_dbcmptlevel compatibility level setting is 65, empty constants are treated as a single blank character and ‘abc’ + ‘‘ + ‘def’ is stored as ‘abc def’. For more information about the interpretation of empty strings, see sp_dbcmptlevel.

Unary Operators

Unary operators perform an operation on only one expression of any of the data types of the numeric data type category.

Operator | Meaning
+ (Positive) | Numeric value is positive.
- (Negative) | Numeric value is negative.
~ (Bitwise NOT) | Returns the ones complement of the number.

The + (Positive) and - (Negative) operators can be used on any expression of any of the data types of the numeric data type category. The ~ (Bitwise NOT) operator can be used only on expressions of any of the data types of the integer data type category.

Operator Precedence

When a complex expression has multiple operators, operator precedence determines the sequence in which the operations are performed. The order of execution can significantly affect the resulting value.

Operators have these precedence levels. An operator on higher levels is evaluated before an operator on a lower level:

  • + (Positive), - (Negative), ~ (Bitwise NOT)
  • * (Multiply), / (Division), % (Modulo)
  • + (Add), (+ Concatenate), - (Subtract)
  • =, >, <, >=, <=, <>, !=, !>, !< (Comparison operators)
  • ^ (Bitwise Exlusive OR), & (Bitwise AND), | (Bitwise OR)
  • NOT
  • AND
  • ALL, ANY, BETWEEN, IN, LIKE, OR, SOME
  • = (Assignment)

When two operators in an expression have the same operator precedence level, they are evaluated left to right based on their position in the expression. For example, in the expression used in the SET statement of this example, the subtraction operator is evaluated before the addition operator.

DECLARE @MyNumber int

SET @MyNumber = 4 - 2 + 27

-- Evaluates to 2 + 27 which yields an expression result of 29.

SELECT @MyNumber

Use parentheses to override the defined precedence of the operators in an expression. Everything within the parentheses is evaluated first to yield a single value before that value can be used by any operator outside of the parentheses.

For example, in the expression used in the SET statement of this example, the multiplication operator has a higher precedence than the addition operator, so it gets evaluated first; the expression result is 13.

DECLARE @MyNumber int

SET @MyNumber = 2 * 4 + 5

-- Evaluates to 8 + 5 which yields an expression result of 13.

SELECT @MyNumber

In the expression used in the SET statement of this example, the parentheses causes the addition to be performed first; the expression result is 18.

DECLARE @MyNumber int

SET @MyNumber = 2 * (4 + 5)

-- Evaluates to 2 * 9 which yields an expression result of 18.

SELECT @MyNumber

If an expression has nested parentheses, the most deeply nested expression is evaluated first. This example contains nested parentheses, with the expression 5 - 3 in the most deeply nested set of parentheses. This expression yields a value of 2. Then, the addition operator (+) adds this result to 4, which yields a value of 6. Finally, the 6 is multiplied by 2 to yield an expression result of 12.

DECLARE @MyNumber int

SET @MyNumber = 2 * (4 + (5 - 3) )

-- Evaluates to 2 * (4 + 2) which further evaluates to 2 * 6, and

-- yields an expression result of 12.

SELECT @MyNumber

See Also

Functions


OR

Combines two conditions. When more than one logical operator is used in a statement, OR operators are evaluated after AND operators. However, you can change the order of evaluation by using parentheses.

Syntax

boolean_expression OR boolean_expression

Arguments
boolean_expression
Is any valid Microsoft® SQL Server™ expression that returns TRUE, FALSE, or UNKNOWN.
Result Types

Boolean

Result Value

OR returns TRUE when either of the conditions is TRUE.

Remarks

The table shows the result of the OR operator.

 | TRUE | FALSE | UNKNOWN
TRUE | TRUE | TRUE | TRUE
FALSE | TRUE | FALSE | UNKNOWN
UNKNOWN | TRUE | UNKNOWN | UNKNOWN

Examples

This example retrieves the book titles that carry an advance greater than $5,500 and that are either business or psychology books. If the parentheses are not included, the WHERE clause retrieves all business books or psychology books that have an advance greater than $5,500.

USE pubs

GO

SELECT SUBSTRING(title, 1, 30) AS Title, type

FROM titles

WHERE (type = 'business' OR type = 'psychology') AND
    advance > $5500

ORDER BY title

GO

Here is the result set:

Title                          type

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

Computer Phobic AND Non-Phobic psychology

Life Without Fear              psychology

You Can Combat Computer Stress business

(3 row(s) affected)

See Also
Expressions | SELECT
Functions | WHERE
Operators (Logical Operators) |


ORDER BY

Specifies the sort order used on columns returned in a SELECT statement. For more information, see SELECT.


PARSENAME

Returns the specified part of an object name. Parts of an object that can be retrieved are the object name, owner name, database name, and server name.

Note The PARSENAME function does not indicate whether or not an object by the specified name exists. It just returns the specified piece of the given object name.

Syntax

PARSENAME('object_name ', object_piece)

Arguments
'object_name'
Is the name of the object for which to retrieve the specified object part. object_name is sysname. This parameter is an optionally qualified object name. If all parts of the object name are qualified, this name can consist of four parts: the server name, the database name, the owner name, and the object name.
object_piece
Is the object part to return. object_piece is int, and can have these values.

Value | Description
1 | Object name
2 | Owner name
3 | Database name
4 | Server name

Return Types

nchar

Remarks

PARSENAME returns NULL if any of the following conditions are met:

  • Either object_name or object_piece is NULL.
  • A syntax error occurs.
  • The requested object part has a length of 0 and is an invalid Microsoft® SQL Server™ identifier. A zero-length object name renders the entire qualified name invalid.
Examples

This example uses PARSENAME to return information about the authors table in the pubs database.

USE pubs

SELECT PARSENAME('pubs..authors', 1) AS 'Object Name'

SELECT PARSENAME('pubs..authors', 2) AS 'Owner Name'

SELECT PARSENAME('pubs..authors', 3) AS 'Database Name'

SELECT PARSENAME('pubs..authors', 4) AS 'Server Name'

Here is the result set:

Object Name

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

authors

(1 row(s) affected)

Owner Name

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

(null)

(1 row(s) affected)

Database Name

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

pubs

(1 row(s) affected)

Server Name

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

(null)

(1 row(s) affected)

See Also
ALTER TABLE | System Functions
CREATE TABLE |


PATINDEX

Returns the starting position of the first occurrence of a pattern in a specified expression, or zeros if the pattern is not found, on all valid text and character data types.

Syntax

PATINDEX('%pattern%', expression)

Arguments
pattern
Is a literal string. Wildcard characters can be used; however, the % character must precede and follow pattern (except when searching for first or last characters). pattern is an expression of the short character data type category.
expression
Is an expression, usually a column that is searched for the specified pattern. expression is of the character string data type category.
Return Types

int

Remarks

PATINDEX is useful with text data types; it can be used in a WHERE clause in addition to IS NULL, IS NOT NULL, and LIKE (the only other comparisons that are valid on text in a WHERE clause).

If either pattern or expression is NULL, PATINDEX returns NULL when the database compatibility level is 70. If the database compatibility level is 65 or earlier, PATINDEX returns NULL only when both pattern and expression are NULL.

Examples
A. Use a pattern with PATINDEX

This example finds the position at which the pattern “wonderful” begins in a specific row of the notes column in the titles table.

USE pubs

GO

SELECT PATINDEX('%wonderful%', notes)

FROM titles

WHERE title_id = 'TC3218'

GO

Here is the result set:

-----------

47

(1 row(s) affected)

If you do not restrict the rows to be searched by using a WHERE clause, the query returns all rows in the table and reports nonzero values for those rows in which the pattern was found and zero for all rows in which the pattern was not found.

B. Use wildcard characters with PATINDEX

This example uses wildcards to find the position at which the pattern “won_erful” begins in a specific row of the notes column in the titles table, where the underscore is a wildcard representing any character.

USE pubs
GO
SELECT PATINDEX('%won_erful%', notes)
FROM titles
WHERE title_id = 'TC3218'
GO

Here is the result set:

------------
47

(1 row(s) affected)

If you do not restrict the rows to be searched, the query returns all rows in the table and reports nonzero values for those rows in which the pattern was found.

See Also
Data Types String Functions


PERMISSIONS

Returns a value containing a bitmap that indicates the statement, object, or column permissions for the current user.

Syntax

PERMISSIONS([objectid [, 'column']])

Arguments
objectid
Is the ID of an object. If objectid is not specified, the bitmap value contains statement permissions for the current user; otherwise, the bitmap contains object permissions on the object ID for the current user. The object specified must be in the current database. Use the OBJECT_ID function with an object name to determine the objectid value.
'column'
Is the optional name of a column for which permission information is being returned. The column must be a valid column name in the table specified by objectid.
Return Types

int

Remarks

PERMISSIONS can be used to determine whether the current user has the necessary permissions to execute a statement or to GRANT a permission on an object to another user.

The permissions information returned is a 32-bit bitmap.

The lower 16 bits reflect permissions granted to the security account for the current user, as well as permissions applied to Microsoft® Windows NT® groups or Microsoft SQL Server™ roles of which the current user is a member. For example, a returned value of 66 (hex value 0x42), when no objectid is specified, indicates the current user has permissions to execute the CREATE TABLE (decimal value 2) and BACKUP DATABASE (decimal value 64) statement permissions.

The upper 16 bits reflect the permissions that the current user can GRANT to other users. The upper 16 bits are interpreted exactly as those for the lower 16 bits described in the following tables, except they are shifted to the left by 16 bits (multiplied by 65536). For example, 0x8 (decimal value 8) is the bit indicating INSERT permissions when an objectid is specified. Whereas 0x80000 (decimal value 524288) indicates the ability to GRANT INSERT permissions, because 524288 = 8 x 65536. Due to membership in roles, it is possible to not have a permission to execute a statement, but still be able to grant that permission to someone else.

The table shows the bits used for statement permissions (objectid is not specified).

Bit (dec) | Bit (hex) | Statement permission
1 | 0x1 | CREATE DATABASE (master database only)
2 | 0x2 | CREATE TABLE
4 | 0x4 | CREATE PROCEDURE
8 | 0x8 | CREATE VIEW
16 | 0x10 | CREATE RULE
32 | 0x20 | CREATE DEFAULT
64 | 0x40 | BACKUP DATABASE
128 | 0x80 | BACKUP LOG
256 | 0x100 | Reserved

The table shows the bits used for object permissions that are returned when only objectid is specified.

Bit (dec) | Bit (hex) | Statement permission
1 | 0x1 | SELECT ALL
2 | 0x2 | UPDATE ALL
4 | 0x4 | REFERENCES ALL
8 | 0x8 | INSERT
16 | 0x10 | DELETE
32 | 0x20 | EXECUTE (procedures only)
4096 | 0x1000 | SELECT ANY (at least one column)
8192 | 0x2000 | UPDATE ANY
16384 | 0x4000 | REFERENCES ANY

The table shows the bits used for column-level object permissions that are returned when both objectid and column are specified.

Bit (dec) | Bit (hex) | Statement permission
1 | 0x1 | SELECT
2 | 0x2 | UPDATE
4 | 0x4 | REFERENCES

A NULL is returned if a specified parameter is NULL or invalid (for example, an objectid or column that does not exist). The bit values for permissions that do not apply (for example EXECUTE permissions, bit 0x20, for a table) are undefined.

Use the bitwise AND (&) operator to determine each bit set in the bitmap returned by the PERMISSIONS function.

The sp_helprotect system stored procedure can also be used to return a list of object permissions for a user in the current database.

Examples
A. Use PERMISSIONS function with statement permissions

This example determines whether the current user can execute the CREATE TABLE statement.

IF PERMISSIONS()&2=2

    CREATE TABLE test_table (col1 INT)

ELSE

    PRINT 'ERROR: The current user cannot create a table.'

B. Use PERMISSIONS function with object permissions

This example determines whether the current user can insert a row of data into the authors table.

IF PERMISSIONS(OBJECT_ID('authors'))&8=8

    PRINT 'The current user can insert data into authors.'

ELSE

    PRINT 'ERROR: The current user cannot insert data into authors.'

C. Use PERMISSIONS function with grantable permissions

This example determines whether the current user can grant the INSERT permission on the authors table to another user.

IF PERMISSIONS(OBJECT_ID('authors'))&0x80000=0x80000

    PRINT 'INSERT on authors is grantable.'

ELSE

    PRINT 'You may not GRANT INSERT permissions on authors.'

See Also
DENY | REVOKE
GRANT | sp_helprotect
OBJECT_ID | System Functions


PI

Returns the constant value of PI.

Syntax

PI()

Return Types

float

Example

This example returns the value of PI.

SELECT PI()

GO

Here is the result set:

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

3.14159265358979

(1 row(s) affected)

See Also

Mathematical Functions


POWER

Returns the value of the given expression to the specified power.

Syntax

POWER(numeric_expression, y)

Arguments
numeric_expression
Is an expression of the exact numeric or approximate numeric data type category, except for the bit data type.
y
Is the power to which to raise numeric_expression. y can be an expression of the exact numeric or approximate numeric data type category, except for the bit data type.
Return Types

Same as numeric_expression.

Examples
A. Use POWER to show results of 0.0

This example shows a floating point underflow that returns a result of 0.0.

SELECT POWER(2.0, -100.0)

GO

Here is the result set:

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

0.0

(1 row(s) affected)

B. Use POWER

This example returns POWER results for 21 to 24.

DECLARE @value int, @counter int

SET @value = 2

SET @counter = 1

WHILE @counter < 5

    BEGIN

        SELECT POWER(@value, @counter)

        SET NOCOUNT ON

        SET @counter = @counter + 1

        SET NOCOUNT OFF

    END

GO

Here is the result set:

-----------

2

(1 row(s) affected)

-----------

4

(1 row(s) affected)

-----------

8

(1 row(s) affected)

-----------

16

(1 row(s) affected)

See Also
decimal and numeric | money and smallmoney
float and real | Mathematical Functions
int, smallint, and tinyint |


Predicate

Is an expression that evaluates to TRUE, FALSE, or UNKNOWN. Predicates are used in the search condition of WHERE clauses and HAVING clauses, and the join conditions of FROM clauses.

See Also
BETWEEN | IN
CONTAINS | LIKE
EXISTS | IS [NOT] NULL
FREETEXT | Search Condition


PRINT

Returns a user-defined message to the client.

Syntax

PRINT 'any ASCII text' | @local_variable | @@FUNCTION | string_expr

Arguments
'any ASCII text'
Is a string of text.
@local_variable
Is a variable of any valid character data type. @local_variable must be char or varchar, or be able to be implicitly converted to those data types.
@@FUNCTION
Is a function that returns string results. @@FUNCTION must be char or varchar, or be able to be implicitly converted to those data types.
string_expr
Is an expression that returns a string. Can include concatenated literal values and variables. The message string can be up to 8,000 characters long; any characters after 8,000 are truncated.
Remarks

To print a user-defined error message having an the error number that can be returned by @@ERROR, use RAISERROR instead of PRINT.

Examples
A. Conditionally executed print (IF EXISTS)

This example uses the PRINT statement to conditionally return a message.

IF EXISTS (SELECT zip FROM authors WHERE zip = '94705')

    PRINT 'Berkeley author'

B. Build and display a string

This example converts the results of the GETDATE function to a varchar data type and concatenates it with literal text to be returned by PRINT.

PRINT 'This message was printed on ' +

    RTRIM(CONVERT(varchar(30), GETDATE())) + '.'

See Also
Data Types | RAISERROR
DECLARE @local_variable | Functions


pubs Sample Database

The pubs sample database is modeled after a book publishing company and is used to demonstrate many of the options available for a Microsoft® SQL Server™ database. The database and its tables are commonly used in the examples presented in the documentation content.

If you have made changes to the pubs database, you can reinstall it using files located in the Install directory of your SQL Server installation. The installation process requires two steps:

  1. From the command prompt, use the osql utility to run the Instpubs.sql script. This drops the existing pubs database, creates a new one, and defines all the objects in the database.
  2. From the command prompt, run Pubimage.bat. This inserts image values into the pub_info table.


authors

Column_name | Data type | Nullable | Default | Check | Key/index
au_id | id | no |  | yes (1) | PK, clust.
au_lname | varchar(40) | no |  |  | Composite, nonclust. (3)
au_fname | varchar(20) | no |  |  | Composite, nonclust. (3)
phone | char(12) | no | 'UNKNOWN' |  |
address | varchar(40) | yes |  |  |
city | varchar(20) | yes |  |  |
state | char(2) | yes |  |  |
zip | char(5) | yes |  | yes (2) |
contract | bit | no |  |  |
1The au_id CHECK constraint is defined as (au_id LIKE '[0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9][0-9][0-9]'). 2 The zip CHECK constraint is defined as (zip LIKE '[0-9][0-9][0-9][0-9][0-9]'). 3 The composite, nonclustered index is defined on au_lname and au_fname.

These tables show the contents of the authors table. The first column (au_id) is repeated in the second table, along with columns 5 through 9.

au_id (1) | au_lname (2) | au_fname (3) | phone (4)
172-32-1176 | White | Johnson | 408 496-7223
213-46-8915 | Green | Marjorie | 415 986-7020
238-95-7766 | Carson | Cheryl | 415 548-7723
267-41-2394 | O'Leary | Michael | 408 286-2428
274-80-9391 | Straight | Dean | 415 834-2919
341-22-1782 | Smith | Meander | 913 843-0462
409-56-7008 | Bennet | Abraham | 415 658-9932
427-17-2319 | Dull | Ann | 415 836-7128
472-27-2349 | Gringlesby | Burt | 707 938-6445
486-29-1786 | Locksley | Charlene | 415 585-4620
527-72-3246 | Greene | Morningstar | 615 297-2723
648-92-1872 | Blotchet-Halls | Reginald | 503 745-6402
672-71-3249 | Yokomoto | Akiko | 415 935-4228
712-45-1867 | del Castillo | Innes | 615 996-8275
722-51-5454 | DeFrance | Michel | 219 547-9982
724-08-9931 | Stringer | Dirk | 415 843-2991
724-80-9391 | MacFeather | Stearns | 415 354-7128
756-30-7391 | Karsen | Livia | 415 534-9219
807-91-6654 | Panteley | Sylvia | 301 946-8853
846-92-7186 | Hunter | Sheryl | 415 836-7128
893-72-1158 | McBadden | Heather | 707 448-4982
899-46-2035 | Ringer | Anne | 801 826-0752
998-72-3567 | Ringer | Albert | 801 826-0752

au_id (1) | address (5) | city (6) | state (7) | zip (8) | contract (9)
172-32-1176 | 10932 Bigge Rd. | Menlo Park | CA | 94025 | 1
213-46-8915 | 309 63rd St. #411 | Oakland | CA | 94618 | 1
238-95-7766 | 589 Darwin Ln. | Berkeley | CA | 94705 | 1
267-41-2394 | 22 Cleveland Av. #14 | San Jose | CA | 95128 | 1
274-80-9391 | 5420 College Av. | Oakland | CA | 94609 | 1
341-22-1782 | 10 Mississippi Dr. | Lawrence | KS | 66044 | 0
409-56-7008 | 6223 Bateman St. | Berkeley | CA | 94705 | 1
427-17-2319 | 3410 Blonde St. | Palo Alto | CA | 94301 | 1
472-27-2349 | PO Box 792 | Covelo | CA | 95428 | 1
486-29-1786 | 18 Broadway Av. | San Francisco | CA | 94130 | 1
527-72-3246 | 22 Graybar House Rd. | Nashville | TN | 37215 | 0
648-92-1872 | 55 Hillsdale Bl. | Corvallis | OR | 97330 | 1
672-71-3249 | 3 Silver Ct. | Walnut Creek | CA | 94595 | 1
712-45-1867 | 2286 Cram Pl. #86 | Ann Arbor | MI | 48105 | 1
722-51-5454 | 3 Balding Pl. | Gary | IN | 46403 | 1
724-08-9931 | 5420 Telegraph Av. | Oakland | CA | 94609 | 0
724-80-9391 | 44 Upland Hts. | Oakland | CA | 94612 | 1
756-30-7391 | 5720 McAuley St. | Oakland | CA | 94609 | 1
807-91-6654 | 1956 Arlington Pl. | Rockville | MD | 20853 | 1
846-92-7186 | 3410 Blonde St. | Palo Alto | CA | 94301 | 1
893-72-1158 | 301 Putnam | Vacaville | CA | 95688 | 0
899-46-2035 | 67 Seventh Av. | Salt Lake City | UT | 84152 | 1
998-72-3567 | 67 Seventh Av. | Salt Lake City | UT | 84152 | 1


discounts

Column_name | Data type | Nullable | Default | Check | Key/index
discounttype | varchar(40) | no |  |  |
stor_id | char(4) | yes |  |  | FK stores(stor_id)
lowqty | smallint | yes |  |  |
highqty | smallint | yes |  |  |
discount | float | no |  |  |

discounttype | stor_id | lowqty | highqty | discount
Initial Customer | NULL | NULL | NULL | 10.5
Volume Discount | NULL | 100 | 1000 | 6.7
Customer Discount | 8042 | NULL | NULL | 5.0


employee

Column_name | Data type | Nullable | Default | Check | Key/index
emp_id | empid | no |  | yes (1) | PK, nonclust.
fname | varchar(20) | no |  |  | Composite, clust. (2)
minit | char(1) | yes |  |  | Composite, clust. (2)
lname | varchar(30) | no |  |  | Composite, clust. (2)
job_id | smallint | no | 1 |  | FK jobs(job_id)
job_lvl | tinyint | no | 10 |  |
pub_id | char(4) | no | '9952' |  | FK publishers(pub_id)
hire_date | datetime | no | GETDATE( ) |  |
1 The CHECK constraint is defined as (emp_id LIKE '[A-Z][A-Z][A-Z][1-9][0-9][0-9][0-9][0-9][FM]') OR (emp_id LIKE '[A-Z]-[A-Z][1-9][0-9][0-9][0-9][0-9][FM]'). 2 The composite, clustered index is defined on lname, fname, and minit.

These tables show the contents of the employee table. The first column (emp_id) is repeated in the second table, along with columns 6 through 8.

emp_id (1) | fname (2) | minit (3) | lname (4) | job_id (5)
PMA42628M | Paolo | M | Accorti | 13
PSA89086M | Pedro | S | Alfonso | 14
VPA30890F | Victoria | P | Ashworth | 6
H-B39728F | Helen | NULL | Bennett | 12
L-B31947F | Lesley | NULL | Brown | 7
F-C16315M | Francisco | NULL | Chang | 4
PTC11962M | Philip | T | Cramer | 2
A-C71970F | Aria | NULL | Cruz | 10
AMD15433F | Ann | M | Devon | 3
ARD36773F | Anabela | R | Domingues | 8
PHF38899M | Peter | H | Franken | 10
PXH22250M | Paul | X | Henriot | 5
CFH28514M | Carlos | F | Hernández | 5
PDI47470M | Palle | D | Ibsen | 7
KJJ92907F | Karla | J | Jablonski | 9
KFJ64308F | Karin | F | Josephs | 14
MGK44605M | Matti | G | Karttunen | 6
POK93028M | Pirkko | O | Koskitalo | 10
JYL26161F | Janine | Y | Labrune | 5
M-L67958F | Maria | NULL | Larsson | 7
Y-L77953M | Yoshi | NULL | Latimer | 12
LAL21447M | Laurence | A | Lebihan | 5
ENL44273F | Elizabeth | N | Lincoln | 14
PCM98509F | Patricia | C | McKenna | 11
R-M53550M | Roland | NULL | Mendel | 11
RBM23061F | Rita | B | Müller | 5
HAN90777M | Helvetius | A | Nagy | 7
TPO55093M | Timothy | P | O'Rourke | 13
SKO22412M | Sven | K | Ottlieb | 5
MAP77183M | Miguel | A | Paolino | 11
PSP68661F | Paula | S | Parente | 8
M-P91209M | Manuel | NULL | Pereira | 8
MJP25939M | Maria | J | Pontes | 5
M-R38834F | Martine | NULL | Rancé | 9
DWR65030M | Diego | W | Roel | 6
A-R89858F | Annette | NULL | Roulet | 6
MMS49649F | Mary | M | Saveley | 8
CGS88322F | Carine | G | Schmitt | 13
MAS70474F | Margaret | A | Smith | 9
HAS54740M | Howard | A | Snyder | 12
MFS52347M | Martín | F | Sommer | 10
GHT50241M | Gary | H | Thomas | 9
DBT39435M | Daniel | B | Tonini | 11

emp_id (1) | job_lvl (6) | pub_id (7) | hire_date (8)
PMA42628M | 35 | 0877 | Aug 27 1992 12:00AM
PSA89086M | 89 | 1389 | Dec 24 1990 12:00AM
VPA30890F | 140 | 0877 | Sep 13 1990 12:00AM
H-B39728F | 35 | 0877 | Sep 21 1989 12:00AM
L-B31947F | 120 | 0877 | Feb 13 1991 12:00AM
F-C16315M | 227 | 9952 | Nov 3 1990 12:00AM
PTC11962M | 215 | 9952 | Nov 11 1989 12:00AM
A-C71970F | 87 | 1389 | Oct 26 1991 12:00AM
AMD15433F | 200 | 9952 | Jul 16 1991 12:00AM
ARD36773F | 100 | 0877 | Jan 27 1993 12:00AM
PHF38899M | 75 | 0877 | May 17 1992 12:00AM
PXH22250M | 159 | 0877 | Aug 19 1993 12:00AM
CFH28514M | 211 | 9999 | Apr 21 1989 12:00AM
PDI47470M | 195 | 0736 | May 9 1993 12:00AM
KJJ92907F | 170 | 9999 | Mar 11 1994 12:00AM
KFJ64308F | 100 | 0736 | Oct 17 1992 12:00AM
MGK44605M | 220 | 0736 | May 1 1994 12:00AM
POK93028M | 80 | 9999 | Nov 29 1993 12:00AM
JYL26161F | 172 | 9901 | May 26 1991 12:00AM
M-L67958F | 135 | 1389 | Mar 27 1992 12:00AM
Y-L77953M | 32 | 1389 | Jun 11 1989 12:00AM
LAL21447M | 175 | 0736 | Jun 3 1990 12:00AM
ENL44273F | 35 | 0877 | Jul 24 1990 12:00AM
PCM98509F | 150 | 9999 | Aug 1 1989 12:00AM
R-M53550M | 150 | 0736 | Sep 5 1991 12:00AM
RBM23061F | 198 | 1622 | Oct 9 1993 12:00AM
HAN90777M | 120 | 9999 | Mar 19 1993 12:00AM
TPO55093M | 100 | 0736 | Jun 19 1988 12:00AM
SKO22412M | 150 | 1389 | Apr 5 1991 12:00AM
MAP77183M | 112 | 1389 | Dec 7 1992 12:00AM
PSP68661F | 125 | 1389 | Jan 19 1994 12:00AM
M-P91209M | 101 | 9999 | Jan 9 1989 12:00AM
MJP25939M | 246 | 1756 | Mar 1 1989 12:00AM
M-R38834F | 75 | 0877 | Feb 5 1992 12:00AM
DWR65030M | 192 | 1389 | Dec 16 1991 12:00AM
A-R89858F | 152 | 9999 | Feb 21 1990 12:00AM
MMS49649F | 175 | 0736 | Jun 29 1993 12:00AM
CGS88322F | 64 | 1389 | Jul 7 1992 12:00AM
MAS70474F | 78 | 1389 | Sep 29 1988 12:00AM
HAS54740M | 100 | 0736 | Nov 19 1988 12:00AM
MFS52347M | 165 | 0736 | Apr 13 1990 12:00AM
GHT50241M | 170 | 0736 | Aug 9 1988 12:00AM
DBT39435M | 75 | 0877 | Jan 1 1990 12:00AM


jobs

Column_name | Data type | Nullable | Default | Check | Key/index
job_id | smallint | no | IDENTITY(1,1) |  | PK, clust
stor_id | char(4) | no | yes1 |  |
min_lvl | tinyint | no |  | yes2 |
max_lvl | tinyint | no |  | yes3 |
1 The DEFAULT constraint is defined as (“New Position - title not formalized yet”). 2 The min_lvl CHECK constraint is defined as (min_lvl >= 10). 3 The max_lvl CHECK constraint is defined as (max_lvl <= 250).

This table shows the contents of the jobs table.

job_id | job_desc | min_lvl | max_lvl
1 | New Hire - Job not specified | 10 | 10
2 | Chief Executive Officer | 200 | 250
3 | Business Operations Manager | 175 | 225
4 | Chief Financial Officer | 175 | 250
5 | Publisher | 150 | 250
6 | Managing Editor | 140 | 225
7 | Marketing Manager | 120 | 200
8 | Public Relations Manager | 100 | 175
9 | Acquisitions Manager | 75 | 175
10 | Productions Manager | 75 | 165
11 | Operations Manager | 75 | 150
12 | Editor | 25 | 100
13 | Sales Representative | 25 | 100
14 | Designer | 25 | 100


pub_info

Column_name | Data type | Nullable | Default | Check | Key/index
pub_id | char(4) | no |  |  | PK, clust., FK publishers(pub_id)
logo | image | yes |  |  |
pr_info | text | yes |  |  |

This table shows the contents of the pub_info table.

pub_id | logo (1) | pr_info (2)
0736 | Newmoon.bmp | This is sample text data for New Moon Books, publisher 0736 in the pubs database. New Moon Books is located in Boston, Massachusetts.
0877 | Binnet.bmp | This is sample text data for Binnet & Hardley, publisher 0877 in the pubs database. Binnet & Hardley is located in Washington, D.C.
1389 | Algodata.bmp | This is sample text data for Algodata Infosystems, publisher 1389 in the pubs database. Algodata Infosystems is located in Berkeley, California.
1622 | 5lakes.bmp | This is sample text data for Five Lakes Publishing, publisher 1622 in the pubs database. Five Lakes Publishing is located in Chicago, Illinois.
1756 | Ramona.bmp | This is sample text data for Ramona Publishers, publisher 1756 in the pubs database. Ramona Publishers is located in Dallas, Texas.
9901 | Gggg.bmp | This is sample text data for GGG&G, publisher 9901 in the pubs database. GGG&G is located in München, Germany.
9952 | Scootney.bmp | This is sample text data for Scootney Books, publisher 9952 in the pubs database. Scootney Books is located in New York City, New York.
9999 | Lucerne.bmp | This is sample text data for Lucerne Publishing, publisher 9999 in the pubs database. Lucerne Publishing is located in Paris, France.
1 The information shown here is not the actual data. It is the file name from which the bitmap (image data) was loaded. 2 The text shown here is incomplete. When displaying text data, the display is limited to a finite number of characters. This table shows the first 120 characters of the text column.


publishers

Column_name | Data type | Nullable | Default | Check | Key/index
pub_id | char(4) | no | yes (1) | PK, clust.
pub_name | varchar(40) | yes
city | varchar(20) | yes
state | char(2) | yes
country | varchar(30) | yes | 'USA'
1 The pub_id CHECK constraint is defined as (pub_id = '1756' OR (pub_id = '1622' OR (pub_id ='0877'
OR (pub_id = '0736' OR (pub_id = '1389')))) OR (pub_id LIKE '99[0-9][0-0]').

This table shows the contents of the publishers table.

pub_id | pub_name | city | state | country
0736 | New Moon Books | Boston | MA | USA
0877 | Binnet & Hardley | Washington | DC | USA
1389 | Algodata Infosystems | Berkeley | CA | USA
1622 | Five Lakes Publishing | Chicago | IL | USA
1756 | Ramona Publishers | Dallas | TX | USA
9901 | GGG&G | München | NULL | Germany
9952 | Scootney Books | New York | NY | USA
9999 | Lucerne Publishing | Paris | NULL | France


roysched

Column_name | Data type | Nullable | Default | Check | Key/index
title_id | tid | no |  |  | FK titles(title_id)
lorange | int | yes |  |  |
hirange | int | yes |  |  |
royalty | int | yes |  |  |

This table shows the contents of the roysched table.

title_id | lorange | hirange | royalty
BU1032 | 0 | 5000 | 10
BU1032 | 5001 | 50000 | 12
PC1035 | 0 | 2000 | 10
PC1035 | 2001 | 3000 | 12
PC1035 | 3001 | 4000 | 14
PC1035 | 4001 | 10000 | 16
PC1035 | 10001 | 50000 | 18
BU2075 | 0 | 1000 | 10
BU2075 | 1001 | 3000 | 12
BU2075 | 3001 | 5000 | 14
BU2075 | 5001 | 7000 | 16
BU2075 | 7001 | 10000 | 18
BU2075 | 10001 | 12000 | 20
BU2075 | 12001 | 14000 | 22
BU2075 | 14001 | 50000 | 24
PS2091 | 0 | 1000 | 10
PS2091 | 1001 | 5000 | 12
PS2091 | 5001 | 10000 | 14
PS2091 | 10001 | 50000 | 16
PS2106 | 0 | 2000 | 10
PS2106 | 2001 | 5000 | 12
PS2106 | 5001 | 10000 | 14
PS2106 | 10001 | 50000 | 16
MC3021 | 0 | 1000 | 10
MC3021 | 1001 | 2000 | 12
MC3021 | 2001 | 4000 | 14
MC3021 | 4001 | 6000 | 16
MC3021 | 6001 | 8000 | 18
MC3021 | 8001 | 10000 | 20
MC3021 | 10001 | 12000 | 22
MC3021 | 12001 | 50000 | 24
TC3218 | 0 | 2000 | 10
TC3218 | 2001 | 4000 | 12
TC3218 | 4001 | 6000 | 14
TC3218 | 6001 | 8000 | 16
TC3218 | 8001 | 10000 | 18
TC3218 | 10001 | 12000 | 20
TC3218 | 12001 | 14000 | 22
TC3218 | 14001 | 50000 | 24
PC8888 | 0 | 5000 | 10
PC8888 | 5001 | 10000 | 12
PC8888 | 10001 | 15000 | 14
PC8888 | 15001 | 50000 | 16
PS7777 | 0 | 5000 | 10
PS7777 | 5001 | 50000 | 12
PS3333 | 0 | 5000 | 10
PS3333 | 5001 | 10000 | 12
PS3333 | 10001 | 15000 | 14
PS3333 | 15001 | 50000 | 16
BU1111 | 0 | 4000 | 10
BU1111 | 4001 | 8000 | 12
BU1111 | 8001 | 10000 | 14
BU1111 | 12001 | 16000 | 16
BU1111 | 16001 | 20000 | 18
BU1111 | 20001 | 24000 | 20
BU1111 | 24001 | 28000 | 22
BU1111 | 28001 | 50000 | 24
MC2222 | 0 | 2000 | 10
MC2222 | 2001 | 4000 | 12
MC2222 | 4001 | 8000 | 14
MC2222 | 8001 | 12000 | 16
MC2222 | 12001 | 20000 | 18
MC2222 | 20001 | 50000 | 20
TC7777 | 0 | 5000 | 10
TC7777 | 5001 | 15000 | 12
TC7777 | 15001 | 50000 | 14
TC4203 | 0 | 2000 | 10
TC4203 | 2001 | 8000 | 12
TC4203 | 8001 | 16000 | 14
TC4203 | 16001 | 24000 | 16
TC4203 | 24001 | 32000 | 18
TC4203 | 32001 | 40000 | 20
TC4203 | 40001 | 50000 | 22
BU7832 | 0 | 5000 | 10
BU7832 | 5001 | 10000 | 12
BU7832 | 10001 | 15000 | 14
BU7832 | 15001 | 20000 | 16
BU7832 | 20001 | 25000 | 18
BU7832 | 25001 | 30000 | 20
BU7832 | 30001 | 35000 | 22
BU7832 | 35001 | 50000 | 24
PS1372 | 0 | 10000 | 10
PS1372 | 10001 | 20000 | 12
PS1372 | 20001 | 30000 | 14
PS1372 | 30001 | 40000 | 16
PS1372 | 40001 | 50000 | 18


sales

Column_name | Data type | Nullable | Key/index
stor_id | char(4) | no | Composite PK, clust. (1) , FK stores(stor_id)
ord_num | varchar(20) | no | Composite PK, clust. (1)
ord_date | datetime | no |
qty | smallint | no |
payterms | varchar(12) | no |
title_id | tid | no | Composite PK, clust. (1) , FK titles(title_id)
1 The composite, primary key, clustered index is defined on stor_id, ord_num, and title_id.

This table shows the contents of the sales table.

stor_id | ord_num | ord_date | qty | payterms | title_id
6380 | 6871 | Sep 14 1994 12:00AM | 5 | Net 60 | BU1032
6380 | 722a | Sep 13 1994 12:00AM | 3 | Net 60 | PS2091
7066 | A2976 | May 24 1993 12:00AM | 50 | Net 30 | PC8888
7066 | QA7442.3 | Sep 13 1994 12:00AM | 75 | ON invoice | PS2091
7067 | D4482 | Sep 14 1994 12:00AM | 10 | Net 60 | PS2091
7067 | P2121 | Jun 15 1992 12:00AM | 40 | Net 30 | TC3218
7067 | P2121 | Jun 15 1992 12:00AM | 20 | Net 30 | TC4203
7067 | P2121 | Jun 15 1992 12:00AM | 20 | Net 30 | TC7777
7131 | N914008 | Sep 14 1994 12:00AM | 20 | Net 30 | PS2091
7131 | N914014 | Sep 14 1994 12:00AM | 25 | Net 30 | MC3021
7131 | P3087a | May 29 1993 12:00AM | 20 | Net 60 | PS1372
7131 | P3087a | May 29 1993 12:00AM | 25 | Net 60 | PS2106
7131 | P3087a | May 29 1993 12:00AM | 15 | Net 60 | PS3333
7131 | P3087a | May 29 1993 12:00AM | 25 | Net 60 | PS7777
7896 | QQ2299 | Oct 28 1993 12:00AM | 15 | Net 60 | BU7832
7896 | TQ456 | Dec 12 1993 12:00AM | 10 | Net 60 | MC2222
7896 | X999 | Feb 21 1993 12:00AM | 35 | ON invoice | BU2075
8042 | 423LL922 | Sep 14 1994 12:00AM | 15 | ON invoice | MC3021
8042 | 423LL930 | Sep 14 1994 12:00AM | 10 | ON invoice | BU1032
8042 | P723 | Mar 11 1993 12:00AM | 25 | Net 30 | BU1111
8042 | QA879.1 | May 22 1993 12:00AM | 30 | Net 30 | PC1035


stores

Column_name | Data type | Nullable | Default | Check | Key/index
stor_id | char(4) | no |  |  | PK, clust.
stor_name | varchar(40) | yes |  |  |
stor_address | varchar(40) | yes |  |  |
city | varchar(20) | yes |  |  |
state | char(2) | yes |  |  |
zip | char(5) | yes |  |  |

This table shows the contents of the stores table.

stor_id | stor_name | stor_address | city | state | zip
6380 | Eric the Read Books | 788 Catamaugus Ave. | Seattle | WA | 98056
7066 | Barnum’s | 567 Pasadena Ave. | Tustin | CA | 92789
7067 | News & Brews | 577 First St. | Los Gatos | CA | 96745
7131 | Doc-U-Mat: Quality Laundry and Books | 24-A Avrogado Way | Remulade | WA | 98014
7896 | Fricative Bookshop | 89 Madison St. | Fremont | CA | 90019
8042 | Bookbeat | 679 Carson St. | Portland | OR | 89076


titleauthor

Column_name | Data type | Nullable | Default | Check | Key/index
au_id | id | no |  |  | Composite PK, clust. (1) , FK authors(au_id) (2)
title_id | tid | no |  |  | Composite PK, clust. (1) , FK titles(title_id) (3)
au_ord | tinyint | yes |  |  |
royaltyper | int | yes |  |  |
1 The composite, primary key, clustered index is defined on au_id and title_id. 2 This foreign key also has a nonclustered index on au_id. 3 This foreign key also has a nonclustered index on title_id.

This table shows the contents of the titleauthor table.

au_id | title_id | au_ord | royaltyper
172-32-1176 | PS3333 | 1 | 100
213-46-8915 | BU1032 | 2 | 40
213-46-8915 | BU2075 | 1 | 100
238-95-7766 | PC1035 | 1 | 100
267-41-2394 | BU1111 | 2 | 40
267-41-2394 | TC7777 | 2 | 30
274-80-9391 | BU7832 | 1 | 100
409-56-7008 | BU1032 | 1 | 60
427-17-2319 | PC8888 | 1 | 50
472-27-2349 | TC7777 | 3 | 30
486-29-1786 | PC9999 | 1 | 100
486-29-1786 | PS7777 | 1 | 100
648-92-1872 | TC4203 | 1 | 100
672-71-3249 | TC7777 | 1 | 40
712-45-1867 | MC2222 | 1 | 100
722-51-5454 | MC3021 | 1 | 75
724-80-9391 | BU1111 | 1 | 60
724-80-9391 | PS1372 | 2 | 25
756-30-7391 | PS1372 | 1 | 75
807-91-6654 | TC3218 | 1 | 100
846-92-7186 | PC8888 | 2 | 50
899-46-2035 | MC3021 | 2 | 25
899-46-2035 | PS2091 | 2 | 50
998-72-3567 | PS2091 | 1 | 50
998-72-3567 | PS2106 | 1 | 100


titles

Column_name | Data type | Nullable | Default | Check | Key/index
title_id | tid | no |  |  | PK, clust.
title | varchar(80) | no |  |  | Nonclust.
type | char(12) | no | 'UNDECIDED' |  |
pub_id | char(4) | yes |  |  | FK publishers (pub_id)
price | money | yes |  |  |
advance | money | yes |  |  |
royalty | int | yes |  |  |
ytd_sales | int | yes |  |  |
notes | varchar(200) | yes |  |  |
pubdate | datetime | no | GETDATE( ) |  |

These tables show the contents of the titles table. The first column (title_id) is repeated in the tables that follow, along with columns 6 through 8, and 9 through 10.

title_id (1) | title (2) | type (3) | pub_id (4) | price (5)
BU1032 | The Busy Executive’s Database Guide | business | 1389 | 19.99
BU1111 | Cooking with Computers: Surreptitious Balance Sheets | business | 1389 | 11.95
BU2075 | You Can Combat Computer Stress! | business | 0736 | 2.99
BU7832 | Straight Talk About Computers | business | 1389 | 19.99
MC2222 | Silicon Valley Gastronomic Treats | mod_cook | 0877 | 19.99
MC3021 | The Gourmet Microwave | mod_cook | 0877 | 2.99
MC3026 | The Psychology of Computer Cooking | UNDECIDED | 0877 | NULL
PC1035 | But Is It User Friendly? | popular_comp | 1389 | 22.95
PC8888 | Secrets of Silicon Valley | popular_comp | 1389 | 20.00
PC9999 | Net Etiquette | popular_comp | 1389 | NULL
PS1372 | Computer Phobic and Non-Phobic Individuals: Behavior Variations | psychology | 0877 | 21.59
PS2091 | Is Anger the Enemy? | psychology | 0736 | 10.95
PS2106 | Life Without Fear | psychology | 0736 | 7.00
PS3333 | Prolonged Data Deprivation: Four Case Studies | psychology | 0736 | 19.99
PS7777 | Emotional Security: A New Algorithm | psychology | 0736 | 7.99
TC3218 | Onions, Leeks, and Garlic: Cooking Secrets of the Mediterranean | trad_cook | 0877 | 20.95
TC4203 | Fifty Years in Buckingham Palace Kitchens | trad_cook | 0877 | 11.95
TC7777 | Sushi, Anyone? | trad_cook | 0877 | 14.99

title_id (1) | advance (6) | royalty (7) | ytd_sales (8)
BU1032 | 5,000.00 | 10 | 4095
BU1111 | 5,000.00 | 10 | 3876
BU2075 | 10,125.00 | 24 | 18722
BU7832 | 5,000.00 | 10 | 4095
MC2222 | 0.00 | 12 | 2032
MC3021 | 15,000.00 | 24 | 22246
MC3026 | NULL | NULL | NULL
PC1035 | 7,000.00 | 16 | 8780
PC8888 | 8,000.00 | 10 | 4095
PC9999 | NULL | NULL | NULL
PS1372 | 7,000.00 | 10 | 375
PS2091 | 2,275.00 | 12 | 2045
PS2106 | 6,000.00 | 10 | 111
PS3333 | 2,000.00 | 10 | 4072
PS7777 | 4,000.00 | 10 | 3336
TC3218 | 7,000.00 | 10 | 375
TC4203 | 4,000.00 | 14 | 15096
TC7777 | 8,000.00 | 10 | 4095

title_id (1) | notes (9) | pubdate (10)
BU1032 | An overview of available database systems with emphasis on common business applications. Illustrated. | Jun 12 1991 12:00AM
BU1111 | Helpful hints on how to use your electronic resources to the best advantage. | Jun 9 1991 12:00AM
BU2075 | The latest medical and psychological techniques for living with the electronic office. Easy-to-understand explanations. | Jun 30 1991 12:00AM
BU7832 | Annotated analysis of what computers can do for you: a no-hype guide for the critical user. | Jun 22 1991 12:00AM
MC2222 | Favorite recipes for quick, easy, and elegant meals. | Jun 9 1991 12:00AM
MC3021 | Traditional French gourmet recipes adapted for modern microwave cooking. | Jun 18 1991 12:00AM
MC3026 | NULL | Apr 28 1995 10:36AM
PC1035 | A survey of software for the naive user, focusing on the “friendliness” of each. | Jun 30 1991 12:00AM
PC8888 | Muckraking reporting on the world’s largest computer hardware and software manufacturers. | Jun 12 1994 12:00AM
PC9999 | A must-read for computer conferencing. | Apr 28 1995 10:36AM
PS1372 | A must for the specialist, examining the difference between those who hate and fear computers and those who don’t. | Oct 21 1991 12:00AM
PS2091 | Carefully researched study of the effects of strong emotions on the body. Metabolic charts included. | Jun 15 1991 12:00AM
PS2106 | New exercise, meditation, and nutritional techniques that can reduce the shock of daily interactions. Popular audience. Sample menus included, exercise video available separately. | Oct 5 1991 12:00AM
PS3333 | What happens when the data runs dry? Searching evaluations of information-shortage effects. | Jun 12 1991 12:00AM
PS7777 | Protecting yourself and your loved ones from undue emotional stress in the modern world. Use of computer and nutritional aids emphasized. | Jun 12 1991 12:00AM
TC3218 | Profusely illustrated in color, this makes a wonderful gift book for a cuisine-oriented friend. | Oct 21 1991 12:00AM
TC4203 | More anecdotes from the Queen’s favorite cook describing life among English royalty. Recipes, techniques, tender vignettes. | Jun 12 1991 12:00AM
TC7777 | Detailed instructions on how to make authentic Japanese sushi in your spare time. | Jun 12 1991 12:00AM


QUOTENAME

Returns a Unicode string with the delimiters added to make the input string a valid Microsoft® SQL Server™ delimited identifier.

Syntax

QUOTENAME('character_string'[, 'quote_character'])

Arguments
'character_string'
Is a string of Unicode character data. character_string is sysname.
'quote_character'
Is a one-character string to use as the delimiter. Can be a single quotation mark (‘), a left or right bracket ([]), or a double quotation mark (“). If quote_character is not specified, brackets are used.
Return Types

nvarchar(129)

Examples

This example takes the character string abc[]def and uses the [ and ] characters to create a valid SQL Server quoted (delimited) identifier.

SELECT QUOTENAME('abc[]def')

Here is the result set:

[abc[]]def]

(1 row(s) affected)

Notice that the right bracket in the string abc[]def is doubled to indicate an escape character.

See Also

String Functions


RADIANS

Returns radians given a numeric expression in degrees.

Syntax

RADIANS(numeric_expression)

Arguments
numeric_expression
Is an expression of the exact numeric or approximate numeric data type category, except for the bit data type.
Return Types

Returns the same type as numeric_expression.

Examples
A. Use RADIANS to show 0.0

This example returns a result of 0.0 because the numeric expression to convert to radians is too small for the RADIANS function.

SELECT RADIANS(1e-307)

GO

Here is the result set:

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

0.0

(1 row(s) affected)

B. Use RADIANS

This example takes a float expression and returns the RADIANS of the given angle.

-- First value is -45.01.

DECLARE @angle float

SET @angle = -45.01

SELECT 'The RADIANS of the angle is: ' +
    CONVERT(varchar, RADIANS(@angle))

GO

-- Next value is -181.01.

DECLARE @angle float

SET @angle = -181.01

SELECT 'The RADIANS of the angle is: ' +
    CONVERT(varchar, RADIANS(@angle))

GO

-- Next value is 0.00.

DECLARE @angle float

SET @angle = 0.00

SELECT 'The RADIANS of the angle is: ' +
    CONVERT(varchar, RADIANS(@angle))

GO

-- Next value is 0.1472738.

DECLARE @angle float

SET @angle = 0.1472738

SELECT 'The RADIANS of the angle is: ' +
     CONVERT(varchar, RADIANS(@angle))

GO

-- Last value is 197.1099392.

DECLARE @angle float

SET @angle = 197.1099392

SELECT 'The RADIANS of the angle is: ' +
    CONVERT(varchar, RADIANS(@angle))

GO

Here is the result set:

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

The RADIANS of the angle is: -0.785573

(1 row(s) affected)

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

The RADIANS of the angle is: -3.15922

(1 row(s) affected)

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

The RADIANS of the angle is: 0

(1 row(s) affected)

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

The RADIANS of the angle is: 0.00257041

 (1 row(s) affected)

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

The RADIANS of the angle is: 3.44022

(1 row(s) affected)

See Also
CAST and CONVERT | int, smallint, and tinyint
decimal and numeric | money and smallmoney
float and real | Mathematical Functions


RAISERROR

Returns a user-defined error message and sets a system flag to record that an error has occurred. Using RAISERROR, the client can either retrieve an entry from the sysmessages table or build a message dynamically with user-specified severity and state information. After the message is defined it is sent back to the client as a server error message.

Syntax

RAISERROR ({msg_id | msg_str}{, severity, state}
[, argument
[,…n]] )
[WITH option[,…n]]

Arguments
msg_id
Is a user-defined error message stored in the sysmessages table. Error numbers for user-defined error messages should be greater than 50,000. Ad hoc messages raise an error of 50,000. The maximum value for msg_id is 2,147,483,647 (2 (31) - 1).
msg_str
Is an ad hoc message with formatting similar to the PRINTF format style used in C. The error message can have as many as 8,000 characters. All ad hoc messages have a standard message ID of 14,000.

This format is supported for msg_str:

% [[flag] [width] [precision] [{h | l}]] type

The parameters that can be used in msg_str are:

flag
Is a code that determines the spacing and justification of the user-defined error message.

Code | Prefix or justification | Description
- (minus) | Left-justified | Left-justify the result within the given field width.
+ (plus) | + (plus) or - (minus) prefix | Preface the output value with a + or - sign if the output value is of signed type.
0 (zero) | Zero padding | If width is prefaced with 0, zeros are added until the minimum width is reached. When 0 and - appear, 0 is ignored. When 0 is specified with an integer format (i, u, x, X, o, d), 0 is ignored.
# (number) | 0x prefix for hexadecimal type of x or X | When used with the o, x, or X format, the # flag prefaces any nonzero value with 0, 0x, or 0X, respectively. When d, i, or u are prefaced by the # flag, the flag is ignored.
‘ ‘ (blank) | Space padding | Preface the output value with blank spaces if the value is signed and positive. This is ignored when included with the + flag.

width
Is an integer defining the minimum width. An asterisk (*) allows precision to determine the width.
precision
Is the maximum number of characters printed for the output field or the minimum number of digits printed for integer values. An asterisk (*) allows argument to determine the precision.
{h | l} type
Is used with types d, i, o, x, X, or u, and creates short int (h) or long int (l) values.

Character type | Represents
d or i | Signed integer
o | Unsigned octal
p | Pointer
s | String
u | Unsigned integer
x or X | Unsigned hexadecimal

Note The float, double-, and single-character types are not supported.

severity
Is the user-defined severity level associated with this message. Severity levels from 0 through 18 can be used by any user. Severity levels 19 through 25 are used only by members of the sysadmin fixed server role. For severity levels 19 through 25, the WITH LOG option is required.

Caution Severity levels 20 through 25 are considered fatal. If a fatal severity level is encountered, the client connection is terminated after receiving the message, and the error is logged in the error log and the application log.

state
Is an arbitrary integer from 1 through 127 that represents information about the invocation state of the error. A negative value for state defaults to 1.
argument
Is the parameters used in the substitution for variables defined in msg_str or the message corresponding to msg_id. There can be 0 or more substitution parameters; however, the total number of substitution parameters cannot exceed 20. Each substitution parameter can be a local variable or any of these data types: int1, int2, int4, char, varchar, binary, or varbinary. No other data types are supported.
option
Is a custom option for the error. option can be one of these values.

Value | Description
LOG | Logs the error in the server error log and the application log. Errors logged in the server error log are currently limited to a maximum of 440 bytes.
NOWAIT | Sends messages immediately to the client.
SETERROR | Sets @@ERROR value to msg_id or 50000, regardless of the severity level.

Remarks

If a sysmessages error is used and the message was created using the format shown for msg_str, the supplied arguments (argument1, argument2, and so on) are passed to the message of the supplied msg_id.

When you use RAISERROR to create and return user-defined error messages, use sp_addmessage to add user-defined error messages and sp_dropmessage to delete user-defined error messages.

When an error is raised, the error number is placed in the @@ERROR function, which stores the most recently generated error number. @@ERROR is set to 0 by default for messages with a severity of 1 through 10.

Examples
A. Create an ad hoc message

This example shows two errors that can be raised. The first is a simple error with a static message. The second error is dynamically built based on the attempted modification.

CREATE TRIGGER employee_insupd

ON employee

FOR INSERT, UPDATE

AS

/* Get the range of level for this job type from the jobs table. */

DECLARE @@MIN_LVL tinyint,

    @@MAX_LVL tinyint,

    @@EMP_LVL tinyint,

    @@JOB_ID smallint

SELECT @@MIN_LVl = min_lvl,

    @@MAX_LV = max_lvl,

    @@ EMP_LVL = i.job_lvl,

    @@JOB_ID = i.job_id

FROM employee e, jobs j, inserted i

WHERE e.emp_id = i.emp_id AND i.job_id = j.job_id

IF (@@JOB_ID = 1) and (@@EMP_lVl <> 10)

BEGIN

    RAISERROR ('Job id 1 expects the default level of 10.', 16, 1)

    ROLLBACK TRANSACTION

END

ELSE

IF NOT @@ EMP_LVL BETWEEN @@MIN_LVL AND @@MAX_LVL)

BEGIN

    RAISERROR ('The level for job_id:%d should be between %d and %d.',
        16, 1, @@JOB_ID, @@MIN_LVL, @@MAX_LVL)

    ROLLBACK TRANSACTION

END

B. Create an ad hoc message in sysmessages

This example shows how to achieve the same results with RAISERROR using parameters passed to a message stored in the sysmessages table by executing the employee_insupd trigger. The message was added to the sysmessages table with the sp_addmessage system stored procedure as message number 50005.

Note This example is shown for illustration only.

RAISERROR (50005, 16, 1, @@JOB_ID, @@MIN_LVL, @@MAX_LVL)

C. Use SETERROR with ad hoc and system messages

The first RAISERROR returns an @@ERROR value of 50000. The second returns the syntax error message used by Microsoft® SQL Server™ with an @@ERROR value of 101.

RAISERROR('Test Only', 1, 2) WITH SETERROR

SELECT @@ERROR

RAISERROR (101, 1, 2) WITH SETERROR

SELECT @@ERROR

Here is the result set:

Msg 50000, Level 1, State 50000

Test Only

-----------

50000

(1 row(s) affected)

Msg 101, Level 1, State 101

Line 0: SQL syntax error.

-----------

101

(1 row(s) affected)

See Also
DECLARE @local_variable | sp_dropmessage
PRINT | xp_logevent
sp_addmessage | Functions
sysmessages |


RAND

Returns a random float value between 0 and 1.

Syntax

RAND([seed])

Arguments
seed
Is an integer expression (tinyint, smallint, or int) giving the seed or starting value.
Return Types

float

Examples

This example uses a variable to produce five different random numbers generated with the RAND function.

DECLARE @counter smallint

SET @counter = 1

WHILE @counter < 5

    BEGIN

        SELECT RAND(@counter)

        SET NOCOUNT ON

        SET @counter = @counter + 1

        SET NOCOUNT OFF

    END

GO

Here is the result set:

(1 row(s) affected)

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

0.00125125888851588

(1 row(s) affected)

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

0.00137333292641987

(1 row(s) affected)

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

0.00146488845484787

(1 row(s) affected)

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

0.00155644398327586

(1 row(s) affected)

See Also

Mathematical Functions


READTEXT

Reads text, ntext, or image values from a text, ntext, or image column, starting from a specified offset and reading the specified number of bytes.

Syntax

READTEXT {table.column text_ptr offset size} [HOLDLOCK]

Arguments
table.column
Is the name of a table and column from which to read. Table and column names must conform to the rules for identifiers. Specifying the table and column names is required; however, specifying the database name and owner names is optional.
text_ptr
Is a valid text pointer. text_ptr must be binary(16).
offset
Is the number of bytes (when using the text or image data types) or characters (when using the ntext data type) to skip before starting to read the text, image, or ntext data. When using ntext data type, offset is the number of characters to skip before starting to read the data. When using text or image data types, offset is the number of bytes to skip before starting to read the data.
size
Is the number of bytes (when using the text or image data types) or characters (when using the ntext data type) of data to read. If size is 0, 4 KB bytes of data are read.
HOLDLOCK
Causes the text value to be locked for reads until the end of the transaction. Other users can read the value, but they cannot modify it.
Remarks

Use the TEXTPTR function to obtain a valid text_ptr value. TEXTPTR returns a pointer to the text, ntext, or image column in the specified row or to the text, ntext, or image column in the last row returned by the query if more than one row is returned. Because TEXTPTR returns a 16-byte binary string, it is best to declare a local variable to hold the text pointer and then use the variable with READTEXT. For more information about declaring a local variable, see DECLARE @local_variable.

The value of the @@TEXTSIZE function supersedes the size specified for READTEXT if it is less than the specified size for READTEXT. The @@TEXTSIZE function is the limit on the number of bytes of data to be returned set by the SET TEXTSIZE statement. For more information about how to set the session setting for TEXTSIZE, see SET TEXTSIZE.

Permissions

READTEXT permissions default to users with SELECT permissions on the specified table. Permissions are transferable when SELECT permissions are transferred.

Examples

This example reads the second through twenty-sixth characters of the pr_info column in the pub_info table.

USE pubs

GO

DECLARE @ptrval varbinary(16)

SELECT @ptrval = TEXTPTR(pr_info)

    FROM pub_info pr INNER JOIN publishers p

        ON pr.pub_id = p.pub_id

        AND p.pub_name = 'New Moon Books'

READTEXT pub_info.pr_info @ptrval 1 25

GO

See Also
@@TEXTSIZE | WRITETEXT
UPDATETEXT |


real

For information about the real data type, see float and real.

See Also
Data Types


RECONFIGURE

Updates the currently configured (the config_value column in the sp_configure result set) value of a configuration option changed with the sp_configure system stored procedure. Because some configuration options require a server stop and restart to update the currently running value, RECONFIGURE does not always update the currently running value (the run_value column in the sp_configure result set) for a changed configuration value.

Syntax

RECONFIGURE [WITH OVERRIDE]

Arguments
RECONFIGURE
Specifies that, if the configuration setting does not require a server stop and restart, the currently running value should be updated. RECONFIGURE also checks the new configuration value for either invalid values (for example, a sort order value that does not exist in syscharsets) or nonrecommended values (for example, setting allow updates to 1). With those configuration options not requiring a server stop and restart, the currently running value and the currently configured values for the configuration option should be the same value after specifying RECONFIGURE.
WITH OVERRIDE
Disables the configuration value checking (for invalid values or for nonrecommended values) for the allow updates, recovery interval, or time slice advanced configuration options. In addition, RECONFIGURE WITH OVERRIDE forces the reconfiguration with the specified value. For example, the min server memory configuration option could be configured with a value greater than the value specified in the max server memory configuration option. However, this is considered a fatal error. Therefore, specifying RECONFIGURE WITH OVERRIDE would not disable configuration value checking. Any configuration option can be reconfigured using the WITH OVERRIDE option.
Remarks

sp_configure disallows new configuration option values that are out of the documented valid ranges for each configuration option.

Permissions

RECONFIGURE permissions default to members of the sysadmin fixed server role, and are not transferable.

Examples

This example sets the upper limit for the network packet size configuration option and uses RECONFIGURE WITH OVERRIDE to install it. Because the WITH OVERRIDE option is specified, Microsoft® SQL Server™ does not check the value specified (8192) to see if it is a valid value for the network packet size configuration option.

EXEC sp_configure 'network packet size', 8192

RECONFIGURE WITH OVERRIDE

GO

See Also
sp_configure


REPLACE

Replaces all occurrences of the second given string expression in the first string expression with a third expression.

Syntax

REPLACE('string_expression1', 'string_expression2', 'string_expression3')

Arguments
'string_expression1'
Is the string expression to search for string_expression2. string_expression1 can be of character or binary data.
'string_expression2'
Is the string expression for which to search in string_expression1 and to replace with string_expression3. string_expression2 can be of character or binary data.
'string_expression3'
Is the new string expression that replaces string_expression2 in string_expression1. string_expression3 can be of character or binary data.
Return Types

Returns character data if string_expression (1, 2, or 3) is one of the supported character data types. Returns binary data if string_expression (1, 2, or 3) is one of the supported binary data types.

Examples

This example replaces the string cde in abcdefghi with xxx.

SELECT REPLACE('abcdefghicde','cde','xxx')

GO

Here is the result set:

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

abxxxfghixxx

(1 row(s) affected)

See Also
Data Types String Functions


REPLICATE

Repeats a character expression a specified number of times.

Syntax

REPLICATE(character_expression, integer_expression)

Arguments
character_expression
Is an alphanumeric expression of character data. character_expression can be a constant, variable, or column of either character or binary data.
integer_expression
Is a positive whole number. If integer_expression is negative, a null string is returned.
Return Types

varchar

character_expression must be of a data type that is implicitly convertible to varchar. Otherwise, use the CAST function to convert explicitly character_expression.

Remarks

Compatibility levels can affect return values. For more information, see sp_dbcmptlevel.

Examples
A. Use REPLICATE

This example replicates each author’s first name twice.

USE pubs

SELECT REPLICATE(au_fname, 2)

FROM authors

ORDER BY au_fname

Here is the result set:

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

AbrahamAbraham

AkikoAkiko

AlbertAlbert

AnnAnn

AnneAnne

BurtBurt

CharleneCharlene

CherylCheryl

DeanDean

DirkDirk

HeatherHeather

InnesInnes

JohnsonJohnson

LiviaLivia

MarjorieMarjorie

MeanderMeander

MichaelMichael

MichelMichel

MorningstarMorningstar

ReginaldReginald

SherylSheryl

StearnsStearns

SylviaSylvia

(23 row(s) affected)

B. Use REPLICATE, SUBSTRING, and SPACE

This example uses REPLICATE, SUBSTRING, and SPACE to produce a telephone and fax listing of all authors in the authors table.

-- Replicate phone number twice since the fax number is identical to

-- the author's telephone number.

USE pubs

GO

SELECT SUBSTRING((UPPER(au_lname) + ',' + SPACE(1) + au_fname), 1, 35)
    AS Name, phone AS Phone, REPLICATE(phone,1) AS Fax

FROM authors

ORDER BY au_lname, au_fname

GO

Here is the result set:

Name                                Phone        Fax

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

BENNET, Abraham                     415 658-9932 415 658-9932

BLOTCHET-HALLS, Reginald            503 745-6402 503 745-6402

CARSON, Cheryl                      415 548-7723 415 548-7723

DEFRANCE, Michel                    219 547-9982 219 547-9982

DEL CASTILLO, Innes                 615 996-8275 615 996-8275

DULL, Ann                           415 836-7128 415 836-7128

GREEN, Marjorie                     415 986-7020 415 986-7020

GREENE, Morningstar                 615 297-2723 615 297-2723

GRINGLESBY, Burt                    707 938-6445 707 938-6445

HUNTER, Sheryl                      415 836-7128 415 836-7128

KARSEN, Livia                       415 534-9219 415 534-9219

LOCKSLEY, Charlene                  415 585-4620 415 585-4620

MACFEATHER, Stearns                 415 354-7128 415 354-7128

MCBADDEN, Heather                   707 448-4982 707 448-4982

O'LEARY, Michael                    408 286-2428 408 286-2428

PANTELEY, Sylvia                    301 946-8853 301 946-8853

RINGER, Albert                      801 826-0752 801 826-0752

RINGER, Anne                        801 826-0752 801 826-0752

SMITH, Meander                      913 843-0462 913 843-0462

STRAIGHT, Dean                      415 834-2919 415 834-2919

STRINGER, Dirk                      415 843-2991 415 843-2991

WHITE, Johnson                      408 496-7223 408 496-7223

YOKOMOTO, Akiko                     415 935-4228 415 935-4228

(23 row(s) affected)

See Also
Data Types String Functions


Reserved Keywords

Microsoft® SQL Server™ uses reserved keywords for defining, manipulating, or accessing databases. Reserved keywords are part of the grammar of the Transact-SQL language used by SQL Server to parse and understand Transact-SQL statements and batches. Although it is syntactically possible to use SQL Server reserved keywords as identifiers and object names in Transact-SQL scripts, this can be done only by using delimited identifiers.

The SQL Server reserved keywords are:

ADD | FETCH | PRINT
ALL | FILE | PRIVILEGES
ALTER | FILLFACTOR | PROC
AND | FLOPPY | PROCEDURE
ANY | FOR | PROCESSEXIT
AS | FOREIGN | PUBLIC
ASC | FORWARD | RAISERROR
AUTHORIZATION | FREETEXT | READ
AVG | FREETEXTTABLE | READTEXT
BACKUP | FROM | RECONFIGURE
BEGIN | FULL | REFERENCES
BETWEEN | GOTO | REMOTE
BREAK | GRANT | REPEATABLE
BROWSE | GROUP | REPLICATION
BULK | HAVING | RESTORE
BY | HOLDLOCK | RESTRICT
CASCADE | IDENTITY | RETURN
CASE | IDENTITY_INSERT | REVOKE
CHECK | IDENTITYCOL | RIGHT
CHECKPOINT | IF | ROLLBACK
CLOSE | IN | ROWCOUNT
CLUSTERED | INDEX | ROWGUIDCOL
COALESCE | INNER | RULE
COLUMN | INSERT | SAVE
COMMIT | INTERSECT | SCHEMA
COMMITTED | INTO | SELECT
COMPUTE | IS | SERIALIZABLE
CONFIRM | ISOLATION | SESSION_USER
CONSTRAINT | JOIN | SET
CONTAINS | KEY | SETUSER
CONTAINSTABLE | KILL | SHUTDOWN
CONTINUE | LEFT | SOME
CONTROLROW | LEVEL | SQUARE
CONVERT | LIKE | STATIC
COUNT | LINENO | STATISTICS
CREATE | LOAD | SUM
CROSS | MAX | SYSTEM_USER
CURRENT | MIN | TABLE
CURRENT_DATE | MIRROREXIT | TAPE
CURRENT_TIME | NATIONAL | TEMP
CURRENT_TIMESTAMP | NOCHECK | TEMPORARY
CURRENT_USER | NONCLUSTERED | TEXTSIZE
CURSOR | NOT | THEN
DATABASE | NULL | TO
DBCC | NULLIF | TOP
DEALLOCATE | OF | TRAN
DECLARE | OFF | TRANSACTION
DEFAULT | OFFSETS | TRIGGER
DELETE | ON | TRUNCATE
DENY | ONCE | TSEQUAL
DESC | ONLY | UNCOMMITTED
DISK | OPEN | UNION
DISTINCT | OPENDATASOURCE | UNIQUE
DISTRIBUTED | OPENQUERY | UPDATE
DOUBLE | OPENROWSET | UPDATETEXT
DROP | OPTION | USE
DUMMY | OR | USER
DUMP | ORDER | VALUES
ELSE | OUTER | VARYING
END | OVER | VIEW
ERRLVL | PERCENT | WAITFOR
ERROREXIT | PERM | WHEN
ESCAPE | PERMANENT | WHERE
EXCEPT | PIPE | WHILE
EXEC | PLAN | WITH
EXECUTE | PRECISION | WORK
EXISTS | PREPARE | WRITETEXT
EXIT | PRIMARY |

In addition, the SQL-92 standard defines a list of reserved keywords. It is recommended that you avoid using SQL-92 reserved keywords for object names and identifiers. The ODBC reserved keyword list (shown below) is the same as the SQL-92 reserved keyword list.

Note The SQL-92 reserved keywords list sometimes can be more restrictive than SQL Server and at other times less restrictive. For example, the SQL-92 reserved keywords list contains INT, which SQL Server does not need to distinguish as a reserved keyword.

Transact-SQL reserved keywords can be used as identifiers or names of databases or database objects, such as tables, columns, views, and so on. Use either quoted identifiers or delimited identifiers. The use of reserved keywords as the names of variables and stored procedure parameters is not restricted.

ODBC Reserved Keywords

The following words are reserved for use in ODBC function calls. These words do not constrain the minimum SQL grammar; however, to ensure compatibility with drivers that support the core SQL grammar, applications should avoid using these keywords.

This is the current list of ODBC reserved keywords. For more information, see Microsoft ODBC 3.0 Programmer’s Reference, Volume 2, Appendix C.

ABSOLUTE | EXEC | OVERLAPS
ACTION | EXECUTE | PAD
ADA | EXISTS | PARTIAL
ADD | EXTERNAL | PASCAL
ALL | EXTRACT | POSITION
ALLOCATE | FALSE | PRECISION
ALTER | FETCH | PREPARE
AND | FIRST | PRESERVE
ANY | FLOAT | PRIMARY
ARE | FOR | PRIOR
AS | FOREIGN | PRIVILEGES
ASC | FORTRAN | PROCEDURE
ASSERTION | FOUND | PUBLIC
AT | FROM | READ
AUTHORIZATION | FULL | REAL
AVG | GET | REFERENCES
BEGIN | GLOBAL | RELATIVE
BETWEEN | GO | RESTRICT
BIT | GOTO | REVOKE
BIT_LENGTH | GRANT | RIGHT
BOTH | GROUP | ROLLBACK
BY | HAVING | ROWS
CASCADE | HOUR | SCHEMA
CASCADED | IDENTITY | SCROLL
CASE | IMMEDIATE | SECOND
CAST | IN | SECTION
CATALOG | INCLUDE | SELECT
CHAR | INDEX | SESSION
CHAR_LENGTH | INDICATOR | SESSION_USER
CHARACTER | INITIALLY | SET
CHARACTER_LENGTH | INNER | SIZE
CHECK | INPUT | SMALLINT
CLOSE | INSENSITIVE | SOME
COALESCE | INSERT | SPACE
COLLATE | INT | SQL
COLLATION | INTEGER | SQLCA
COLUMN | INTERSECT | SQLCODE
COMMIT | INTERVAL | SQLERROR
CONNECT | INTO | SQLSTATE
CONNECTION | IS | SQLWARNING
CONSTRAINT | ISOLATION | SUBSTRING
CONSTRAINTS | JOIN | SUM
CONTINUE | KEY | SYSTEM_USER
CONVERT | LANGUAGE | TABLE
CORRESPONDING | LAST | TEMPORARY
COUNT | LEADING | THEN
CREATE | LEFT | TIME
CROSS | LEVEL | TIMESTAMP
CURRENT | LIKE | TIMEZONE_HOUR
CURRENT_DATE | LOCAL | TIMEZONE_MINUTE
CURRENT_TIME | LOWER | TO
CURRENT_TIMESTAMP | MATCH | TRAILING
CURRENT_USER | MAX | TRANSACTION
CURSOR | MIN | TRANSLATE
DATE | MINUTE | TRANSLATION
DAY | MODULE | TRIM
DEALLOCATE | MONTH | TRUE
DEC | NAMES | UNION
DECIMAL | NATIONAL | UNIQUE
DECLARE | NATURAL | UNKNOWN
DEFAULT | NCHAR | UPDATE
DEFERRABLE | NEXT | UPPER
DEFERRED | NO | USAGE
DELETE | NONE | USER
DESC | NOT | USING
DESCRIBE | NULL | VALUE
DESCRIPTOR | NULLIF | VALUES
DIAGNOSTICS | NUMERIC | VARCHAR
DISCONNECT | OCTET_LENGTH | VARYING
DISTINCT | OF | VIEW
DOMAIN | ON | WHEN
DOUBLE | ONLY | WHENEVER
DROP | OPEN | WHERE
ELSE | OPTION | WITH
END | OR | WORK
END-EXEC | ORDER | WRITE
ESCAPE | OUTER | YEAR
EXCEPT | OUTPUT | ZONE
EXCEPTION |  |

See Also
SET QUOTED_IDENTIFIER


RESTORE

Restores an entire database and transaction log, database file(s), or a transaction log.

Caution Backups created with Microsoft® SQL Server™ version 7.0 cannot be restored to an earlier version of SQL Server.

Syntax

Restore an entire database:

RESTORE DATABASE {database_name | @database_name_var}
[FROM <backup_device> [,…n]]
[WITH
[DBO_ONLY]
[[,] FILE = file_number]
[[,] MEDIANAME = {media_name | @media_name_variable}]
[[,] MOVE 'logical_file_name' TO 'operating_system_file_name']
[,…n]
[[,] {NORECOVERY | RECOVERY | STANDBY = undo_file_name}]
[[,] {NOUNLOAD | UNLOAD}]
[[,] REPLACE]
[[,] RESTART]
[[,] STATS [= percentage]]
]

Restore specific files or filegroups:

RESTORE DATABASE {database_name | @database_name_var}
<file_or_filegroup> [,…n]
[FROM <backup_device> [,…n]]
[WITH
[DBO_ONLY]
[[,] FILE = file_number]
[[,] MEDIANAME = {media_name | @media_name_variable}]
[[,] NORECOVERY]
[[,] {NOUNLOAD | UNLOAD}]
[[,] REPLACE]
[[,] RESTART]
[[,] STATS [= percentage]]
]

Restore a transaction log:

RESTORE LOG {database_name | @database_name_var}
[FROM <backup_device> [,…n]]
[WITH
[DBO_ONLY]
[[,] FILE = file_number]
[[,] MEDIANAME = {media_name | @media_name_variable}]
[[,] {NORECOVERY | RECOVERY | STANDBY = undo_file_name}]
[[,] {NOUNLOAD | UNLOAD}]
[[,] RESTART]
[[,] STATS [= percentage]]
[[,] STOPAT = {date_time | @date_time_var}]
]

<backup_device> ::=
{
{'backup_device_name' | @backup_device_name_var}
| {DISK | TAPE | PIPE} =
{'temp_backup_device' | @temp_backup_device_var}
}

<file_or_filegroup> ::=
{
FILE = {logical_file_name | @logical_file_name_var}
|
FILEGROUP = {logical_filegroup_name | @logical_filegroup_name_var}
 }

Arguments
DATABASE
Specifies the complete restore of the database from a backup. If a list of files and filegroups is specified, only those files and filegroups are restored.
{database_name | @database_name_var}
Is the database that the log or complete database is restored into. If supplied as a variable (@database_name_var), this name can be specified either as a string constant (@database_name_var = database name) or as a variable of character string data type, except for the ntext or text data types.
FROM
Specifies the backup devices from which to restore the backup. If the FROM clause is not specified, the restore of a backup does not take place. Instead, the database is recovered. Omitting the FROM clause can be used to attempt recovery of a nonsuspect database that has been restored with the NORECOVERY option, or to switch over to a standby server. If the FROM clause is omitted, NORECOVERY, RECOVERY, or STANDBY must be specified.
<backup_device>
Specifies the permanent or temporary backup devices to use for the restore operation. Can be one or more of the following:
{'backup_device_name' | @backup_device_name_var}
Is the logical name, which must follow the rules for identifiers, of the backup device(s) created by sp_addumpdevice from which the database is restored. The maximum number of backup devices in a single RESTORE statement is 32. If supplied as a variable (@backup_device_name_var), the backup device name can be specified either as a string constant (@backup_device_name_var = backup_device_name) or as a variable of character string data type, except for the ntext or text data types.
{DISK | TAPE | PIPE} =
‘temp_backup_device’ | @temp_backup_device_var

Allows backups to be restored from the named disk, tape, or pipe device. The device types of disk and tape should be specified with the actual name (for example, complete path and file name) of the device: DISK = ‘C:\Mssql7\Backup\Mybackup.dat’ or TAPE = \\.\TAPE0. A device type of pipe should specify the name of the named pipe that is used by the client application. If specified as a variable (@temp_backup_device_var), the device name can be specified either as a string constant (@temp_backup_device_var = 'temp_backup_device') or as a variable of character string data type, except for the ntext or text data types.

Pipe devices have been added to allow third-party vendors a flexible way to connect their own software. The pipe device is not used for typical Transact-SQL use.

If you are using either a network server with a UNC name or a redirected drive letter, specify a device type of disk.

n
Is a placeholder indicating that multiple backup devices and temporary backup devices can be specified. The maximum number of backup devices or temporary backup devices is 32.
DBO_ONLY
Restricts access for the newly restored database to only the database owner. Causes the dbo use only option of sp_dboption to be set to true. This database option restricts access to the database owner after the restore operation until the option is set to false by executing sp_dboption. If this option is not specified, then the setting of the dbo use only database option may or may not change. For more information about when the dbo use only database setting may or may not be changed, see Database Settings and Restoring later in this topic. Use with the RECOVERY option.
FILE = file_number
Identifies the backup set to be restored. For example, a file_number of 1 indicates the first backup set on the backup medium and a file_number of 2 indicates the second backup set.
MEDIANAME = {media_name | @media_name_variable}
Specifies the media name for the entire backup set. If provided, the media name must match the media name on the backup volume(s); otherwise, the restore operation terminates. If no media name is given in the RESTORE statement, the check for a matching media name on the backup volume(s) is not performed.

Important Consistently using media names in backup and restore operations provides an extra safety check for the media selected for the restore operation.

MOVE 'logical_file_name' TO 'operating_system_file_name'
Specifies that the given logical_file_name should be moved to operating_system_file_name. By default, the logical_file_name is restored to its original location. If either the BACKUP or RESTORE statements is used to copy a database to the same or different server, the MOVE option may be needed to relocate the database files and to avoid collisions with existing files. Each logical file in the database can be specified in different MOVE statements.
n
Is a placeholder indicating that more than one logical file can be moved by specifying multiple MOVE statements.
NORECOVERY
Instructs the restore operation to not roll back any uncommitted transactions. Either the NORECOVERY or STANDBY option must be specified if another transaction log has to be applied. If neither NORECOVERY, RECOVERY, or STANDBY is specified, RECOVERY is the default.

SQL Server requires that the WITH NORECOVERY option be used on all but the final RESTORE statement when restoring a database backup and multiple transaction logs, or when multiple RESTORE statements are needed (for example, a full database backup followed by a differential database backup).

Note When specifying the NORECOVERY option, the database is not usable in this intermediate, nonrecovered state.

When used with a file or filegroup restore operation, NORECOVERY forces the database to remain in load state after the restore operation. This is useful in either of these situations:

  • A restore script is being run and the log is always wanted to be applied.
  • A sequence of file restores is used and the database is not wanted to be usable between two of the restore operations.
RECOVERY
Instructs the restore operation to rollback any uncommitted transactions. After the recovery process, the database is ready for use.

If subsequent RESTORE operations (RESTORE LOG, or RESTORE DATABASE from differential) are planned, NORECOVERY or STANDBY should be specified instead.

If neither NORECOVERY, RECOVERY, or STANDBY is specified, RECOVERY is the default. The database version is updated for databases and transaction logs if RECOVERY is specified.

STANDBY = undo_file_name
Specifies the undo file name so the recovery effects can be undone. This file is of unlimited size. If neither NORECOVERY, RECOVERY, or STANDBY is specified, RECOVERY is the default.

STANDBY allows a database to be brought up for read-only access between transaction log restores and can be used with either warm backup server situations or special recovery situations in which it is useful to check the database between log restores.

If the specified undo file name does not exist, SQL Server creates it. If the file does exist, SQL Server overwrites it unless the file contains current undo information for a database.

The same undo file can be used for consecutive restores of the same database.

Important If free disk space is exhausted on the drive containing the specified undo file name, the restore operation stops.

NOUNLOAD
Specifies that the tape is not unloaded automatically from the tape drive after a RESTORE. NOUNLOAD remains set until UNLOAD is specified. This option is used only for tape devices. If a nontape device is being used for the RESTORE, this option is ignored.
UNLOAD
Specifies that the tape is automatically rewound and unloaded when the RESTORE is finished. UNLOAD is set by default when a new user session is started. It remains set until NOUNLOAD is specified. This option is used only for tape devices. If a nontape device is being used for the RESTORE, this option is ignored.
REPLACE
Specifies that SQL Server should create the specified database and its related files even if another database already exists with the same name. In such a case, the existing database is deleted. When the REPLACE option is not specified, a safety check occurs (which prevents overwriting a different database on accident). The safety check ensures that the RESTORE DATABASE statement will not restore the database to the current server if:
  1. The database named in the RESTORE statement already exists on the current server, and
  2. Either the database name is different from the database name recorded in the backup set,

    Or

    The set of files in the database is different from the set of database files contained in the backup set. Differences in file size are ignored.

When used with a file or filegroup restore operation, REPLACE allows overwriting of an existing file, which is useful only when attempting to restore a file on a disk that is replacing a failed disk.

RESTART
Specifies that SQL Server should restart a restore operation that has been interrupted. RESTART restarts the restore operation at the point it was interrupted.

Important This option can only be used for restores directed from tape media and for restores that span multiple tape volumes.

STATS [= percentage]
Displays a message every time another percentage completes and is used to gauge progress. If percentage is omitted, SQL Server displays a message after every 10 percent completed.
<file_or_filegroup>
Specifies the names of the logical files or filegroups to include in the database restore. Multiple files or filegroups can be specified.
FILE = {logical_file_name | @logical_file_name_var}
Names one or more files to include in the database restore.
FILEGROUP = {logical_filegroup_name | @logical_filegroup_name_var}
Names one or more filegroups to include in the database restore.

When this option is used, the transaction log must be applied to the database files immediately after the last file or filegroup restore operation to roll the files forward to be consistent with the rest of the database. If no files being restored have been modified since they were last backed up, a transaction log does not have to be applied. The RESTORE statement informs the user of this situation.

The RESTORE statement requires that one or more filegroups be restored in a single operation if indexes were created on these filegroups since the last time these files were backed up. This requirement of restoring the entire set of filegroup(s) is necessary whether the restore is from a filegroup backup or a full database backup. The RESTORE statement detects this filegroup situation and reports the minimum filegroups that must be restored.

n
Is a placeholder indicating that multiple files and filegroups may be specified. There is no maximum number of files or filegroups.
LOG
Specifies that a transaction log backup is to be applied to this database. Transaction logs must be applied in sequential order. SQL Server checks the backed up transaction log to ensure that the transactions are being loaded into the correct database and in the correct sequence. To apply multiple transaction logs, use the NORECOVERY option on all restore operations except the last.
STOPAT = date_time | @date_time_var
Specifies that the database be restored to the state it was in as of the specified date and time. If a variable is used for STOPAT, the variable must be varchar, char, smalldatetime, or datetime data type. Only transaction log records written before the specified date and time are applied to the database. STOPAT cannot be used with NORECOVERY or STANDBY.

Note If you specify a STOPAT time that is beyond the end of the RESTORE LOG operation, the database is left in an unrecovered state, just as if RESTORE LOG had been run with NORECOVERY.

Remarks

During the restore, the specified database must not be in use. Any data in the specified database is replaced by the restored data.

Cross-platform restores, even between different processor types, can be performed if the following sort order and character set restrictions are met:

  • Usually, the sort order and character set of two servers must match to backup on one server and restore on the other. An exception is when both servers use a binary sort order; then, the character sets can differ. When the code page or sort order differs, use the bcp utility or Data Transformation Services to move the data.
  • You can perform a backup on a server with a binary sort order and restore the backup onto a different server with a binary sort order. If the character sets are the same, all characters are interpreted identically between the two servers. If the character sets are different, however, any extended characters are interpreted differently. Although the stored binary value is the same, extended characters are interpreted differently depending on the installed character set. For example, the character A (ASCII value of 65) is interpreted the same for all character sets. If the character stored is ÷ (ASCII value of 246) on the first server with a character set of code page 437 (U.S. English), the second server with a character set of code page ISO 8859-1 (Latin 1 or ANSI), interprets the ÷ character as the ö character (ASCII value still 246).
Restore Types

Here are the types of restores that SQL Server supports:

  • Full database restore which restores the entire database.
  • Full database restore and a differential database restore. Restore a differential backup by using the RESTORE DATABASE statement.
  • Transaction log restore.
  • Individual file and filegroup restores. Files and filegroups can be restored either from a file or filegroup backup operation or from a full database backup operation. When restoring files or filegroups, you must apply a transaction log.
  • Create and maintain a warm backup server or standby server.

Important To maintain backward compatibility, the LOAD keyword can be used in place of the RESTORE keyword in the RESTORE statement syntax. In addition, the TRANSACTION keyword can be used in place of the LOG keyword in the RESTORE statement syntax.

Database Settings and Restoring

When you use the RESTORE DATABASE statement, the restorable database options (which are all the settable options of sp_dboption except offline and the merge publish, published, and subscribed replication options) are reset to the settings in force at the time the BACKUP operation ended.

Note This behavior differs from earlier versions of Microsoft SQL Server.

Using the WITH DBO_ONLY option, however, overrides this behavior for the dbo use only setting. This setting is always set following a RESTORE statement which includes the WITH DBO_ONLY option.

Restore History Tables

SQL Server includes the following restore history tables, which track the RESTORE activity for each computer system:

  • restorefile
  • restorefilegroup
  • restorehistory

Note When a RESTORE is performed, the backup history tables are modified.

Restoring the master database because it has been damaged is performed using a special procedure.

Caution VOLUME is not an available option in SQL Server version 7.0. If VOLUME is specified, SQL Server returns an error message and halts the operation.

Permissions

If the database being restored does not exist, the user must have CREATE DATABASE permissions. If the database does exist, RESTORE permissions default to members of the sysadmin fixed server role and the db_owner fixed database role.

Examples

Note All examples assume that a full database backup has been performed earlier.

A. Restore a full database

Note The MyNwind database is shown for illustration.

This example restores a full database backup.

RESTORE DATABASE MyNwind

    FROM MyNwind_1

B. Restore a full database and a differential backup

This example restores a full database backup followed by a differential backup restore. In addition, this example shows restoring the second backup set on the media. The differential backup was appended to the backup device that contains the full database backup.

RESTORE DATABASE MyNwind

    FROM MyNwind_1

    WITH NORECOVERY

RESTORE DATABASE MyNwind

    FROM MyNwind_1

    WITH FILE = 2

C. Restore a database using RESTART syntax

This example uses the RESTART option to restart a RESTORE operation that was interrupted by a server power failure.

-- This database RESTORE halted prematurely due to power failure.

RESTORE DATABASE MyNwind

    FROM MyNwind_1

-- Here is the RESTORE RESTART operation.

RESTORE DATABASE MyNwind

    FROM MyNwind_1 WITH RESTART

D. Restore a database and move files

This example restores a full database and transaction log and moves the restored database into the C:\Mssql7\Data directory.

RESTORE DATABASE MyNwind

    FROM MyNwind_1

    WITH NORECOVERY,

        MOVE 'MyNwind' TO 'c:\mssql7\data\NewNwind.mdf',

        MOVE 'MyNwindLog1' TO 'c:\mssql7\data\NewNwind.ldf'

RESTORE LOG MyNwind

    FROM MyNwindLog1

    WITH RECOVERY

E. Make a copy of a database using BACKUP and RESTORE

This example uses both the BACKUP and RESTORE statements to make a copy of the Northwind database. The MOVE statement causes the data and log file to be restored to the specified locations. The RESTORE FILELISTONLY statement is used to determine the number and names of the files in the database being restored. The new copy of the database is named TestDB. For more information, see RESTORE FILELISTONLY.

BACKUP DATABASE Northwind

    TO DISK = 'c:\Northwind.bak'

RESTORE FILELISTONLY

    FROM DISK = 'c:\Northwind.bak'

RESTORE DATABASE TestDB

    FROM DISK = 'c:\Northwind.bak'

    WITH MOVE 'Northwind' TO 'c:\test\testdb.mdf',

    MOVE 'Northwind_log' TO 'c:\test\testdb.ldf'

GO

F. Restore to a point-in-time using STOPAT syntax and restore with more than one device

This example restores a database to its state as of 12:00 A.M. on April 15, 1998, and shows a restore operation that involves multiple logs and multiple backup devices.

RESTORE DATABASE MyNwind
    FROM MyNwind_1, MyNwind_2
    WITH NORECOVERY

RESTORE LOG MyNwind
    FROM MyNwindLog1
    WITH NORECOVERY

RESTORE LOG MyNwind
    FROM MyNwindLog2
    WITH RECOVERY, STOPAT = 'Apr 15, 1998 12:00 AM'

G. Restore using DISK syntax

This example restores a full database backup from a DISK backup device.

RESTORE DATABASE MyNwind

    FROM DISK = 'c:\mssql7\backup\MyNwind.bak'

H. Restore using TAPE syntax

This example restores a full database backup from a TAPE backup device.

RESTORE DATABASE MyNwind

    FROM TAPE = '\\.\tape0'

I. Restore using FILE and FILEGROUP syntax

This example illustrates restoring a database with two files, one filegroup, and one transaction log.

RESTORE DATABASE MyNwind

    FILE = 'MyNwind_data_1',

    FILE = 'MyNwind_data_2',

    FILEGROUP = 'new_customers'
    FROM MyNwind_1

    WITH NORECOVERY

-- Restore the log backup.

RESTORE LOG MyNwind
    FROM MyNwindLog1

See Also
BACKUP | RESTORE LABELONLY
Data Types | RESTORE VERIFYONLY
RESTORE FILELISTONLY | sp_addumpdevice
RESTORE HEADERONLY |


RESTORE FILELISTONLY

Returns a result set with a list of the database and log files contained in the backup set.

Syntax

RESTORE FILELISTONLY
FROM <backup_device>
[WITH
[FILE = file_number]
[[, ] {NOUNLOAD | UNLOAD}]
]

<backup_device> ::=
{
{'backup_device_name' | @backup_device_namevar}
| {DISK | TAPE | PIPE} =
{'temp_backup_device' | @temp_backup_device_var}
}

Arguments
<backup_device>
Specifies the permanent or temporary backup device(s) to use for the restore. Can be one or more of the following:
{'backup_device_name' | @backup_device_namevar}
Is the logical name, which must follow the rules for identifiers, of the backup device created by sp_addumpdevice from which the database is restored. If supplied as a variable (@backup_device_name_var), the backup device name can be specified either as a string constant (@backup_device_name_var = ‘backup_device_name’) or as a variable of character string data type, except for the ntext or text data types.
{DISK | TAPE | PIPE} =
'temp_backup_device' | @temp_backup_device_var

Allows backups to be restored from the named disk, tape, or pipe device. The device types of disk and tape should be specified with the actual name (for example, complete path and file name) of the device: DISK = ‘C:\Mssql7\Backup\Mybackup.dat’ or TAPE = \\.\TAPE0. A device type of pipe should specify the name of the named pipe that is used by the client application. If specified as a variable (@temp_backup_device_var), the device name can be specified either as a string constant (@temp_backup_device_var = ‘temp_backup_device’) or as a variable of character string data type, except for the ntext or text data types.

Pipe devices have been added to allow third-party vendors a flexible way to connect their own software. The pipe device is not used for typical Transact-SQL use.

If you are using either a network server with a UNC name or a redirected drive letter, specify a device type of disk.

FILE = file_number
Identifies the backup set to be processed. For example, a file_number of 1 indicates the first backup set and a file_number of 2 indicates the second backup set. If no file_number is supplied, the first backup set on the specified <backup_device> is assumed.
NOUNLOAD
Specifies that the tape is not unloaded automatically from the tape drive after a restore. NOUNLOAD remains set until UNLOAD is specified. This option is used only for tape devices.
UNLOAD
Specifies that the tape is automatically rewound and unloaded when the restore is finished. UNLOAD is set by default when a new user session is started. It remains set until NOUNLOAD is specified. This option is used only for tape devices.
Permissions

RESTORE permissions default to members of the sysadmin fixed server role and the db_owner fixed database role, and are not transferable.

Remarks

A client can use RESTORE FILELISTONLY to obtain a list of the files contained in a backup set. This information is returned as a result set containing one row for each file.

Column name | Data type | Description
LogicalName | nvarchar(128) | Logical name of the file
PhysicalName | nvarchar(260) | Physical or operating-system name of the file
Type | char(1) | Data file (D) or a log file (L)
FileGroupName | nvarchar(128) | Name of the filegroup that contains the file
Size | numeric(20,0) | Current size in bytes
MaxSize | numeric(20,0) | Maximum allowed size in bytes

See Also
BACKUP | RESTORE HEADERONLY
Data Types | RESTORE LABELONLY
RESTORE | RESTORE VERIFYONLY


RESTORE HEADERONLY

Retrieves all the backup header information for all backup sets on a particular backup device. The result from executing RESTORE HEADERONLY is a result set.

Syntax

RESTORE HEADERONLY
FROM <backup_device>
[WITH {NOUNLOAD | UNLOAD}]

<backup_device> ::=
{
{'backup_device_name' | @backup_device_name_var}
| {DISK | TAPE | PIPE} =
{'temp_backup_device' | @temp_backup_device_var}
}

Arguments
<backup_device>
Specifies the permanent or temporary backup device(s) to use for the restore. Can be one of the following:
{'backup_device_name' | @backup_device_name_var}
Is the logical name, which must follow the rules for identifiers, of the backup device created by sp_addumpdevice from which the database is restored. If supplied as a variable (@backup_device_name_var), the backup device name can be specified either as a string constant (@backup_device_name_var = ‘backup_device_name’) or as a variable of character string data type, except for the ntext or text data types.
{DISK | TAPE | PIPE} =
'temp_backup_device' | @backup_device_var

Allows backups to be restored from the named disk, tape, or pipe device. The device types of disk and tape should be specified with the actual name (for example, complete path and file name) of the device: DISK = ‘C:\Mssql7\Backup\Mybackup.dat’ or TAPE = \\.\TAPE0. A device type of pipe should specify the name of the named pipe that is used by the client application. If specified as a variable (@temp_backup_device_var), the device name can be specified either as a string constant (@temp_backup_device_var = ‘temp_backup_device’) or as a variable of character string data type, except for the ntext or text data types.

Pipe devices have been added to allow third-party vendors a flexible way to connect their own software. The pipe device is not used for typical Transact-SQL use.

If you are using either a network server with a UNC name or a redirected drive letter, specify a device type of disk.

NOUNLOAD
Specifies that the tape is not unloaded automatically from the tape drive after a restore. NOUNLOAD remains set until UNLOAD is specified. This option is used only for tape devices.
UNLOAD
Specifies that the tape is automatically rewound and unloaded when the restore is finished. UNLOAD is set by default when a new user session is started. It remains set until NOUNLOAD is specified. This option is used only for tape devices.
Permissions

RESTORE permissions default to members of the sysadmin fixed server role and the db_owner fixed database role, and are not transferable.

Remarks

A client can use RESTORE HEADERONLY to retrieve all the backup header information (subject to having the necessary permissions) for all backups on a particular backup device. The header information is sent as a row by the server for each backup on a given backup device in a table with the following columns:

Note Because RESTORE HEADERONLY looks at all backup sets on the media, it can take some time to produce this result set when using high-capacity tape drives. To get a quick look at the media without getting information about every backup set, use RESTORE LABELONLY.

Due to the nature of Microsoft Tape Format, it is possible for backup sets from other software programs to occupy space on the same media as Microsoft® SQL Server™ backup sets. The result set returned by RESTORE HEADERONLY includes a row for each of these other backup sets.

Column name | Data type | Description for SQL Server backup sets | Description for other backup sets
BackupName | nvarchar(128) | Backup set name. | Data set name.
Backup Description | nvarchar(255) | Backup set description. | Data set description.
BackupType | smallint | Backup type: 1 = Database 2 = Transaction Log 4 = File 5 = Differential Database | Backup type: 1 = Normal 5 = Differential 16 = Incremental 17 = Daily
ExpirationDate | datetime | Expiration date for the backup set. | NULL
Compressed | tinyint | 0 = No. SQL Server does not support software compression. | Whether the backup set is compressed using software-based compression: 1 = Yes 0 = No
Position | smallint | Position of the backup set in the volume (for use with the FILE = option). | Position of the backup set in the volume.
DeviceType | tinyint | Number corresponding to the device used for the backup operation: Disk 2 = Temporary 102 = Permanent Tape 5 = Temporary 105 = Permanent Pipe 6 = Temporary 106 = Permanent Virtual Device 7 = Temporary 107 = Permanent All permanent device names and device numbers can be found in sysdevices. | NULL
UserName | nvarchar(128) | Username that performed the backup operation. | Username that performed the backup operation.
ServerName | nvarchar(128) | Name of the server that wrote the backup set. | NULL
DatabaseName | nvarchar(128) | Name of the database that was backed up. | NULL
Database Version | int | Version of the database from which the backup was created. | NULL
Database CreationDate | datetime | Date and time the database was created. | NULL
BackupSize | numeric(20,0) | Size of the backup, in bytes. | NULL
FirstLSN | numeric(25,0) | Log sequence number of the first transaction in the backup set. NULL for file backups. | NULL
LastLSN | numeric(25,0) | Log sequence number of the last transaction in the backup set. NULL for file backups. | NULL
Checkpoint LSN | numeric(25,0) | Log sequence number of the most recent checkpoint at the time the backup was created. | NULL
Database BackupLSN | numeric(25,0) | Log sequence number of the most recent full database backup. | NULL
Backup StartDate | datetime | Date and time that the backup operation began. | Media Write Date.
Backup FinishDate | datetime | Date and time that the backup operation finished. | Media Write Date.
SortOrder | smallint | Server sort order. This column is valid for database backups only. | NULL
CodePage | smallint | Server code page or character set used by the server. | NULL
UnicodeLocaleId | int | Server Unicode locale ID configuration option used for Unicode character data sorting. | NULL
UnicodeComparisonStyle | int | Server Unicode comparison style configuration option, which provides additional control over the sorting of Unicode data. | NULL
Compatibility Level | tinyint | Compatibility level setting of the database from which the backup was created. | NULL
Software VendorId | int | Software vendor identification number. For SQL Server, this number is 4608 (or hexadecimal 0x1200). | Software vendor identification number.
Software VersionMajor | int | Major version number of the server that created the backup set. | Major version number of the software that created the backup set.
Software VersionMinor | int | Minor version number of the server that created the backup set. | Minor version number of the software that created the backup set.
Software VersionBuild | int | Build number of the server that created the backup set. | NULL
MachineName | nvarchar(128) | Name of the computer that performed the backup operation. | Type of the computer that performed the backup operation.

Note If the backup set is password protected, the BackupName column value is ***Password Protected***, and all other columns are NULL. For any backup, only the appropriate columns contain a value; all other columns are NULL.

Important To maintain backward compatibility, the LOAD keyword can be used in place of the RESTORE keyword in the RESTORE statement syntax.

See Also
BACKUP | Data Types
RESTORE FILELISTONLY | RESTORE
RESTORE LABELONLY | RESTORE VERIFYONLY


RESTORE LABELONLY

Returns a result set containing information about the backup media identified by the given backup device.

Syntax

RESTORE LABELONLY
FROM <backup_device>
[WITH {NOUNLOAD | UNLOAD}]

<backup_device> ::=
{
{'backup_device_name' | @backup_device_name_var}
| {DISK | TAPE | PIPE} =
{'temp_backup_device' | @temp_backup_device_var}
}

Arguments
<backup_device>
Specifies the permanent or temporary backup device to use for the restore. Can be one of the following:
{'backup_device__name' | @backup_device_name_var}
Is the logical name, which must follow the rules for identifiers, of the backup device created by sp_addumpdevice from which the database is restored. If supplied as a variable (@backup_device_name_var), the backup device name can be specified either as a string constant (@backup_device_name_var = ‘backup_device_name’) or as a variable of character string data type, except for the ntext or text data types.
{DISK | TAPE | PIPE} =
'temp_backup_device' | @temp_backup_device_var

Allows backups to be restored from the named disk, tape, or pipe device. The device types of disk and tape should be specified with the actual name (for example, complete path and file name) of the device: DISK = ‘C:\Mssql7\Backup\Mybackup.dat’ or TAPE = \\.\TAPE0. A device type of pipe should specify the name of the named pipe that is used by the client application. If specified as a variable (@temp_backup_device_var), the device name can be specified either as a string constant (@temp_backup_device_var = ‘temp_backup_device’) or as a variable of character string data type, except for the ntext or text data types.

Pipe devices have been added to allow third-party vendors a flexible way to connect their own software. The pipe device is not used for typical Transact-SQL use.

If you are using either a network server with a UNC name or a redirected drive letter, specify a device type of disk.

NOUNLOAD
Specifies that the tape is not unloaded automatically from the tape drive after a restore. NOUNLOAD remains set until UNLOAD is specified. This option is used only for tape devices.
UNLOAD
Specifies that the tape is automatically rewound and unloaded when the restore is finished. UNLOAD is set by default when a new user session is started. It remains set until NOUNLOAD is specified. This option is used only for tape devices.
Permissions

RESTORE permissions default to members of the sysadmin fixed server role and the db_owner fixed database role, and are not transferable.

Remarks

Executing RESTORE LABELONLY is a quick way to find out what the backup media contains. Because RESTORE LABELONLY reads only the media header, this statement finishes quickly even when using high-capacity tape devices. The result set from RESTORE LABELONLY consists of a single row with this information.

Column name | Data type | Description
MediaName | nvarchar(128) | Name of the media.
MediaSetId | uniqueidentifier | Unique identification number of the media set. This column is NULL if there is only one media family in the media set.
FamilyCount | int | Number of media families in the media set.
Family SequenceNumber | int | Sequence number of this family.
MediaFamilyId | uniqueidentifier | Unique identification number for the media family.
MediaSequence Number | int | Sequence number of this media in the media family.
MediaLabel Present | tinyint | Whether the media description contains: 1 = Microsoft Tape Format media label 0 = Media description
MediaDescription | nvarchar(255) | Media description, in free-form text, or the Microsoft Tape Format media label.
SoftwareName | nvarchar(128) | Name of the backup software that wrote the label.
SoftwareVendorId | int | Unique vendor identification number of the software vendor that wrote the backup.
MediaDate | datetime | Date and time the label was written.

See Also
BACKUP | RESTORE FILELISTONLY
Data Types | RESTORE VERIFYONLY
RESTORE |


RESTORE VERIFYONLY

Verifies the backup but does not restore the backup. Checks to see that the backup set is complete and that all volumes are readable. However, RESTORE VERIFYONLY does not attempt to verify the structure of the data contained in the backup volumes. If the backup is valid, Microsoft® SQL Server™ returns the message: “The backup set is valid.”

Syntax

RESTORE VERIFYONLY
FROM <backup_device> [,…n]
[WITH
[FILE = file_number]
[[,] {NOUNLOAD | UNLOAD}]
[[,] LOADHISTORY]
]

<backup_device> ::=
{
{'backup_device_name' | @backup_device_name_var}
| {DISK | TAPE | PIPE} =
{'temp_backup_device' | @temp_backup_device_var}
}

Arguments
<backup_device>
Specifies the permanent or temporary backup device(s) to use for the restore. Can be one or more of the following:
{'backup_device_name' | @backup_device_name_var}
Is the logical name, which must follow the rules for identifiers, of the backup device(s) created by sp_addumpdevice from which the database is restored. The maximum number of backup devices in a single RESTORE statement is 32. If supplied as a variable (@backup_device_name_var), the backup device name can be specified either as a string constant (@backup_device_name_var = ‘backup_device_name’) or as a variable of character string data type, except for the ntext or text data types.
{DISK | TAPE | PIPE} =
'temp_backup_device' | @temp_backup_device_var

Allows backups to be restored from the named disk, tape, or pipe device. The device types of disk and tape should be specified with the actual name (for example, complete path and file name) of the device: DISK = ‘C:\Mssql7\Backup\Mybackup.dat’ or TAPE = \\.\TAPE0. A device type of pipe should specify the name of the named pipe that is used by the client application. If specified as a variable (@temp_backup_device_var), the device name can be specified either as a string constant (@temp_backup_device_var = ‘temp_backup_device’) or as a variable of character string data type, except for the ntext or text data types.

Pipe devices have been added to allow third-party vendors a flexible way to connect their own software. The pipe device is not used for typical Transact-SQL use.

If you are using either a network server with a UNC name or a redirected drive letter, specify a device type of disk.

n
Is a placeholder indicating that multiple backup devices and temporary backup devices may be specified. The maximum number of backup devices or temporary backup devices in a single RESTORE VERIFYONLY statement is 32.

Note In order to specify multiple backup devices for <backup_device>, all backup devices specified must be part of the same media set.

FILE = file_number
Identifies the backup set to be restored or processed. For example, a file_number of 1 indicates the first backup set and a file_number of 2 indicates the second backup set. If no file_number is supplied, the first backup set on the specified <backup_device> is assumed.
NOUNLOAD
Specifies that the tape is not unloaded automatically from the tape drive after a restore. NOUNLOAD remains set until UNLOAD is specified. This option is used only for tape devices. If a nontape device is being used for the restore, this option is ignored.
UNLOAD
Specifies that the tape is automatically rewound and unloaded when the RESTORE is finished. UNLOAD is set by default when a new user session is started. It remains set until NOUNLOAD is specified. This option is used only for tape devices. If a nontape device is being used for the RESTORE, this option is ignored.
LOADHISTORY
Specifies that the restore operation loads the information into the msdb history tables. The LOADHISTORY option loads information, for the single backup set being verified, about SQL Server backups stored on the media set to the backup and restore history tables in the msdb database. No information for non-SQL Server backups is loaded into these history tables. For more information about history tables, see System Tables.
Permissions

RESTORE permissions default to members of the sysadmin fixed server role and the db_owner fixed database role, and are not transferable.

See Also
BACKUP | RESTORE HEADERONLY
Data Types | RESTORE LABELONLY
RESTORE | System Tables
RESTORE FILELISTONLY |


RETURN

Exits unconditionally from a query or procedure. RETURN is immediate and complete and can be used at any point to exit from a procedure, batch, or statement block. Statements following RETURN are not executed.

Syntax

RETURN [integer_expression]

Arguments
integer_expression
Is the integer value returned. Stored procedures can return an integer value to a calling procedure or an application.
Return Types

Optionally returns int.

Note Unless documented otherwise, all system stored procedures return a value of 0, which indicates success; a nonzero value indicates failure.

Remarks

When used with a stored procedure, RETURN cannot return a null value. If a procedure attempts to return a null value (for example, using RETURN @status and @status is NULL), a warning message is generated and a value from 0 through - 14 is returned.

The return status value can be included in subsequent Transact-SQL statements in the batch or procedure that executed the current procedure, but it must be entered in the following form:

EXECUTE @return_status = procedure_name

Note Whether Microsoft® SQL Server™ interprets an empty string (NULL) as either a single space or as a true empty string is controlled by the compatibility level setting. If the compatibility level is less than or equal to 65, SQL Server interprets empty strings as single spaces. If the compatibility level is equal to 70, SQL Server interprets empty strings as empty strings. For more information, see sp_dbcmptlevel.

Examples
A. Return from a procedure

This example shows if no username is given as a parameter when findjobs is executed, RETURN causes the procedure to exit after a message has been sent to the user’s screen. If a username is given, the names of all objects created by this user in the current database are retrieved from the appropriate system tables.

CREATE PROCEDURE findjobs @nm sysname = NULL

AS

IF @nm IS NULL

    BEGIN

        PRINT 'You must give a username'

        RETURN

    END

ELSE

    BEGIN

        SELECT o.name, o.id, o.uid

        FROM sysobjects o INNER JOIN master..syslogins l

            ON o.uid = l.suid

        WHERE l.name = @nm

    END

B. Return status codes

This example checks the state for the specified author’s ID. If the state is California (CA), a status of 1 is returned. Otherwise, 2 is returned for any other condition (a value other than CA for state or an au_id that did not match a row).

CREATE PROCEDURE checkstate @param varchar(11)

AS

IF (SELECT state FROM authors WHERE au_id = @param) = 'CA'

    RETURN 1

ELSE

    RETURN 2

The following examples show the return status from the execution of checkstate. The first shows an author in California; the second, an author not in California; and the third, an invalid author. The @return_status local variable must be declared before it can be used.

DECLARE @return_status int

EXEC @return_status = checkstate '172-32-1176'

SELECT 'Return Status' = @return_status

GO

Here is the result set:

Return Status
-------------
1

Execute the query again, specifying a different author number.

DECLARE @return_status int

EXEC @return_status = checkstate '648-92-1872'

SELECT 'Return Status' = @return_status

GO

Here is the result set:

Return Status
-------------
2

Execute the query again, specifying another author number.

DECLARE @return_status int

EXEC @return_status = checkstate '12345678901'

SELECT 'Return Status' = @return_status

GO

Here is the result set:

Return Status
-------------
2

See Also
ALTER PROCEDURE | EXECUTE
CREATE PROCEDURE | SET @local_variable
DECLARE @local_variable |


REVERSE

Returns the reverse of a character expression.

Syntax

REVERSE(character_expression)

Arguments
character_expression
Is an expression of character data. character_expression can be a constant, variable, or column of either character or binary data.
Return Types

varchar

Remarks

character_expression must be of a data type that is implicitly convertible to varchar. Otherwise, use CAST to explicitly convert character_expression.

Examples

This example returns all author first names with the characters reversed.

USE pubs

GO

SELECT REVERSE(au_fname)

FROM authors

ORDER BY au_fname

GO

Here is the result set:

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

maharbA

okikA

treblA

nnA

ennA

truB

enelrahC

lyrehC

naeD

kriD

rehtaeH

sennI

nosnhoJ

aiviL

eirojraM

rednaeM

leahciM

lehciM

ratsgninroM

dlanigeR

lyrehS

snraetS

aivlyS

(23 row(s) affected)

See Also
CAST and CONVERT | String Functions
Data Types |


REVOKE

Removes a previously granted or denied permission from a user in the current database.

Syntax

Statement permissions:

REVOKE {ALL | statement[,…n]}
FROM security_account[,…n]

Object permissions:

REVOKE [GRANT OPTION FOR]
{ALL [PRIVILEGES] | permission[,…n]}
{
[(column[,…n])] ON {table | view}
| ON {table | view}[(column[,…n])]
| {stored_procedure | extended_procedure}
}
{TO | FROM}
security_account[,…n]
[CASCADE]
[AS {group | role}]

Arguments
ALL
Specifies that all applicable permissions are being removed. For statement permissions, ALL can be used only by members of the sysadmin fixed server role. For object permissions, ALL can be used by members of the sysadmin fixed server and db_owner fixed database roles, and database object owners.
statement
Is a granted statement for which permission is being removed. The statement list can include:
  • CREATE DATABASE
  • CREATE DEFAULT
  • CREATE PROCEDURE
  • CREATE RULE
  • CREATE TABLE
  • CREATE VIEW
  • BACKUP DATABASE
  • BACKUP LOG
n
Is a placeholder indicating the item can be repeated in a comma-separated list.
FROM
Specifies the security account list.
security_account
Is the security account in the current database from which the permissions are being removed. The security account can be a:
  • Microsoft® SQL Server™ user.
  • SQL Server role.
  • Microsoft Windows NT® user.
  • Windows NT group.

Permissions cannot be revoked from the system roles, such as sysadmin. When permissions are revoked from a SQL Server or Windows NT user account, the specified security_account is the only account affected by the permissions. If permissions are revoked from a SQL Server role or a Windows NT group, the permissions affect all users in the current database who are members of the group or role, unless the user has already been explicitly granted or denied a permission.

There are two special security accounts that can be used with REVOKE. Permissions revoked from the public role are applied to all users in the database. Permissions revoked from the guest user are used by all users who do not have a user account in the database.

When revoking permissions to a Windows NT local or global group, specify the domain or computer name the group is defined on, followed by a backslash, then the group name, for example London\JoeB. However, to revoke permissions to a Windows NT built-in local group, specify BUILTIN instead of the domain or computer name, for example BUILTIN\Users.

GRANT OPTION FOR
Specifies that WITH GRANT OPTION permissions are being removed. Use the GRANT OPTION FOR keywords with REVOKE to remove the effects of the WITH GRANT OPTION setting specified in the GRANT statement. The user still has the permissions, but cannot grant the permissions to other users.

If the permissions being revoked were not originally granted using the WITH GRANT OPTION setting, GRANT OPTION FOR is ignored if specified, and permissions are revoked as usual.

If the permissions being revoked were originally granted using the WITH GRANT OPTION setting, specify both the CASCADE and GRANT OPTION FOR clauses; otherwise, an error is returned.

PRIVILEGES
Is an optional keyword that can be included for SQL-92 compliance.
permission
Is an object permission that is being revoked. When permissions are revoked on a table or a view, the permission list can include one or more of these statements: SELECT, INSERT, DELETE, or UPDATE.

Object permissions revoked on a table can also include REFERENCES, and object permissions revoked on a stored procedure or extended stored procedure can be EXECUTE. When permissions are revoked on columns, the permissions list can include SELECT or UPDATE.

column
Is the name of the column in the current database for which permissions are being removed.
table
Is the name of the table in the current database for which permissions are being removed.
view
Is the name of the view in the current database for which permissions are being removed.
stored_procedure
Is the name of the stored procedure in the current database for which permissions are being removed.
extended_procedure
The name of an extended stored procedure for which permissions are being removed.
TO
Specifies the security account list.
CASCADE
Specifies that permissions are being removed from security_account as well as any other security accounts that were granted permissions by security_account. Use when revoking a grantable permission.

If the permissions being revoked were originally granted to security_account using the WITH GRANT OPTION setting, specify both the CASCADE and GRANT OPTION FOR clauses; otherwise, an error is returned. Specifying both the CASCADE and GRANT OPTION FOR clauses revokes only the permissions granted using the WITH GRANT OPTION setting from security_account, as well as any other security accounts that were granted permissions by security_account.

AS {group | role}
Specifies the optional name of the security account in the current database under whose authority the REVOKE statement will be executed. AS is used when permissions on an object are granted to a group or role, and the object permissions need to be revoked from other users. Because only a user, rather than a group or role, can execute a REVOKE statement, a specific member of the group or role revokes permissions from the object under the authority of the group or role.
Remarks

Only use REVOKE with permissions in the current database.

A revoked permission removes the granted or denied permission only at the level revoked (user, group, or role). For example, permission to view the authors table is explicitly granted to the Andrew user account, which is a member of the employees role only. If the employees role is revoked access to view the authors table, Andrew can still view the table because permission has been explicitly granted. Andrew is unable to view the authors table only if Andrew is revoked permission as well. If Andrew is never explicitly granted permissions to view authors, then revoking permission from the employees role prevents Andrew from viewing the table.

Note In Microsoft SQL Server version 7.0, REVOKE removes only previously granted or denied permissions; therefore, existing SQL Server 6.x scripts that use REVOKE may have to be changed to use DENY to maintain behavior.

If a user activates an application role, the effect of REVOKE is null for any objects the user accesses using the application role. Although a user may be revoked access to a specific object in the current database, if the application role has access to the object, the user also has access while the application role is activated.

Use sp_helprotect to report the permissions on a database object or user.

Permissions

REVOKE permissions default to members of the sysadmin fixed server role, db_owner and db_securityadmin fixed database roles, and database object owners.

Examples
A. Revoke statement permissions from a user account

This example revokes the CREATE TABLE permissions that have been granted to the users Joe and Corporate\BobJ. It removes the permissions that allow Joe and Corporate\BobJ to create a table; however, Joe and Corporate\BobJ can still create tables if CREATE TABLE permissions have been granted to any roles of which they are members.

REVOKE CREATE TABLE FROM Joe, [Corporate\BobJ]

B. Revoke multiple permissions from multiple user accounts

This example revokes multiple statement permissions from multiple users.

REVOKE CREATE TABLE, CREATE DEFAULT

FROM Mary, John

C. Revoke a denied permission

The user Mary is a member of the Budget role, which has been granted SELECT permissions on the Budget_Data table. The DENY statement has been used with Mary to prevent access to the Budget_Data table through the permissions granted to the Budget role.

This example removes the denied permission from Mary and, through the SELECT permissions applied to the Budget role, allows Mary to use the SELECT statement on the table.

REVOKE SELECT ON Budget_Data TO Mary

See Also
DENY | sp_helprotect
GRANT |


RIGHT

Returns the part of a character string starting a specified number of integer_expression characters from the right.

Syntax

RIGHT(character_expression, integer_expression)

Arguments
character_expression
Is an expression of character data. character_expression can be a constant, variable, or column of either character or binary data.
integer_expression
Is the starting position, expressed as a positive whole number. If integer_expression is negative, an error is returned.
Return Types

varchar

character_expression must be of a data type that is implicitly convertible to varchar. Otherwise, use CAST to explicitly convert character_expression.

Remarks

Compatibility levels can affect return values. For more information, see sp_dbcmptlevel.

Examples

This example returns the five right-most characters of each author’s first name.

USE pubs

GO

SELECT RIGHT(au_fname, 5)

FROM authors

ORDER BY au_fname

GO

Here is the result set:

-----

raham

Akiko

lbert

Ann

Anne

Burt

rlene

heryl

Dean

Dirk

ather

Innes

hnson

Livia

jorie

ander

chael

ichel

gstar

inald

heryl

earns

ylvia

(23 row(s) affected)

See Also
CAST and CONVERT | String Functions
Data Types |


ROLLBACK TRANSACTION

Rolls back an explicit or implicit transaction to the beginning of the transaction, or to a savepoint inside a transaction.

Syntax

ROLLBACK [TRAN[SACTION] [transaction_name |
@tran_name_variable | savepoint_name | @savepoint_variable] ]

Arguments
transaction_name
Is the name assigned to the transaction on BEGIN TRANSACTION. transaction_name must conform to the rules for identifiers, but only the first 32 characters of the transaction name are used. When nesting transactions, transaction_name must be the name from the outermost BEGIN TRANSACTION statement.
@tran_name_variable
Is the name of a user-defined variable containing a valid transaction name. The variable must be declared with a char, varchar, nchar, or nvarchar data type.
savepoint_name
Is savepoint_name from a SAVE TRANSACTION statement. savepoint_name must conform to the rules for identifiers. Use savepoint_name when a conditional rollback should affect only part of the transaction.
@savepoint_variable
Is name of a user-defined variable containing a valid savepoint name. The variable must be declared with a char, varchar, nchar, or nvarchar data type.
Remarks

ROLLBACK TRANSACTION erases all data modifications made since the start of the transaction or to a savepoint. It also frees resources held by the transaction.

ROLLBACK TRANSACTION without a savepoint_name or transaction_name rolls back to the beginning of the transaction. When nesting transactions, this same statement rolls back all inner transactions to the outermost BEGIN TRANSACTION statement. In both cases, ROLLBACK TRANSACTION decrements the @@TRANCOUNT system function to 0. ROLLBACK TRANSACTION savepoint_name does not decrement @@TRANCOUNT.

A ROLLBACK TRANSACTION statement specifying a savepoint_name does not free any locks.

ROLLBACK TRANSACTION cannot reference a savepoint_name in distributed transactions started either explicitly with BEGIN DISTRIBUTED TRANSACTION or escalated from a local transaction.

A transaction cannot be rolled back after a COMMIT TRANSACTION statement is executed.

Within a transaction, duplicate savepoint names are allowed, but a ROLLBACK TRANSACTION using the duplicate savepoint name rolls back only to the most recent SAVE TRANSACTION using that savepoint name.

In stored procedures, ROLLBACK TRANSACTION statements without a savepoint_name or transaction_name roll back all statements to the outermost BEGIN TRANSACTION. A ROLLBACK TRANSACTION statement in a stored procedure that causes @@TRANCOUNT to have a different value when the trigger completes than the @@TRANCOUNT value when the stored procedure was called produces an informational message. This message does not affect subsequent processing.

If a ROLLBACK TRANSACTION is issued in a trigger:

  • All data modifications made to that point in the current transaction are rolled back, including any that were made by the trigger.
  • The trigger continues executing any remaining statements after the ROLLBACK statement. If any of these statements modify data, the modifications are not rolled back. No nested triggers are fired by the execution of these remaining statements.
  • The statements in the batch after the statement that fired the trigger are not executed.

@@TRANCOUNT is incremented by one when entering a trigger, even when in autocommit mode. (The system treats a trigger as an implied nested transaction.)

ROLLBACK TRANSACTION statements in stored procedures do not affect subsequent statements in the batch that called the procedure; subsequent statements in the batch are executed. ROLLBACK TRANSACTION statements in triggers terminate the batch containing the statement that fired the trigger; subsequent statements in the batch are not executed.

A ROLLBACK TRANSACTION statement does not produce any messages to the user. If warnings are needed in stored procedures or triggers, use the RAISERROR or PRINT statements. RAISERROR is the preferred statement for indicating errors.

The effect of a ROLLBACK on cursors is defined by these three rules:

  1. With CURSOR_CLOSE_ON_COMMIT set ON, ROLLBACK closes but does not deallocate all open cursors.
  2. With CURSOR_CLOSE_ON_COMMIT set OFF, ROLLBACK does not affect any open STATIC or INSENSITIVE cursors. Open cursors of any other type are closed but not deallocated.
  3. An error that terminates a batch and generates an internal rollback deallocates all cursors that were declared in the batch containing the error statement. All cursors are deallocated regardless of their type or the setting of CURSOR_CLOSE_ON_COMMIT. This includes cursors declared in stored procedures called by the error batch. Cursors declared in a batch before the error batch are subject to rules 1 and 2. A deadlock error is an example of this type of error. A ROLLBACK statement issued in a trigger also automatically generates this type of error.
Permissions

ROLLBACK TRANSACTION permissions default to any valid user.

See Also
BEGIN DISTRIBUTED TRANSACTION | COMMIT WORK
BEGIN TRANSACTION | ROLLBACK WORK
COMMIT TRANSACTION | SAVE TRANSACTION


ROLLBACK WORK

Rolls back a user-specified transaction to the beginning of a transaction.

Syntax

ROLLBACK [WORK]

Remarks

This statement functions identically to ROLLBACK TRANSACTION except that ROLLBACK TRANSACTION accepts a user-defined transaction name. With or without specifying the optional WORK keyword, this ROLLBACK syntax is SQL-92-compatible.

When nesting transactions, ROLLBACK WORK always rolls back to the outermost BEGIN TRANSACTION statement and decrements the @@TRANCOUNT system function to 0.

Permissions

ROLLBACK WORK permissions default to any valid user.

See Also
BEGIN DISTRIBUTED TRANSACTION | COMMIT WORK
BEGIN TRANSACTION | ROLLBACK TRANSACTION
COMMIT TRANSACTION | SAVE TRANSACTION


ROUND

Returns a numeric expression, rounded to the specified length or precision.

Syntax

ROUND(numeric_expression, length[, function])

Arguments
numeric_expression
Is an expression of the exact numeric or approximate numeric data type category, except for the bit data type.
length
Is the precision to which numeric_expression is to be rounded. length must be tinyint, smallint, or int. When length is a positive number, numeric_expression is rounded to the number of decimal places specified by length. When length is a negative number, numeric_expression is rounded on the left side of the decimal point, as specified by length.
function
Is the type of operation to perform. function must be tinyint, smallint, or int. When function is omitted or has a value of 0 (default), numeric_expression is rounded. When a value other than 0 is specified, numeric_expression is truncated.
Return Types

Returns the same type as numeric_expression.

Remarks

ROUND always returns a value. If length is negative and larger than the number of digits before the decimal point, ROUND returns 0.

Example | Result
ROUND(748.58, -4) | 0

In Microsoft® SQL Server™ version 7.0, ROUND returns a rounded numeric_expression, regardless of data type, when length is a negative number.

Examples | Result
ROUND(748.58, -1) | 750.00
ROUND(748.58, -2) | 700.00
ROUND(748.58, -3) | 1000.00

Examples
A. Use ROUND and estimates

This example shows two expressions illustrating that with the ROUND function the last digit is always an estimate.

SELECT ROUND(123.9994, 3), ROUND(123.9995, 3)

GO

Here is the result set:

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

123.9990    124.0000

B. Use ROUND and rounding approximations

This example shows rounding and approximations.

Statement | Result
SELECT ROUND(123.4545, 2) | 123.4500
SELECT ROUND(123.45, -2) | 100.00

C. Use ROUND to truncate

This example uses two SELECT statements to demonstrate the difference between rounding and truncation. The first statement rounds the result. The second statement truncates the result.

Statement | Result
SELECT ROUND(150.75, 0) | 151.00
SELECT ROUND(150.75, 0, 1) | 150.00

See Also
CEILING | FLOOR
Data Types | Mathematical Functions
Expressions |


RTRIM

Returns a character string after removing all trailing blanks.

Syntax

RTRIM(character_expression)

Arguments
character_expression
Is an expression of character data. character_expression can be a constant, variable, or column of either character or binary data.
Return Types

varchar

Remarks

character_expression must be of a data type that is implicitly convertible to varchar. Otherwise, use the CAST function to explicitly convert character_expression.

Note Compatibility levels can affect return values. For more information, see sp_dbcmptlevel.

Examples

This example shows using RTRIM to remove trailing spaces from a character variable.

DECLARE @string_to_trim varchar(60)

SET @string_to_trim = 'Four spaces are after the period in this sentence.    '

SELECT 'Here is the string without the leading spaces: ' + CHAR(13) +

    RTRIM(@string_to_trim)

GO

Here is the result set:

(1 row(s) affected)

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

Here is the string without the leading spaces: Four spaces are after the period in this sentence.

(1 row(s) affected)

See Also
CAST and CONVERT | String Functions
Data Types |


SAVE TRANSACTION

Sets a savepoint within a transaction.

Syntax

SAVE TRAN[SACTION] {savepoint_name | @savepoint_variable}

Arguments
savepoint_name
Is the name assigned to the savepoint. Savepoint names must conform to the rules for identifiers, but only the first 32 characters are used.
@savepoint_variable
Is the name of a user-defined variable containing a valid savepoint name. The variable must be declared with a char, varchar, nchar, or nvarchar data type.
Remarks

A user can set a savepoint, or marker, within a transaction. The savepoint defines a location to which a transaction can return if part of the transaction is conditionally canceled. If a transaction is rolled back to a savepoint, it must proceed to completion (with more Transact-SQL statements if needed and a COMMIT TRANSACTION statement), or it must be canceled altogether (by rolling the transaction back to its beginning). To cancel an entire transaction, use the form ROLLBACK TRANSACTION transaction_name. All the statements or procedures of the transaction are undone.

SAVE TRANSACTION is not supported in distributed transactions started either explicitly with BEGIN DISTRIBUTED TRANSACTION or escalated from a local transaction.

Important When a transaction begins, resources used during the transaction are held until the completion of the transaction (namely locks). When part of a transaction is rolled back to a savepoint, resources continue to be held until the completion of the transaction (or a rollback of the complete transaction).

Permissions

SAVE TRANSACTION permissions default to any valid user.

Examples

This example changes the royalty split for the two authors of The Gourmet Microwave. Because the database would be inconsistent between the two updates, they must be grouped into a user-defined transaction.

BEGIN TRANSACTION royaltychange

    UPDATE titleauthor

        SET royaltyper = 65

            FROM titleauthor, titles

                WHERE royaltyper = 75

                    AND titleauthor.title_id = titles.title_id

                    AND title = 'The Gourmet Microwave'

    UPDATE titleauthor

        SET royaltyper = 35

            FROM titleauthor, titles

                WHERE royaltyper = 25

                    AND titleauthor.title_id = titles.title_id

                    AND title = 'The Gourmet Microwave'

SAVE TRANSACTION percentchanged

/*

After having updated the royaltyper entries for the two authors, the
user inserts the savepoint percentchanged, and then determines how a 10=percent increase in the book's price would affect the authors' royalty earnings.
*/

UPDATE titles

    SET price = price * 1.1

        WHERE title = 'The Gourmet Microwave'

SELECT (price * royalty * ytd_sales) * royaltyper

    FROM titles, titleauthor

        WHERE title = 'The Gourmet Microwave'

            AND titles.title_id = titleauthor.title_id

/*

The transaction is rolled back to the savepoint
with the ROLLBACK TRANSACTION statement.

*/

ROLLBACK TRANSACTION percentchanged

COMMIT TRANSACTION

/* End of royaltychange. */

See Also
BEGIN TRANSACTION | INSERT
COMMIT TRANSACTION | ROLLBACK TRANSACTION
COMMIT WORK | ROLLBACK WORK
CREATE PROCEDURE | SELECT
CREATE TRIGGER | UPDATE
DELETE |


Search Condition

Is a combination of one or more predicates using the logical operators AND, OR, and NOT.

Syntax

<search_condition> ::=
{ [ NOT ] <predicate> | ( <search_condition> ) }
[ {AND | OR} [NOT] {<predicate> | ( <search_condition> ) } ]
} [,…n]

<predicate> ::=
{
expression { = | <> | != | > | >= | !> | < | <= | !< } expression
| string_expression [NOT] LIKE string_expression
[ESCAPE 'escape_character']
| expression [NOT] BETWEEN expression AND expression
| expression IS [NOT] NULL
| CONTAINS
( {column | * }, '<contains_search_condition>' )
 | FREETEXT ( {column | * }, 'freetext_string' )
| expression [NOT] IN (subquery | expression [,…n])
| expression { = | <> | != | > | >= | !> | < | <= | !< }
{ALL | SOME | ANY} (subquery)
| EXISTS (subquery)
}

Arguments
<search_condition>
Specifies the conditions for the rows returned in the result set for a SELECT statement, query expression, or subquery. For an UPDATE, specifies the rows to be updated. For a DELETE statement, specifies the rows to be deleted. There is no limit to the number of predicates that can be included in a Transact-SQL statement search condition.
NOT
Negates the Boolean expression specified by the predicate. For more information, see NOT.
AND
Combines two conditions and evaluates to TRUE when both of the conditions are TRUE. For more information, see AND.
OR
Combines two conditions and evaluates to TRUE when either condition is TRUE. For more information, see OR.
<predicate>
Is an expression that returns TRUE, FALSE, or UNKNOWN.
expression
Is a column name, a constant, a function, a variable, a scalar subquery, or any combination of column names, constants, and functions connected by an operator(s) or a subquery. The expression can also contain the CASE function.
=
Is the operator used to test the equality between two expressions.
<>
Is the operator used to test the condition of two expressions not being equal to each other.
!=
Is the operator used to test the condition of two expressions not being equal to each other.
>
Is the operator used to test the condition of one expression being greater than the other.
>=
Is the operator used to test the condition of one expression being greater than or equal to the other expression.
!>
Is the operator used to test the condition of one expression not being greater than the other expression.
<
Is the operator used to test the condition of one expression being less than the other.
<=
Is the operator used to test the condition of one expression being less than or equal to the other expression.
!<
Is the operator used to test the condition of one expression not being less than the other expression.
string_expression
Is a string of characters and wildcard characters.
[NOT] LIKE
Indicates that the subsequent character string is to be used with pattern matching. For more information, see LIKE.
ESCAPE 'escape_character'
Allows a wildcard character to be searched for in a character string instead of functioning as a wildcard. escape_character is the character that is placed in front of the wildcard character to denote this special use.
[NOT] BETWEEN
Specifies an inclusive range of values. Use AND to separate the beginning and ending values. For more information, see BETWEEN.
IS [NOT] NULL
Specifies a search for null values, or for values that are not null, depending on the keywords used. An expression with a bitwise or arithmetic operator evaluates to NULL if any of the operands is NULL.
CONTAINS
Searches columns containing character-based data for precise or “fuzzy” (less precise) matches to single words and phrases, the proximity of words within a certain distance of one another, and weighted matches. Can only be used with SELECT statements. For more information, see CONTAINS.
FREETEXT
Provides a simple form of natural language query by searching columns containing character-based data for values that match the meaning rather than the exact words in the predicate. Can only be used with SELECT statements. For more information, see FREETEXT.
[NOT] IN
Specifies the search for an expression, based on the expression's inclusion in or exclusion from a list. The search expression can be a constant or a column name, and the list can be a set of constants or, more commonly, a subquery. Enclose the list of values in parentheses. For more information, see IN.
subquery
Can be considered a restricted SELECT statement and is similar to <query_expresssion> in the SELECT statement. The ORDER BY clause, the COMPUTE clause, and the INTO keyword are not allowed. For more information see SELECT.
ALL
Used with a comparison operator and a subquery. Returns TRUE for <predicate> if all values retrieved for the subquery satisfy the comparison operation, or FALSE if not all values satisfy the comparison or if the subquery returns no rows to the outer statement. For more information, see ALL.
{SOME | ANY}
Used with a comparison operator and a subquery. Returns TRUE for <predicate> if any value retrieved for the subquery satisfies the comparison operation, or FALSE if no values in the subquery satisfy the comparison or if the subquery returns no rows to the outer statement. Otherwise, the expression is unknown. For more information, see SOME | ANY.
EXISTS
Used with a subquery to test for the existence of rows returned by the subquery. For more information, see EXISTS.
Remarks

The order of precedence for the logical operators is NOT (highest), followed by AND, followed by OR. The order of evaluation at the same precedence level is from left to right. Parentheses can be used to override this order in a search condition. For information about how the logical operators operate on truth values, see AND, OR, and NOT.

Examples
A. Use WHERE with LIKE and ESCAPE syntax

This example assumes a description column exists in finances table. To search for the rows in which the description column contains the exact characters g_, use the ESCAPE option because _ is a wildcard character. Without specifying the ESCAPE option, the query would search for any description values containing the letter g followed by any single character other than the _ character.

SELECT *

FROM finances

WHERE description LIKE 'gs_' ESCAPE 'S'

GO

B. Use WHERE and LIKE syntax with Unicode data

This example uses the WHERE clause to retrieve the contact name, telephone, and fax numbers for any companies containing the string snabbköp at the end of the company name.

USE Northwind

SELECT CompanyName, ContactName, Phone, Fax

FROM Customers

WHERE CompanyName LIKE N'%snabbköp'

ORDER BY CompanyName ASC, ContactName ASC

See Also
Aggregate Functions Expressions
CASE FREETEXTTABLE
CONTAINSTABLE FROM
Cursors Operators (Logical)


SELECT @local_variable

Specifies that the given local variable (created using DECLARE @local_variable) should be set to the specified expression.

It is recommended that SET @local_variable be used for variable assignment rather than SELECT @local_variable. For more information, see SET @local_variable.

Syntax

SELECT {@local_variable = expression } [,…n]

Arguments
@local_variable
Is a declared variable for which a value is to be assigned.
expression
Is any valid Microsoft® SQL Server™ expression, including a scalar subquery.
Remarks

SELECT @local_variable is usually used to return a single value into the variable; however, it can return multiple values, for example, if expression is the name of a column. If the SELECT statement returns more than one value, the variable is assigned the last value returned.

If the SELECT statement returns no rows, the variable retains its present value. If expression is a scalar subquery that returns no value, the variable is set to NULL.

In the first example, a variable @var1 is assigned 'Generic Name' as its value. The query against the Customers table returns no rows because the value specified for CustomerID does not exist in the table. The variable retains the 'Generic Name' value.

USE Northwind

DECLARE @var1 nvarchar(30)

SELECT @var1 = 'Generic Name'

SELECT @var1 = CompanyName
FROM Customers
WHERE CustomerID = 'ALFKA'

SELECT @var1 AS 'Company Name'

This is the result.

Company Name

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

Generic Name

In this example, a subquery is used to assign a value to @var1. Because the value requested for CustomerID does not exist, the subquery returns no value and the variable is set to NULL.

USE Northwind

DECLARE @var1 nvarchar(30)

SELECT @var1 = 'Generic Name'

SELECT @var1 =
    (SELECT CompanyName
    FROM Customers
    WHERE CustomerID = 'ALFKA')

SELECT @var1 AS 'Company Name'

This is the result.

Company Name

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

NULL

One SELECT statement can initialize multiple local variables.

Note A SELECT statement that contains a variable assignment cannot also be used to perform normal result set retrieval operations.

See Also
DECLARE @local_variable | SELECT
Expressions |


SELECT

Retrieves rows from the database and allows the selection of one or many rows or columns from one or many tables. The full syntax of the SELECT statement is complex, but the main clauses can be summarized as:

SELECT select_list
[INTO new_table_]
FROM table_source
[WHERE search_condition]
[GROUP BY group_by_expression]
[HAVING search_condition]
[ORDER BY order_expression [ASC | DESC] ]

The UNION operator can be used between queries to combine their results into a single result set.

Syntax

SELECT statement ::=
<query_expression>
[ ORDER BY { order_by_expression | column_position [ ASC | DESC ] }
[,…n] ]
[ COMPUTE
{ { AVG | COUNT | MAX | MIN | SUM } (expression) } [,…n]
[ BY expression [,…n]
]
[ FOR BROWSE ]
[ OPTION (<query_hint> [,…n) ]

<query expression> ::=
{ <query specification> | (<query expression>) }
[UNION [ALL] <query specification | (<query expression>) […n] ]

<query specification> ::=
SELECT [ ALL | DISTINCT ]
[ {TOP integer | TOP integer PERCENT} [ WITH TIES] ]
<select_list>
[ INTO new_table ]
[ FROM {<table_source>} [,…n] ]
[ WHERE <search_condition> ]
[ GROUP BY [ALL] group_by_expression [,…n]
[ WITH { CUBE | ROLLUP } ]
]
[ HAVING <search_condition> ]

Because of the complexity of the SELECT statement, detailed syntax elements and arguments are shown by clause:

SELECT Clause
INTO Clause
FROM Clause
WHERE Clause
GROUP BY Clause
HAVING Clause
UNION Operator
ORDER BY Clause
COMPUTE Clause
FOR BROWSE Clause
OPTION Clause

SELECT Clause

Specifies the columns to be returned by the query.

Syntax

SELECT [ ALL | DISTINCT ]
[ TOP n [PERCENT] [ WITH TIES] ]
<select_list>

<select_list> ::=

{ *
| { table_name | view_name | table_alias }.*
| { column_name | expression | IDENTITYCOL | ROWGUIDCOL }
[ [AS] column_alias ]
 | column_alias = expression
} [,…n]

Arguments
ALL
Specifies that duplicate rows can appear in the result set. ALL is the default.
DISTINCT
Specifies that only unique rows can appear in the result set. Null values are considered equal for the purposes of the DISTINCT keyword.
TOP n [PERCENT]
Specifies that only the first n rows are to be output from the query result set. If PERCENT is also specified, only the first n percent of the rows are output from the result set. When specified with PERCENT, n must be an integer between 0 and 100.

If the query includes an ORDER BY clause, the first n rows (or n percent of rows) ordered by the ORDER BY clause are output. If the query has no ORDER BY clause, the order of the rows is arbitrary.

WITH TIES
Specifies that additional rows be returned from the base result set with the same value in the ORDER BY columns appearing as the last of the TOP n (PERCENT) rows. TOP …WITH TIES can only be specified if an ORDER BY clause is specified.
<select_list>
The columns to be selected for the result set. The select list is a series of expressions separated by commas.
*
Specifies that all columns from all tables and views in the FROM clause should be returned. The columns are returned by table or view, as specified in the FROM clause, and in the order in which they exist in the table or view.
table_name | view_name | table_alias.*
Limits the scope of the * to the specified table or view.
column_name
Is the name of a column to return. Qualify column_name to prevent an ambiguous reference, such as occurs when two tables in the FROM clause have columns with duplicate names. For example, the Customers and Orders tables in the Northwind database both have a column named ColumnID. If the two tables are joined in a query, the customer ID can be specified in the select list as Customers.CustomerID.
expression
Is a column name, constant, function, any combination of column names, constants, and functions connected by an operator(s), or a subquery.
IDENTITYCOL
Returns the identity column. For more information, see IDENTITY (Property), ALTER TABLE, and CREATE TABLE.

If the more than one table in the FROM clause has a column with the IDENTITY property, IDENTITYCOL must be qualified with the specific table name, such as T1.IDENTITYCOL.

ROWGUIDCOL
Returns the row global unique identifier column.

If the more than one table in the FROM clause with the ROWGUIDCOL property, ROWGUIDCOL must be qualified with the specific table name, such as T1.ROWGUIDCOL.

column_alias
Is an alternative name to replace the column name in the query result set. For example, an alias such as “Quantity”, or “Quantity to Date”, or “Qty” can be specified for a column named quantity.

Aliases are used also to specify names for the results of expressions, for example:

USE Northwind

SELECT AVG(UnitPrice) AS 'Average Price'
FROM [Order Details]

column_alias can be used in an ORDER BY clause; however, it cannot be used in a WHERE, GROUP BY, or HAVING clause. If the query expression is part of a DECLARE CURSOR statement, column_alias cannot be used in the FOR UPDATE clause.

INTO Clause

Creates a new table and inserts the resulting rows from the query into it.

The user executing a SELECT statement with the INTO clause must have CREATE TABLE permission in the destination database. SELECT…INTO cannot be used with the COMPUTE clause or inside an explicit transaction.

You can use SELECT…INTO to create an identical table definition (different table name) with no data by having a FALSE condition in the WHERE clause.

Syntax

[ INTO new_table ]

Arguments
new_table
Specifies the name of a new table to be created, based on the columns in the select list and the rows chosen by the WHERE clause. The format of new_table is determined by evaluating the expressions in the select list. The columns in new_table are created in the order specified by the select list. Each column in new_table has the same name, data type, and value as the corresponding expression in the select list.

When a computed column is included in the select list, the corresponding column in the new table is not a computed column. The values in the new column are the values that were computed at the time SELECT…INTO was executed.

To select into a permanent table, execute sp_dboption to turn on the select into/bulkcopy option before executing the SELECT statement.

  • If select into/bulkcopy is on in the database in which the table is to be created, a permanent table is created. The table name must be unique in the database and conform to the rules for identifiers.
  • If select into/bulkcopy is not on in the database in which the table is to be created, permanent tables cannot be created using SELECT INTO; only local or global temporary tables can be created. To create a temporary table, the table name must begin with a number sign (#). For more information about temporary tables, see CREATE TABLE.
FROM Clause

Specifies the table(s) from which to retrieve rows. The FROM clause is required except when the select list contains only constants, variables, and arithmetic expressions (no column names). For more information, see FROM.

Syntax

[ FROM {<table_source>} [,…n] ]

<table_source> ::=
 table_name [ [AS] table_alias ] [ WITH ( <table_hint> [,…n]) ]
| view_name [ [AS] table_alias ]
| rowset_function [ [AS] table_alias ]
| derived_table [AS] table_alias [ (column_alias [,…n] ) ]
| <joined_table>

<joined_table> ::=
<table_source> <join_type> <table_source> ON <search_condition>
| <table_source> CROSS JOIN <table_source>
| <joined_table>

<join_type> ::=
[ INNER | { { LEFT | RIGHT | FULL } [OUTER] } ]
[ <join_hint> ]
JOIN

Arguments
<table_source>
Specifies tables, views, derived tables, and joined tables for the SELECT statement.
table_name [ [AS] table_alias ]
Specifies the name of a table and an optional alias.
view_name [ [AS] table_alias ]
Specifies the name a view and an optional alias.
rowset_function [ [AS] table_alias ]
Is the name of a rowset function and an optional alias. For more information about a list of rowset functions, see Rowset Functions.
WITH (<table_hint> [,…n])
Specifies one or more table hints. For information about table hints, see FROM.
derived_table [ [AS] table_alias ]
Is a nested SELECT statement, retrieving rows from the specified database and table(s).
column_alias
Is an optional alias to replace a column name in the result set.
<joined_table>
Is a result set that is the product of two or more tables, for example:

FROM tab1 LEFT OUTER JOIN tab1.c3 = tab2.c3
    RIGHT OUTER JOIN tab3 LEFT OUTER JOIN tab4
        ON tab3.c1
    ON tab2.c3 = tab4.c3

For multiple CROSS joins, use parentheses to change the natural order of the joins.

<join_type>
Specifies the type of join operation.
INNER
Specifies that all matching pairs of rows are returned. Discards unmatched rows from both tables. This is the default if no join type is specified.
LEFT [OUTER]
Specifies that all rows from the left table not meeting the specified condition are included in the result set in addition to all rows returned by the inner join. Output columns from the left table are set to NULL.
RIGHT [OUTER]
Specifies that all rows from the right table not meeting the specified condition are included in the result set in addition to all rows returned by the inner join. Output columns from the right table are set to NULL.
FULL [OUTER]
If a row from either the left or right table does not match the selection criteria, specifies the row be included in the result set, and output columns that correspond to the other table be set to NULL. This is in addition to all rows usually returned by the inner join.
<join_hint>
Specifies a join hint or execution algorithm. If <join_hint> is specified, INNER, LEFT, RIGHT, or FULL must also be explicitly specified. For more information about join hints, see FROM.
JOIN
Indicates that the specified tables or views should be joined.
ON <search_condition>
Specifies the condition on which the join is based. The condition can specify any predicate, although columns and comparison operators are often used, for example:

SELECT ProductID, Suppliers.SupplierID
    FROM Suppliers JOIN Products
    ON (Suppliers.SupplierID = Products.SupplierID)

When the condition specifies columns, the columns do not have to have the same name or same data type; however, if the data types are not identical, they must be either compatible or types that Microsoft® SQL Server™ can implicitly convert. If the data types cannot be implicitly converted, the condition must explicitly convert the data type using the CAST function.

For more information about search conditions and predicates, see Search Condition.

CROSS JOIN
Specifies the cross-product of two tables. Returns the same rows as if the tables to be joined were simply listed in the FROM clause and no WHERE clause was specified. For example, both of these queries return a result set that is a cross join of all the rows in T1 and T2:

SELECT * FROM T1, T2

SELECT * FROM T1 CROSS JOIN T2

WHERE Clause

Specifies a search condition to restrict the rows returned.

Syntax

[WHERE <search_condition> | <old_outer_join>]

<old_outer_join> ::=
column_name { *= | =* } column_name

Arguments
<search_condition>
Restricts the rows returned in the result set through the use of predicates. There is no limit to the number of predicates that can be included in a search condition. For more information about search conditions and predicates, see Search Condition.
<old_outer_join>
Specifies an outer join using the nonstandard product-specific syntax and the WHERE clause. The *= operator is used to specify a left outer join and the =* operator is used to specify a right outer join.

This example specifies a left outer join in which the rows from Tab1 that do not meet the specified condition are included in the result set:

SELECT Tab1.name, Tab2.id
FROM Tab1, Tab2
WHERE Tab1.id *=Tab2.id

Note Using this syntax for outer joins is discouraged because of the potential for ambiguous interpretation and because it is nonstandard. Instead, specify joins in the FROM clause.

It is possible to specify outer joins by using join operators in the FROM clause or by using the non-standard *= and =* operators in the WHERE clause. The two methods cannot both be used in the same statement.

GROUP BY Clause

Specifies the groups into which output rows are to be placed and, if aggregate functions are included in the SELECT clause <select list>, calculates a summary value for each group. When a GROUP BY clause is used, each item in the select list must produce a single value for each group. Null values in one item are placed in one group.

Note If the ORDER BY clause is not specified, groups returned using the GROUP BY clause are not in any particular order. It is recommended that you always use the ORDER BY clause to specify a particular ordering of the data.

Syntax

[ GROUP BY [ALL] group_by_expression [,…n]
[ WITH { CUBE | ROLLUP } ]
]

Arguments
ALL
Includes all groups and result sets, even those that do not have any rows that meet the search condition specified in the WHERE clause. When ALL is specified, null values are returned for the summary columns of groups that do not meet the search condition. You cannot specify ALL with the CUBE or ROLLUP operators.

GROUP BY ALL is not supported in queries that access remote tables.

group_by_expression
Is an expression on which grouping is performed. group_by_expression is also known as a grouping column. group_by expression can be a column or a nonaggregate expression that references a column. A column alias that is defined in the select list cannot be used to specify a grouping column. When GROUP BY is specified, any column in the select list (except a column used in an aggregate function) must be specified as a grouping column.

Note Columns of type text, ntext, image, and bit cannot be used in group_by_expression.

For GROUP BY clauses that do not contain CUBE or ROLLUP, the number of group_by_expression items is limited by the GROUP BY column sizes, the aggregated columns, and the aggregate values involved in the query. This limit originates from the limit of 8,060 bytes on the intermediate work table that is needed to hold intermediate query results. A maximum of 10 grouping expressions is permitted when CUBE or ROLLUP is specified.

CUBE
Specifies that, in addition to the usual rows provided by GROUP BY, summary rows are introduced into the result set. A GROUP BY summary row is returned for every possible combination of group and subgroup in the result set. A GROUP BY summary row is displayed as NULL in the result, but is used to indicate all values. Use the GROUPING function to determine whether null values in the result set are GROUP BY summary values.

The number of summary rows in the result set is determined by the number of columns included in the GROUP BY clause. Each operand (column) in the GROUP BY clause is bound under the grouping NULL and grouping is applied to all other operands (columns). Because CUBE returns every possible combination of group and subgroup, the number of rows is the same, regardless of the order in which the grouping columns are specified.

ROLLUP
Specifies that, in addition to the usual rows provided by GROUP BY, summary rows are introduced into the result set. Groups are summarized in a hierarchical order, from the lowest level in the group to the highest. The group hierarchy is determined by the order in which the grouping columns are specified. Changing the order of the grouping columns can affect the number of rows produced in the result set.

Important Distinct aggregates, for example, AVG(DISTINCT column_name), COUNT(DISTINCT column_name), and SUM(DISTINCT column_name), are not supported when using CUBE or ROLLUP. If used, SQL Server returns an error message and cancels the query.

HAVING Clause

Specifies a search condition for a group or an aggregate. HAVING is usually used with the GROUP BY clause. When GROUP BY is not used, HAVING behaves like a WHERE clause.

Syntax

[ HAVING <search_condition> ]

Arguments
<search_condition>
Specifies the search condition for the group or the aggregate to meet. When HAVING is used with GROUP BY ALL, the HAVING clause overrides ALL. For more information, see Search Conditions.

The text, image, and ntext data types cannot be used in a HAVING clause.

Note Using the HAVING clause in the SELECT statement does not affect the way the CUBE operator groups the result set and returns summary aggregate rows.

UNION Operator

Combines the results of two or more queries into a single result set consisting of all the rows belonging to all queries in the union. This is different from using joins that combine columns from two tables.

Two basic rules for combining the result sets of two queries with UNION are:

  • The number and the order of the columns must be identical in all queries

· The data types must be compatible.

Syntax

{ <query specification> | (<query expression>) }
UNION [ALL]
<query specification | (<query expression>)
[UNION [ALL] <query specification | (<query expression>)
[…n] ]

Arguments
<query_specification> | (<query_expression>)
Is a query specification or query expression that returns data to be combined with the data from another query specification or query expression. The definitions of the columns that are part of a UNION operation do not have to be identical, but they must be compatible through implicit conversion.

The table shows the rules for comparing the data types and options of corresponding (ith) columns.

Data type of ith column | Data type of ith column of results table
Not data type-compatible (data conversion not handled implicitly by Microsoft SQL Server). | Error returned by SQL Server.
Both fixed-length char with lengths L1 and L2. | Fixed-length char with length equal to the greater of L1 and L2.
Both fixed-length binary with lengths L1 and L2. | Fixed-length binary with length equal to the greater of L1 and L2.
Either or both variable-length char. | Variable-length char with length equal to the maximum of the lengths specified for the ith columns.
Either or both variable-length binary. | Variable-length binary with length equal to the maximum of the lengths specified for the ith columns.
Both numeric data types (for example, smallint, int, float, money). | Data type equal to the maximum precision of the two columns. For example, if the ith column of table A is of type int and the ith column of table B is of type float, then the data type of the ith column of the results table is float because float is more precise than int.
Both columns’ descriptions specify NOT NULL. | Specifies NOT NULL.

UNION
Specifies that multiple result sets are to be combined and returned as a single result set.
ALL
Incorporates all rows into the results, including duplicates. If not specified, duplicate rows are removed.
ORDER BY Clause

Specifies the sort for the result set. Subqueries and view definitions cannot include an ORDER BY clause.

Syntax

[ORDER BY {order_by_expression [ ASC | DESC ] } [,…n] ]

Arguments
order_by_expression
Specifies a column on which to sort. A sort column can be specified as a name or column alias (which can be qualified by the table or view name), an expression, or a nonnegative integer representing the position of the name, alias, or expression in select list.

Multiple sort columns can be specified. The sequence of the sort columns in the ORDER BY clause defines the organization of the sorted result set.

The ORDER BY clause can include items not appearing in the select list; however, if SELECT DISTINCT is specified or if the SELECT statement contains a UNION operator, the sort columns must appear in the select list.

Furthermore, when the SELECT statement includes a UNION operator, the column names or column aliases must be those specified in the first select list.

Note ntext, text, or image columns cannot be used in an ORDER BY clause.

ASC
Specifies that the values in the specified column should be sorted in ascending order, from lowest value to highest value.
DESC
Specifies that the values in the specified column should be sorted in descending order, from highest value to lowest value.

Null values are treated as the lowest possible values.

There is no limit to the number of items in the ORDER BY clause; however, there is a limit of 8,060 bytes, for the row size of intermediate worktables needed for sort operations. This limits the total size of columns specified in an ORDER BY clause.

COMPUTE Clause

Generates totals that appear as additional summary columns at the end of the result set. When used with BY, the COMPUTE clause generates control-breaks and subtotals in the result set. You can specify COMPUTE BY and COMPUTE in the same query.

Syntax

[ COMPUTE
{ { AVG | COUNT | MAX | MIN | STDEV | STDEVP
|VAR | VARP | SUM }
(expression) } [,…n]
[ BY expression [,…n] ]
]

Arguments
AVG | COUNT | MAX | MIN | STDEV | STDEVP | VAR | VARP | SUM
Specifies the aggregation to be performed. These row aggregate functions are used with the COMPUTE clause.

Row aggregate function | Result
AVG | Average of the values in the numeric expression
COUNT | Number of selected rows
MAX | Highest value in the expression
MIN | Lowest value in the expression
STDEV | Statistical standard deviation for all values in the expression
STDEVP | Statistical standard deviation for the population for all values in the expression
SUM | Total of the values in the numeric expression
VAR | Statistical variance for all values in the expression
VARP | Statistical variance for the population for all values in the expression

There is no equivalent to COUNT(*). To find the summary information produced by GROUP BY and COUNT(*), use a COMPUTE clause without BY.

These functions ignore null values.

The DISTINCT keyword is not allowed with row aggregate functions when they are specified with the COMPUTE clause.

When you add or average integer data, SQL Server treats the result as an int value, even if the data type of the column is smallint or tinyint. For more information about the return types of added or average data, see SUM and AVG.

Note To reduce the possibility of overflow errors in ODBC and DB-Library programs, make all variable declarations for the results of averages or sums the data type int.

(expression)
An expression, such as the name of a column on which the calculation is performed. expression must appear in the select list and must be specified exactly the same as one of the expressions in the select list. A column alias specified in the select list cannot be used within expression.

Note ntext, text, or image data types cannot be specified in a COMPUTE or COMPUTE BY clause.

BY expression
Generates control-breaks and subtotals in the result set. expression is an exact copy of an order_by_expression in the associated ORDER BY clause. Typically, this is a column name or column alias. Multiple expressions can be specified. Listing multiple expressions after BY breaks a group into subgroups and applies the aggregate function at each level of grouping.

If you use COMPUTE BY, you must also use an ORDER BY clause. The expressions must be identical to or a subset of those listed after ORDER BY, and must be in the same sequence. For example, if the ORDER BY clause is:

ORDER BY a, b, c

The COMPUTE clause can be any (or all) of these:

COMPUTE BY a, b, c

COMPUTE BY a, b

COMPUTE BY a

Note In a SELECT statement with a COMPUTE clause, the order of columns in the select list overrides the order of the aggregate functions in the COMPUTE clause. ODBC and DB-Library programmers must be aware of this order requirement to put the aggregate function results in the correct place.

You cannot use COMPUTE in a SELECT INTO statement because statements including COMPUTE generate tables and their summary results are not stored in the database. Therefore, any calculations produced by COMPUTE do not appear in the new table created with the SELECT INTO statement.

You cannot use the COMPUTE clause when the SELECT statement is part of a DECLARE CURSOR statement.

FOR BROWSE Clause

Specifies that updates be allowed while viewing data in client applications using DB-Library.

A table can be browsed in an application under these conditions:

  • The table includes a time-stamped column (defined with the timestamp data type).
  • The table has a unique index.
  • The FOR BROWSE option is at the end of the SELECT statement(s) sent to SQL Server.

For more information, see DB Library for C.

Note It is not possible to use the <lock_hint> HOLDLOCK in a SELECT statement that includes the FOR BROWSE option.

The FOR BROWSE option cannot appear in SELECT statements joined by the UNION operator.

Syntax

[ FOR BROWSE ]

OPTION Clause

Specifies that the indicated query hint should be used throughout the entire query. Each query hint can be specified only once, although multiple query hints are permitted. The OPTION clause must be specified with the outermost query of the statement. The query hint affects all operators in the statement. If a UNION is involved in the main query, only the last query involving a UNION operator can have the OPTION clause. If one or more query hints causes the query optimizer to not generate a valid plan, SQL Server recompiles the query without the specified query hints, and issues a SQL Server Profiler event.

Caution Because the query optimizer usually selects the best execution plan for a query, it is recommended that <join_hint>, <query_hint>, and <table_hint> be used only as a last resort by experienced database administrators.

Syntax

[ OPTION (<query_hint> [,…n) ]

<query_hint> ::=
{ { HASH | ORDER } GROUP
| { CONCAT | HASH | MERGE } UNION
| { LOOP | MERGE | HASH } JOIN
| FAST number_rows
| FORCE ORDER
| MAXDOP number
| ROBUST PLAN
| KEEP PLAN
}

Arguments
{HASH | ORDER} GROUP
Specifies that aggregations described in the GROUP BY or COMPUTE clause of the query should use hashing or ordering.
{MERGE | HASH | CONCAT} UNION
Specifies that all UNION operations are performed by merging, hashing, or concatenating UNION sets. If more than one UNION hint is specified, the optimizer selects the least expensive strategy from those hints specified.
{LOOP | MERGE | HASH |} JOIN
Specifies that all join operations are performed by loop join, merge join, or hash join in the whole query. If more than one join hint is specified, the optimizer selects the least expensive join strategy for the allowed ones. If, in the same query, a join hint is also specified for a specific pair of tables, it takes precedence in the joining of the two tables.
FAST number_rows
Specifies that the query is optimized for fast retrieval of the first number_rows (a nonnegative integer). After the first number_rows are returned, the query continues execution and produces its full result set.
FORCE ORDER
Specifies that the join order indicated by the query syntax is preserved during query optimization.
MAXDOP number
Overrides the max degree of parallelism configuration option (of sp_configure) only for the query specifying this option. All semantic rules used with max degree of parallelism configuration option are applicable when using the MAXDOP query hint.
ROBUST PLAN
Forces the query optimizer to attempt a plan that works for the maximum potential row size, possibly at the expense of performance. When the query is processed, intermediate tables and operators may need to store and process rows that are wider than any of the input rows. The rows may be so wide that, in some cases, the particular operator cannot process the row. If this happens, SQL Server produces an error during query execution. By using ROBUST PLAN, you instruct the query optimizer not to consider any query plans that may encounter this problem.
KEEP PLAN
Forces the query optimizer to relax the estimated recompile threshold for a query. The estimated recompile threshold is the point at which a query is automatically recompiled when the estimated number of indexed column changes (update, delete or insert) have been made to a table. Specifying KEEP PLAN ensures that a query will not be recompiled as frequently when there are multiple updates to a table.
Remarks

The order of the clauses in the SELECT statement is significant. Any of the optional clauses can be omitted, but when used, they must appear in the appropriate order.

The length returned for text or ntext columns included in the select list defaults to the smallest of the actual size of the text, the default TEXTSIZE session setting, or the hard-coded application limit. To change the length of returned text for the session, use the SET statement. By default, the limit on the length of text data returned with a SELECT statement is 4,000 bytes.

SQL Server raises exception 511 and rolls back the current executing statement if either of these occur:

  • The SELECT statement produces a result row or an intermediate work table row exceeding 8,060 bytes.
  • The DELETE, INSERT, or UPDATE statement attempts action on a row exceeding 8,060 bytes.

In SQL Server, an error occurs if no column name is given to a column created by a SELECT INTO or CREATE VIEW statement. For more information, see trace flag 246 in Trace Flags.

Selecting Identity Columns

When selecting an existing identity column into a new table, the new column inherits the IDENTITY property, unless one of the following conditions is true:

  • The SELECT statement contains a join, GROUP BY clause, or aggregate function.
  • Multiple SELECT statements are joined with UNION.
  • The identity column is listed more than once in the select list.
  • The identity column is part of an expression.

If any of these conditions is true, the column is created NOT NULL instead of inheriting the IDENTITY property. All rules and restrictions for the identity columns apply to the new table.

Old-Style Outer Joins

Earlier versions of SQL Server supported the definition of outer joins that used the *= and =* operators in the WHERE clause. SQL Server version 7.0 supports the SQL-92 standard, which provides join operators in the FROM clause. It is recommended that queries be rewritten to use the SQL-92 syntax.

Processing Order of WHERE, GROUP BY, and HAVING Clauses

This list shows the processing order for a SELECT statement with a WHERE clause, a GROUP BY clause, and a HAVING clause.

  1. The WHERE clause excludes rows not meeting its search condition.
  2. The GROUP BY clause collects the selected rows into one group for each unique value in the GROUP BY clause.
  3. Aggregate functions specified in the select list calculate summary values for each group.
  4. The HAVING clause further excludes rows not meeting its search condition.
Permissions

SELECT permissions default to members of the sysadmin fixed server role, members of the db_owner fixed database role, and the table owner, who can transfer permissions to other users. If the INTO clause is used to create a permanent table, the user must have CREATE TABLE permission in the destination database.

See Also
CONTAINS | FREETEXTTABLE
CONTAINSTABLE | INSERT
CREATE TRIGGER | SET TRANSACTION ISOLATION LEVEL
CREATE VIEW | sp_dboption
DELETE | UNION
EXECUTE | UPDATE
Expressions | WHERE
FREETEXT |


SELECT Examples

A. Use SELECT to retrieve rows and columns

This example shows three code examples. This first code example returns all rows (no WHERE clause is specified) and all columns (using the *) from the authors table in the pubs database.

USE pubs

SELECT *

FROM authors

ORDER BY au_lname ASC, au_fname ASC

-- Alternate way.

USE pubs

SELECT authors.*

FROM customers

ORDER BY au_lname ASC, au_fname ASC

This example returns all rows (no WHERE clause is specified), and only a subset of the columns (au_lname, au_fname, phone, city, state) from the authors table in the pubs database. In addition, column headings are added.

USE pubs

SELECT au_fname, au_lname, phone AS Telephone, city, state

FROM authors

ORDER BY au_lname ASC, au_fname ASC

This example returns only the rows for authors who live in California and do not have the last name McBadden.

USE pubs

SELECT au_fname, au_lname, phone AS Telephone

FROM authors

WHERE state = 'CA' and au_lname <> 'McBadden'

ORDER BY au_lname ASC, au_fname ASC

B. Use SELECT with column headings and calculations

These examples return all rows from titles. The first example returns total year-to-date sales and the amounts due to each author and publisher. In the second example, the total revenue is calculated for each book.

USE pubs

SELECT ytd_sales AS Sales,

    authors.au_fname + ' '+ authors.au_lname AS Author,

    ToAuthor = (ytd_sales * royalty) / 100,

    ToPublisher = ytd_sales - (ytd_sales * royalty) / 100

FROM titles INNER JOIN titleauthor

    ON titles.title_id = titleauthor.title_id INNER JOIN authors

    ON titleauthor.au_id = authors.au_id

ORDER BY Sales DESC, Author ASC

Here is the result set:

Sales       Author                    ToAuthor    ToPublisher

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

22246       Anne Ringer               5339        16907

22246       Michel DeFrance           5339        16907

18722       Marjorie Green            4493        14229

15096       Reginald Blotchet-Halls   2113        12983

8780        Cheryl Carson             1404        7376

4095        Abraham Bennet            409         3686

4095        Akiko Yokomoto            409         3686

4095        Ann Dull                  409         3686

4095        Burt Gringlesby           409         3686

4095        Dean Straight             409         3686

4095        Marjorie Green            409         3686

4095        Michael O'Leary           409         3686

4095        Sheryl Hunter             409         3686

4072        Johnson White             407         3665

3876        Michael O'Leary           387         3489

3876        Stearns MacFeather        387         3489

3336        Charlene Locksley         333         3003

2045        Albert Ringer             245         1800

2045        Anne Ringer               245         1800

2032        Innes del Castillo        243         1789

375         Livia Karsen              37          338

375         Stearns MacFeather        37          338

375         Sylvia Panteley           37          338

111         Albert Ringer             11          100

NULL        Charlene Locksley         NULL        NULL

(25 row(s) affected)

This is the query that calculates the revenue for each book:

USE pubs

SELECT 'Total income is', price * ytd_sales AS Revenue,

'for', title_id AS Book#

FROM titles

ORDER BY Book# ASC

Here is the result set:

Revenue                    Book#

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

Total income is 81859.0500            for  BU1032

Total income is 46318.2000            for  BU1111

Total income is 55978.7800            for  BU2075

Total income is 81859.0500            for  BU7832

Total income is 40619.6800            for  MC2222

Total income is 66515.5400            for  MC3021

Total income is NULL                  for  MC3026

Total income is 201501.0000           for  PC1035

Total income is 81900.0000            for  PC8888

Total income is NULL                  for  PC9999

Total income is 8096.2500             for  PS1372

Total income is 22392.7500            for  PS2091

Total income is 777.0000              for  PS2106

Total income is 81399.2800            for  PS3333

Total income is 26654.6400            for  PS7777

Total income is 7856.2500             for  TC3218

Total income is 180397.2000           for  TC4203

Total income is 61384.0500            for  TC7777

(18 row(s) affected)

C. Use DISTINCT with SELECT

This example uses DISTINCT to prevent the retrieval of duplicate author ID numbers.

USE pubs

SELECT DISTINCT au_id

FROM authors

ORDER BY au_id

D. Create tables with SELECT INTO

This first example creates a temporary table named #coffeetabletitles in tempdb. To use this table, always refer to it with the exact name shown, including the number sign (#).

USE pubs

DROP TABLE #coffeetabletitles

GO

SET NOCOUNT ON

SELECT * INTO #coffeetabletitles

FROM titles

WHERE price < $20

SET NOCOUNT OFF

SELECT name

FROM tempdb..sysobjects

WHERE name LIKE '#c%'

Here is the result set:

name

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

#coffeetabletitles__________________________________________________________________________________________________000000000028

(1 row(s) affected)

CHECKPOINTing database that was changed.

(12 row(s) affected)

name

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

newtitles

(1 row(s) affected)

CHECKPOINTing database that was changed.

This second example creates a permanent table named newtitles.

USE pubs

IF EXISTS (SELECT table_name FROM INFORMATION_SCHEMA.TABLES

        WHERE table_name = 'newtitles')

    DROP TABLE newtitles

GO

EXEC sp_dboption 'pubs', 'select into/bulkcopy', 'true'

USE pubs

SELECT * INTO newtitles

FROM titles

WHERE price > $25 OR price < $20

SELECT name FROM sysobjects WHERE name LIKE 'new%'

USE master

EXEC sp_dboption 'pubs', 'select into/bulkcopy', 'false'

Here is the result set:

name

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

newtitles

(1 row(s) affected)

E. Use correlated subqueries

This example shows queries that are semantically equivalent and illustrates the difference between using the EXISTS keyword and the IN keyword. Both are examples of a valid subquery retrieving one instance of each publisher name for which the book title is a business book, and the publisher ID numbers match between the titles and publishers tables.

USE pubs

SELECT DISTINCT pub_name

FROM publishers

WHERE EXISTS

(SELECT *

FROM titles

WHERE pub_id = publishers.pub_id

AND type = 'business')

-- Or

USE pubs

SELECT distinct pub_name

FROM publishers

WHERE pub_id IN

(SELECT pub_id

FROM titles

WHERE type = 'business')

This example uses IN in a correlated (or repeating) subquery, which is a query that depends on the outer query for its values. It is executed repeatedly, once for each row that may be selected by the outer query. This query retrieves one instance of each author’s first and last name for which the royalty percentage in the titleauthor table is 100 and for which the author identification numbers match in the authors and titleauthor tables.

USE pubs

SELECT DISTINCT au_lname, au_fname

FROM authors

WHERE 100 IN

(SELECT royaltyper

FROM titleauthor

WHERE titleauthor.au_id = authors.au_id)

The above subquery in this statement cannot be evaluated independently of the outer query. It needs a value for authors.au_id, but this value changes as Microsoft® SQL Server™ examines different rows in authors.

A correlated subquery can also be used in the HAVING clause of an outer query. This example finds the types of books for which the maximum advance is more than twice the average for the group.

USE pubs

SELECT t1.type

FROM titles t1

GROUP BY t1.type

HAVING MAX(t1.advance) >= ALL

(SELECT 2 * AVG(t2.advance)

FROM titles t2

WHERE t1.type = t2.type)

This example uses two correlated subqueries to find the names of authors who have participated in writing at least one popular computing book.

USE pubs

SELECT au_lname, au_fname

FROM authors

WHERE au_id IN

(SELECT au_id

FROM titleauthor

WHERE title_id IN

(SELECT title_id

FROM titles

WHERE type = 'popular_comp'))

F. Use GROUP BY

This example finds the total year-to-date sales of each publisher in the database.

USE pubs

SELECT pub_id, SUM(ytd_sales) AS total

FROM titles

GROUP BY pub_id

ORDER BY pub_id

Here is the result set:

pub_id total

------ -----

0736     28286

0877     44219

1389     24941

(3 row(s) affected)

Because of the GROUP BY clause, only one row containing the sum of all sales is returned for each publisher.

G. Use GROUP BY with multiple groups

This example finds the average price and the sum of year-to-date sales, grouped by type and publisher ID.

USE pubs

SELECT type, pub_id, AVG(price) AS 'avg', sum(ytd_sales) AS 'sum'

FROM titles

GROUP BY type, pub_id

ORDER BY type, pub_id

Here is the result set:

type         pub_id avg                   sum

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

business     0736   2.9900                18722

business     1389   17.3100               12066

mod_cook     0877   11.4900               24278

popular_comp 1389   21.4750               12875

psychology   0736   11.4825               9564

psychology   0877   21.5900               375

trad_cook    0877   15.9633               19566

UNDECIDED    0877   NULL                  NULL

(8 row(s) affected)

Warning, null value eliminated from aggregate.

H. Use GROUP BY and WHERE

This example puts the results into groups after retrieving only the rows with advances greater than $5,000.

USE pubs

SELECT type, AVG(price)

FROM titles

WHERE advance > $5000

GROUP BY type

ORDER BY type

Here is the result set:

type

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

business     2.99

mod_cook     2.99

popular_comp 21.48

psychology   14.30

trad_cook    17.97

(5 row(s) affected)

I. Use GROUP BY with an expression

This example groups by an expression. You can group by an expression if the expression does not include aggregate functions.

USE pubs

SELECT AVG(ytd_sales), ytd_sales * royalty

FROM titles

GROUP BY ytd_sales * royalty

ORDER BY ytd_sales * royalty

Here is the result set:

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

NULL        NULL

111         1110

375         3750

2032        24384

2045        24540

3336        33360

3876        38760

4072        40720

4095        40950

8780        140480

15096       211344

18722       449328

22246       533904

(13 row(s) affected)

J. Compare GROUP BY and GROUP BY ALL

The first example produces groups only for those books that commanded royalties of 10 percent. Because no modern cookbooks have a royalty of 10 percent, there is no group in the results for the mod_cook type.

The second example produces groups for all types, including modern cookbooks and UNDECIDED, although the modern cookbook group does not include any rows that meet the qualification specified in the WHERE clause.

The column that holds the aggregate value (the average price) is NULL for groups that lack qualifying rows.

USE pubs

SELECT type, AVG(price)

FROM titles

WHERE royalty = 10

GROUP BY type

ORDER BY type

Here is the result set:

type

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

business     17.31

popular_comp 20.00

psychology   14.14

trad_cook    17.97

(4 row(s) affected)

-- Using GROUP BY ALL

USE pubs

SELECT type, AVG(price)

FROM titles

WHERE royalty = 10

GROUP BY all type

ORDER BY type

Here is the result set:

type

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

business     17.31

mod_cook     NULL

popular_comp 20.00

psychology   14.14

trad_cook    17.97

UNDECIDED    NULL

(6 row(s) affected)

K. Use GROUP BY with ORDER BY

This example finds the average price of each type of book and orders the results by average price.

USE pubs

SELECT type, AVG(price)

FROM titles

GROUP BY type

ORDER BY AVG(price)

Here is the result set:

type

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

UNDECIDED    NULL

mod_cook     11.49

psychology   13.50

business     13.73

trad_cook    15.96

popular_comp 21.48

(6 row(s) affected)

L. Use the HAVING clause

The first example shows a HAVING clause with an aggregate function. It groups the rows in the titles table by type and eliminates the groups that include only one book. The second example shows a HAVING clause without aggregate functions. It groups the rows in the titles table by type and eliminates those types that do not start with the letter p.

USE pubs

SELECT type

FROM titles

GROUP BY type

HAVING COUNT(*) > 1

ORDER BY type

Here is the result set:

type

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

business

mod_cook

popular_comp

psychology

trad_cook

(5 row(s) affected)

This query uses the LIKE clause in the HAVING clause.

USE pubs

SELECT type

FROM titles

GROUP BY type

HAVING type LIKE 'p%'

ORDER BY type

Here is the result set:

type

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

popular_comp

psychology

(2 row(s) affected)

M. Use HAVING and GROUP BY

This example shows using GROUP BY, HAVING, WHERE, and ORDER BY clauses in one SELECT statement. It produces groups and summary values but does so after eliminating the titles with prices under $5. It also organizes the results by pub_id.

USE pubs

SELECT pub_id, SUM(advance), AVG(price)

FROM titles

WHERE price >= $5

GROUP BY pub_id

HAVING SUM(advance) > $15000

AND AVG(price) < $20

AND pub_id > '0800'

ORDER BY pub_id

Here is the result set:

pub_id

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

0877   26,000.00                  17.89

1389   30,000.00                  18.98

(2 row(s) affected)

N. Use HAVING with SUM and AVG

This example groups the titles table by publisher and includes only those groups of publishers who have paid more than $25,000 in total advances and whose books average more than $15 in price.

USE pubs

SELECT pub_id, SUM(advance), AVG(price)

FROM titles

GROUP BY pub_id

HAVING SUM(advance) > $25000

AND AVG(price) > $15

To see the publishers who have had year-to-date sales greater than $40,000, use this query:

USE pubs

SELECT pub_id, total = SUM(ytd_sales)

FROM titles

GROUP BY pub_id

HAVING SUM(ytd_sales) > 40000

If you want to make sure there are at least six books involved in the calculations for each publisher, use HAVING COUNT(*) > 5 to eliminate the publishers that return totals for fewer than six books. The query looks like this:

USE pubs

SELECT pub_id, SUM(ytd_sales) AS total

FROM titles

GROUP BY pub_id

HAVING COUNT(*) > 5

Here is the result set:

pub_id    total

------    -----

0877        44219

1389        24941

(2 row(s) affected)

With this statement, two rows are returned. New Moon Books (0736) is eliminated.

O. Calculate group totals with COMPUTE BY

This example uses two code examples to show the use of COMPUTE BY. The first code example uses one COMPUTE BY with one aggregate function, and the second code example uses one COMPUTE BY item and two aggregate functions.

This example calculates the sum of the prices (for prices over $10) for each type of cookbook, in order first by type of book and then by price of book.

USE pubs

SELECT type, price

FROM titles

WHERE price > $10

    AND type LIKE '%cook'

ORDER BY type, price

COMPUTE SUM(price) BY type

Here is the result set:

type         price

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

mod_cook     19.9900

(1 row(s) affected)

sum

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

19.9900

(1 row(s) affected)

type         price

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

trad_cook    11.9500

trad_cook    14.9900

trad_cook    20.9500

(3 row(s) affected)

sum

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

47.8900

(1 row(s) affected)

This example retrieves the book type, publisher identification number, and price of all cookbooks. The COMPUTE BY clause uses two different aggregate functions.

USE pubs

SELECT type, pub_id, price

FROM titles

WHERE type LIKE '%cook'

ORDER BY type, pub_id

COMPUTE SUM(price), MAX(pub_id) BY type

Here is the result set:

type         pub_id price

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

mod_cook     0877   19.9900

mod_cook     0877   2.9900

(2 row(s) affected)

sum                   max

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

22.9800               0877

(1 row(s) affected)

type         pub_id price

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

trad_cook    0877   20.9500

trad_cook    0877   11.9500

trad_cook    0877   14.9900

(3 row(s) affected)

sum                   max

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

47.8900               0877

(1 row(s) affected)

P. Calculate grand values using COMPUTE without BY

The COMPUTE keyword can be used without BY to generate grand totals, grand counts, and so on.

This statement finds the grand total of the prices and advances for all types of books over $20.

USE pubs

SELECT type, price, advance

FROM titles

WHERE price > $20

COMPUTE SUM(price), SUM(advance)

You can use COMPUTE BY and COMPUTE without BY in the same query. This query finds the sum of prices and advances by type, and then computes the grand total of prices and advances for all types of books.

USE pubs

SELECT type, price, advance

FROM titles

WHERE type LIKE '%cook'

ORDER BY type, price

COMPUTE SUM(price), SUM(advance) BY type

COMPUTE SUM(price), SUM(advance)

Here is the result set:

type         price                 advance

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

mod_cook     2.9900                15000.0000

mod_cook     19.9900               .0000

(2 row(s) affected)

sum                   sum

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

22.9800               15000.0000

(1 row(s) affected)

type         price                 advance

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

trad_cook    11.9500               4000.0000

trad_cook    14.9900               8000.0000

trad_cook    20.9500               7000.0000

(3 row(s) affected)

sum                   sum

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

47.8900               19000.0000

(1 row(s) affected)

sum                   sum

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

70.8700               34000.0000

(1 row(s) affected)

Q. Calculate computed sums on all rows

This example shows only three columns in the select list and gives totals based on all prices and all advances at the end of the results.

USE pubs

SELECT type, price, advance

FROM titles

COMPUTE SUM(price), SUM(advance)

Here is the result set:

type         price                 advance

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

business     19.9900               5000.0000

business     11.9500               5000.0000

business     2.9900                10125.0000

business     19.9900               5000.0000

mod_cook     19.9900               .0000

mod_cook     2.9900                15000.0000

UNDECIDED    NULL                  NULL

popular_comp 22.9500               7000.0000

popular_comp 20.0000               8000.0000

popular_comp NULL                  NULL

psychology   21.5900               7000.0000

psychology   10.9500               2275.0000

psychology   7.0000                6000.0000

psychology   19.9900               2000.0000

psychology   7.9900                4000.0000

trad_cook    20.9500               7000.0000

trad_cook    11.9500               4000.0000

trad_cook    14.9900               8000.0000

(18 row(s) affected)

sum                   sum

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

236.2600              95400.0000

(1 row(s) affected)

Warning, null value eliminated from aggregate.

R. Use more than one COMPUTE clause

This example finds the sum of the prices of all psychology books, as well as the sum of the prices of psychology books organized by publisher. You can use different aggregate functions in the same statement by including more than one COMPUTE BY clause.

USE pubs

SELECT type, pub_id, price

FROM titles

WHERE type = 'psychology'

ORDER BY type, pub_id, price

COMPUTE SUM(price) BY type, pub_id

COMPUTE SUM(price) BY type

Here is the result set:

type         pub_id price

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

psychology   0736   7.0000

psychology   0736   7.9900

psychology   0736   10.9500

psychology   0736   19.9900

(4 row(s) affected)

sum

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

45.9300

(1 row(s) affected)

type         pub_id price

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

psychology   0877   21.5900

(1 row(s) affected)

sum

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

21.5900

(1 row(s) affected)

sum

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

67.5200

(1 row(s) affected)

S. Compare GROUP BY with COMPUTE

The first example uses the COMPUTE clause to calculate the sum for the prices of the different types of cookbooks. The second example produces the same summary information using only GROUP BY.

USE pubs

-- Using COMPUTE

SELECT type, price

FROM titles

WHERE type like '%cook'

ORDER BY type, price

COMPUTE SUM(price) BY type

Here is the result set:

type         price

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

mod_cook     2.9900

mod_cook     19.9900

(2 row(s) affected)

sum

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

22.9800

(1 row(s) affected)

type         price

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

trad_cook    11.9500

trad_cook    14.9900

trad_cook    20.9500

(3 row(s) affected)

sum

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

47.8900

(1 row(s) affected)

This is the second query using GROUP BY:

USE pubs

-- Using GROUP BY

SELECT type, SUM(price)

FROM titles

WHERE type LIKE '%cook'

GROUP BY type

ORDER BY type

Here is the result set:

type

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

mod_cook     22.9800

trad_cook    47.8900

(2 row(s) affected)

T. Use SELECT with GROUP BY, COMPUTE, and ORDER BY clauses

This example returns only those rows with current year-to-date sales, and then computes the average book cost and total advances in descending order by type. Four columns of data are returned, including a truncated title. All computed columns appear within the select list.

USE pubs

SELECT CAST(title AS char(20)) AS title, type, price, advance

FROM titles

WHERE ytd_sales IS NOT NULL

ORDER BY type DESC

COMPUTE AVG(price), SUM(advance) BY type

COMPUTE SUM(price), SUM(advance)

Here is the result set:

title                type         price                 advance

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

Onions, Leeks, and G trad_cook    20.9500               7000.0000

Fifty Years in Bucki trad_cook    11.9500               4000.0000

Sushi, Anyone?       trad_cook    14.9900               8000.0000

(3 row(s) affected)

avg                   sum

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

15.9633               19000.0000

(1 row(s) affected)

title                type         price                 advance

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

Computer Phobic AND  psychology   21.5900               7000.0000

Is Anger the Enemy?  psychology   10.9500               2275.0000

Life Without Fear    psychology   7.0000                6000.0000

Prolonged Data Depri psychology   19.9900               2000.0000

Emotional Security:  psychology   7.9900                4000.0000

(5 row(s) affected)

avg                   sum

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

13.5040               21275.0000

(1 row(s) affected)

title                type         price                 advance

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

But Is It User Frien popular_comp 22.9500               7000.0000

Secrets of Silicon V popular_comp 20.0000               8000.0000

(2 row(s) affected)

avg                   sum

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

21.4750               15000.0000

(1 row(s) affected)

title                type         price                 advance

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

Silicon Valley Gastr mod_cook     19.9900               .0000

The Gourmet Microwav mod_cook     2.9900                15000.0000

(2 row(s) affected)

avg                   sum

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

11.4900               15000.0000

(1 row(s) affected)

title                type         price                 advance

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

The Busy Executive's business     19.9900               5000.0000

Cooking with Compute business     11.9500               5000.0000

You Can Combat Compu business     2.9900                10125.0000

Straight Talk About  business     19.9900               5000.0000

(4 row(s) affected)

avg                   sum

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

13.7300               25125.0000

(1 row(s) affected)

sum                   sum

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

236.2600              95400.0000

(1 row(s) affected)

U. Use SELECT statement with CUBE

This example shows two code examples. The first example returns a result set from a SELECT statement using the CUBE operator. The SELECT statement covers a one-to-many relationship between book titles and the quantity sold of each book. By using the CUBE operator, the statement returns an extra row.

USE pubs

SELECT SUBSTRING(title, 1, 65) AS title, SUM(qty) AS 'qty'

FROM sales INNER JOIN titles

    ON sales.title_id = titles.title_id

GROUP BY title

WITH CUBE

ORDER BY title

Here is the result set:

title                                                             qty

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

NULL                                                              493

But Is It User Friendly?                                          30

Computer Phobic AND Non-Phobic Individuals: Behavior Variations   20

Cooking with Computers: Surreptitious Balance Sheets              25

…

The Busy Executive's Database Guide                               15

The Gourmet Microwave                                             40

You Can Combat Computer Stress!                                   35

(17 row(s) affected)

NULL represents all values in the title column. The result set returns values for the quantity sold of each title and the total quantity sold of all titles. Applying the CUBE operator or ROLLUP operator returns the same result.

This example uses the cube_examples table to show how the CUBE operator affects the result set and uses an aggregate function (SUM). The cube_examples table contains a product name, a customer name, and the number of orders each customer has made for a particular product.

USE pubs

CREATE TABLE cube_examples

(product_name varchar(30)  NULL,

 customer_name varchar(30) NULL,

 number_of_orders int      NULL

)

INSERT cube_examples (product_name, customer_name, number_of_orders)

    VALUES ('Filo Mix', 'Romero y tomillo', 10)

INSERT cube_examples (product_name, customer_name, number_of_orders)

    VALUES ('Outback Lager', 'Wilman Kala', 10)

INSERT cube_examples (product_name, customer_name, number_of_orders)

    VALUES ('Filo Mix', 'Romero y tomillo', 20)

INSERT cube_examples (product_name, customer_name, number_of_orders)

    VALUES ('Ikura', 'Wilman Kala', 10)

INSERT cube_examples (product_name, customer_name, number_of_orders)

    VALUES ('Ikura', 'Romero y tomillo', 10)

INSERT cube_examples (product_name, customer_name, number_of_orders)

    VALUES ('Outback Lager', 'Wilman Kala', 20)

INSERT cube_examples (product_name, customer_name, number_of_orders)

    VALUES ('Filo Mix', 'Wilman Kala', 30)

INSERT cube_examples (product_name, customer_name, number_of_orders)

    VALUES ('Filo Mix', 'Eastern Connection', 40)

INSERT cube_examples (product_name, customer_name, number_of_orders)

    VALUES ('Outback Lager', 'Eastern Connection', 10)

INSERT cube_examples (product_name, customer_name, number_of_orders)

    VALUES ('Ikura', 'Wilman Kala', 40)

INSERT cube_examples (product_name, customer_name, number_of_orders)

    VALUES ('Ikura', 'Romero y tomillo', 10)

INSERT cube_examples (product_name, customer_name, number_of_orders)

    VALUES ('Filo Mix', 'Romero y tomillo', 50)

First, issue a typical query with a GROUP BY clause and the result set.

USE pubs

SELECT product_name, customer_name, SUM(number_of_orders)

FROM cube_examples

GROUP BY product_name, customer_name

ORDER BY product_name

The GROUP BY causes the result set to form groups within groups. Here is the result set:

product_name                   customer_name

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

Filo Mix                       Eastern Connection             40

Filo Mix                       Romero y tomillo               80

Filo Mix                       Wilman Kala                    30

Ikura                          Romero y tomillo               20

Ikura                          Wilman Kala                    50

Outback Lager                  Eastern Connection             10

Outback Lager                  Wilman Kala                    30

(7 row(s) affected)

Next, issue a query with a GROUP BY clause by using the CUBE operator. The result set should include the same information, and super-aggregate information for each of the GROUP BY columns.

USE pubs

SELECT product_name, customer_name, SUM(number_of_orders)

FROM cube_examples

GROUP BY product_name, customer_name

WITH CUBE

The result set for the CUBE operator holds the values from the simple GROUP BY result set above and adds the super-aggregates for each column in the GROUP BY clause. NULL represents all values in the set from which the aggregate is computed. Here is the result set:

product_name                   customer_name

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

Filo Mix                       Eastern Connection             40

Filo Mix                       Romero y tomillo               80

Filo Mix                       Wilman Kala                    30

Filo Mix                       NULL                           150

Ikura                          Romero y tomillo               20

Ikura                          Wilman Kala                    50

Ikura                          NULL                           70

Outback Lager                  Eastern Connection             10

Outback Lager                  Wilman Kala                    30

Outback Lager                  NULL                           40

NULL                           NULL                           260

NULL                           Eastern Connection             50

NULL                           Romero y tomillo               100

NULL                           Wilman Kala                    110

(14 row(s) affected)

Line 4 of the result set indicates that a total of 150 orders for Filo Mix was placed for all customers.

Line 11 of the result set indicates that the total number of orders placed for all products by all customers is 260.

Lines 12-14 of the result set indicate that the total number of orders for each customer for all products are 100, 110, and 50, respectively.

V. Use CUBE on a result set with three columns

This example shows two code examples. The first code example produces a CUBE result set with three columns, and the second example produces a four-column CUBE result set.

The first SELECT statement returns the publication name, title, and quantity of books sold. The GROUP BY clause in this example includes two columns called pub_name and title. There are also two one-to-many relationships between publishers and titles and between titles and sales.

By using the CUBE operator, the result set contains more detailed information about the quantities of titles sold by publishers. NULL represents all values in the title column.

USE pubs

SELECT pub_name, title, SUM(qty) AS 'qty'

FROM sales INNER JOIN titles

    ON sales.title_id = titles.title_id INNER JOIN publishers

    ON publishers.pub_id = titles.pub_id

GROUP BY pub_name, title

WITH CUBE

Here is the result set:

pub_name             title                                      qty

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

Algodata Infosystems But Is It User Friendly?                    30

Algodata Infosystems Cooking with Computers: Surreptitious Ba    25

Algodata Infosystems Secrets of Silicon Valley                   50

Algodata Infosystems Straight Talk About Computers               15

Algodata Infosystems The Busy Executive's Database Guide         15

Algodata Infosystems NULL                                       135

Binnet & Hardley     Computer Phobic AND Non-Phobic Individu     20

Binnet & Hardley     Fifty Years in Buckingham Palace Kitche     20

…                                                                …

NULL                 Sushi, Anyone?                              20

NULL                 The Busy Executive's Database Guide         15

NULL                 The Gourmet Microwave                       40

NULL                 You Can Combat Computer Stress!             35

(36 row(s) affected)

Increasing the number of columns in the GROUP BY clause shows why the CUBE operator is an n-dimensional operator. A GROUP BY clause with two columns returns three more kinds of groupings when the CUBE operator is used. The number of groupings can be more than three, depending on the distinct values in the columns.

The result set is grouped by the publisher name and then by the book title. The quantity of each title sold by each publisher is listed in the right-hand column.

NULL in the title column represents all titles. For information about how to differentiate specific values and all values in the result set, see Example H. The CUBE operator returns these groups of information from one SELECT statement:

  • Quantity of each title that each publisher has sold
  • Quantity of each title sold
  • Quantity of titles sold by each publisher
  • Total number of titles sold by all publishers

Each column referenced in the GROUP BY clause has been cross-referenced with all other columns in the GROUP BY clause and the SUM aggregate has been reapplied, which produces additional rows in the result set. Information returned in the result set grows n-dimensionally along with the number of columns in the GROUP BY clause.

Note Ensure that the columns following the GROUP BY clause have meaningful, real-life relationships with each other. For example, if you use au_fname and au_lname, the CUBE operator returns irrelevant information, such as the number of books sold by authors with the same first name. Using the CUBE operator on a real-life hierarchy, such as yearly sales and quarterly sales, produces meaningless rows in the result set. It is more efficient to use the ROLLUP operator.

In this second code example, the GROUP BY clause contains three columns cross-referenced by the CUBE operator. Three one-to-many relationships exist between publishers and authors, between authors and titles, and between titles and sales.

By using the CUBE operator, more detailed information is returned about the quantities of titles sold by publishers.

USE pubs

SELECT pub_name, au_lname, title, SUM(qty)

FROM authors INNER JOIN titleauthor

    ON authors.au_id = titleauthor.au_id INNER JOIN titles

    ON titles.title_id = titleauthor.title_id INNER JOIN publishers

    ON publishers.pub_id = titles.pub_id INNER JOIN sales

    ON sales.title_id = titles.title_id

GROUP BY pub_name, au_lname, title

WITH CUBE

The CUBE operator returns this information based on the cross-referenced groupings returned with the CUBE operator:

  • Quantity of each title that each publisher has sold for each author
  • Quantity of all titles each publisher has sold for each author
  • Quantity of all titles each publisher has sold
  • Total quantity of all titles sold by all publishers for all authors
  • Quantity of each title sold by all publishers for each author
  • Quantity of all titles sold by all publishers for each author
  • Quantity of each title sold by each publisher for all authors
  • Quantity of each title sold by all publishers for each author

Note The super-aggregate for all publishers, all titles, and all authors is greater than the total number of sales, because a number of books have more than one author.

A pattern emerges as the number of relationships grows. The pattern of values and NULL in the report shows which groups have been formed for a summary aggregate. Explicit information about the groups is provided by the GROUPING function.

W. Use the GROUPING function with CUBE

This example shows how the SELECT statement uses the SUM aggregate, the GROUP BY clause, and the CUBE operator. It also uses the GROUPING function on the two columns listed after the GROUP BY clause.

USE pubs

SELECT pub_name, GROUPING(pub_name),title, GROUPING(title),

    SUM(qty) AS 'qty'

FROM sales INNER JOIN titles

    ON sales.title_id = titles.title_id INNER JOIN publishers

    ON publishers.pub_id = titles.pub_id

GROUP BY pub_name, title

WITH CUBE

The result set has two columns containing 0 and 1 values, which are produced by the GROUPING(pub_name) and GROUPING(title) expressions.

Here is the result set:

pub_name                 title                         qty

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

Algodata Infosystems   0 But Is It User Friendly?    0          30

Algodata Infosystems   0 Cooking with Computers: S   0          25

Algodata Infosystems   0 Secrets of Silicon Valley   0          50

Algodata Infosystems   0 Straight Talk About Compu   0          15

Algodata Infosystems   0 The Busy Executive's Data   0          15

Algodata Infosystems   0 NULL                        1         135

Binnet & Hardley       0 Computer Phobic AND Non-P   0          20

Binnet & Hardley       0 Fifty Years in Buckingham   0          20

…                                                                …

NULL                   1 The Busy Executive's Data   0          15

NULL                   1 The Gourmet Microwave       0          40

NULL                   1 You Can Combat Computer S   0          35

(36 row(s) affected)

X.Use the ROLLUP operator

This example shows two code examples. This first example retrieves the product name, customer name, and the sum of orders placed and uses the ROLLUP operator.

USE pubs

SELECT product_name, customer_name, SUM(number_of_orders)

    AS 'Sum orders'

FROM cube_examples

GROUP BY product_name, customer_name

WITH ROLLUP

Here is the result set:

product_name                   customer_name                  Sum orders

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

Filo Mix                       Eastern Connection             40

Filo Mix                       Romero y tomillo               80

Filo Mix                       Wilman Kala                    30

Filo Mix                       NULL                          150

Ikura                          Romero y tomillo               20

Ikura                          Wilman Kala                    50

Ikura                          NULL                           70

Outback Lager                  Eastern Connection             10

Outback Lager                  Wilman Kala                    30

Outback Lager                  NULL                           40

NULL                           NULL                           260

(11 row(s) affected)

This second example performs a ROLLUP operation on the company and department columns and totals the number of employees.

The ROLLUP operator produces a summary of aggregates. This is useful when summary information is needed but a full CUBE provides extraneous data or when you have sets within sets. For example, departments within a company are a set within a set.

USE pubs

CREATE TABLE personnel

(

 company_name varchar(20),

 department   varchar(15),

 num_employees int

)

INSERT personnel VALUES ('Du monde entier', 'Finance', 10)

INSERT personnel VALUES ('Du monde entier', 'Engineering', 40)

INSERT personnel VALUES ('Du monde entier', 'Marketing', 40)

INSERT personnel VALUES ('Piccolo und mehr', 'Accounting', 20)

INSERT personnel VALUES ('Piccolo und mehr', 'Personnel', 30)

INSERT personnel VALUES ('Piccolo und mehr', 'Payroll', 40)

In this query, the company name, department, and the sum of all employees for the company become part of the result set, in addition to the ROLLUP calculations.

SELECT company_name, department, SUM(num_employees)

FROM personnel

GROUP BY company_name, department WITH ROLLUP

Here is the result set:

company_name         department

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

Du monde entier      Engineering     40

Du monde entier      Finance         10

Du monde entier      Marketing       40

Du monde entier      NULL            90

Piccolo und mehr     Accounting      20

Piccolo und mehr     Payroll         40

Piccolo und mehr     Personnel       30

Piccolo und mehr     NULL            90

NULL                 NULL            180

(9 row(s) affected)

Y. Use the GROUPING function

This example adds three new rows to the cube_examples table. Each of the three records NULL in one or more columns to show only the ROLLUP function produces a value of 1 in the grouping column. In addition, this example modifies the SELECT statement that was used in the earlier example.

USE pubs

-- Add first row with a NULL customer name and 0 orders.

INSERT cube_examples (product_name, customer_name, number_of_orders)

    VALUES ('Ikura', NULL, 0)

-- Add second row with a NULL product and NULL customer with real value

-- for orders.

INSERT cube_examples (product_name, customer_name, number_of_orders)

    VALUES (NULL, NULL, 50)

-- Add third row with a NULL product, NULL order amount, but a real

-- customer name.

INSERT cube_examples (product_name, customer_name, number_of_orders)

VALUES (NULL, 'Wilman Kala', NULL)

SELECT product_name AS Prod, customer_name AS Cust,

    SUM(number_of_orders) AS 'Sum Orders',

    GROUPING(product_name) AS 'Grp prod_name',

    GROUPING(customer_name) AS 'Grp cust_name'

FROM cube_examples

GROUP BY product_name, customer_name

WITH ROLLUP

The GROUPING function can be used only with CUBE or ROLLUP. The GROUPING function returns 1 when an expression evaluates to NULL, because the column value is NULL and represents the set of all values. The GROUPING function returns 0 when the corresponding column (whether it is NULL or not) did not come from either the CUBE or ROLLUP options as a syntax value. The returned value has a tinyint data type.

Here is the result set:

Prod          Cust               Sum Orders  Grp prod_name Grp cust_name

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

NULL          NULL               50          0             0

NULL          Wilman Kala        NULL        0             0

NULL          NULL               50          0             1

Filo Mix      Eastern Connection 40          0             0

Filo Mix      Romero y tomillo   80          0             0

Filo Mix      Wilman Kala        30          0             0

Filo Mix      NULL               150         0             1

Ikura         NULL               0           0             0

Ikura         Romero y tomillo   20          0             0

Ikura         Wilman Kala        50          0             0

Ikura         NULL               70          0             1

Outback Lager Eastern Connection 10          0             0

Outback Lager Wilman Kala        30          0             0

Outback Lager NULL               40          0             1

NULL          NULL               310         1             1

(15 row(s) affected)

Z. Use SELECT with GROUP BY, an aggregate function, and ROLLUP

This example uses a SELECT query that contains an aggregate function and a GROUP BY clause, which lists pub_name, au_lname, and title, in that order.

USE pubs

SELECT pub_name, au_lname, title, SUM(qty) AS 'SUM'

FROM authors INNER JOIN titleauthor

    ON authors.au_id = titleauthor.au_id INNER JOIN titles

    ON titles.title_id = titleauthor.title_id INNER JOIN publishers

    ON publishers.pub_id = titles.pub_id INNER JOIN sales

    ON sales.title_id = titles.title_id

GROUP BY pub_name, au_lname, title

WITH ROLLUP

By using the ROLLUP operator, these groupings are created by moving right to left along the list of columns.

pub_name        au_lname        title        SUM(qty)

pub_name        au_lname        NULL            SUM(qty)

pub_name        NULL            NULL            SUM(qty)

NULL            NULL            NULL            SUM(qty)

NULL represents all values for that column.

If you use the SELECT statement without the ROLLUP operator, the statement creates a single grouping. The query returns a sum value for each unique combination of pub_name, au_lname, and title.

pub_name           au_lname          title          SUM(qty)

Compare these examples with the groupings created by using the CUBE operator on the same query.

pub_name        au_lname        title        SUM(qty)

pub_name        au_lname        NULL            SUM(qty)

pub_name        NULL            NULL            SUM(qty)

NULL            NULL            NULL            SUM(qty)

NULL            au_lname        title        SUM(qty)

NULL            au_lname        NULL            SUM(qty)

pub_name        NULL            title        SUM(qty)

NULL            NULL            title        SUM(qty)

The groupings correspond to the information returned in the result set. NULL in the result set represents all values in the column. The ROLLUP operator returns the following data when the columns (pub_name, au_lname, title) are in the order listed in the GROUP BY clause:

  • Quantity of each title that each publisher has sold for each author
  • Quantity of all titles each publisher has sold for each author
  • Quantity of all titles each publisher has sold
  • Total quantity of all titles sold by all publishers for all authors

Here is the result set:

pub_name          au_lname     title                                SUM

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

Algodata Infosys  Bennet       The Busy Executive's Database Guide  15

Algodata Infosys  Bennet       NULL                                 15

Algodata Infosys  Carson       NULL                                 30

Algodata Infosys  Dull         Secrets of Silicon Valley            50

Algodata Infosys  Dull         NULL                                 50

…                                                                    …

New Moon Books    White        Prolonged Data Deprivation: Four     15

New Moon Books    White        NULL                                 15

New Moon Books    NULL         NULL                                316

NULL              NULL         NULL                                791

(49 row(s) affected)

The GROUPING function can be used with the ROLLUP operator or with the CUBE operator. You can apply this function to one of the columns in the select list. The function returns either 1 or 0 depending upon whether the column is grouped by the ROLLUP operator.

a. Use the INDEX optimizer hint

This example shows two ways to use the INDEX optimizer hint. The first example shows how to force the optimizer to use a nonclustered index to retrieve rows from a table and the second example forces a table scan by using an index of 0.

-- Use the specifically named INDEX.

USE pubs

SELECT au_lname, au_fname, phone

FROM authors WITH (INDEX(aunmind))

WHERE au_lname = 'Smith'

Here is the result set:

au_lname                               au_fname             phone

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

Smith                                  Meander              913 843-0462

(1 row(s) affected)

-- Force a table scan by using INDEX = 0.

USE pubs

SELECT emp_id, fname, lname, hire_date
FROM employee (index = 0)
WHERE hire_date > '10/1/1994'

b. Use OPTION and the GROUP hints

This example shows how the OPTION (GROUP) clause is used with a GROUP BY clause.

USE pubs

SELECT a.au_fname, a.au_lname, SUBSTRING(t.title, 1, 15)

FROM authors a INNER JOIN titleauthor ta

    ON a.au_id = ta.au_id INNER JOIN titles t

    ON t.title_id = ta.title_id

GROUP BY a.au_lname, a.au_fname, t.title

ORDER BY au_lname ASC, au_fname ASC

OPTION (HASH GROUP, FAST 10)

c. Use the UNION query hint

This example uses the MERGE UNION query hint.

USE pubs

SELECT *

FROM authors a1

OPTION (MERGE UNION)

SELECT *

FROM authors a2

d. Use a simple UNION

The result set in this example includes the contents of the ContactName, CompanyName, City, and Phone columns of both the Customers and SouthAmericanCustomers tables.

USE Northwind

GO

IF EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES

        WHERE TABLE_NAME = 'SouthAmericanCustomers')

    DROP TABLE SouthAmericanCustomers

GO

-- Create SouthAmericanCustomers table.

SELECT ContactName, CompanyName, City, Phone

INTO SouthAmericanCustomers

FROM Customers

WHERE Country IN ('USA', 'Canada')

GO

-- Here is the simple union.

USE Northwind

SELECT ContactName, CompanyName, City, Phone

FROM Customers

WHERE Country IN ('USA', 'Canada')

UNION

SELECT ContactName, CompanyName, City, Phone

FROM SouthAmericanCustomers

ORDER BY CompanyName, ContactName ASC

GO

e. Use SELECT INTO with UNION

In this example, the INTO clause in the first SELECT statement specifies that the table named CustomerResults holds the final result set of the union of the designated columns of the Customers and SouthAmericanCustomers tables.

USE Northwind

IF EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES

        WHERE TABLE_NAME = 'CustomerResults')

    DROP TABLE CustomerResults

GO

USE Northwind

SELECT ContactName, CompanyName, City, Phone INTO CustomerResults

FROM Customers

WHERE Country IN ('USA', 'Canada')

UNION

SELECT ContactName, CompanyName, City, Phone

FROM SouthAmericanCustomers

ORDER BY CompanyName, ContactName ASC

GO

f. Use UNION of two SELECT statements with ORDER BY

The order of certain parameters used with the UNION clause is important. This example shows the incorrect and correct use of UNION in two SELECT statements in which a column is to be renamed in the output.

/* INCORRECT */

USE Northwind

GO

SELECT City

FROM Customers

ORDER BY Cities

UNION

SELECT Cities = City

FROM SouthAmericanCustomers

GO

/* CORRECT */

USE Northwind

GO

SELECT Cities = City

FROM Customers

    UNION

SELECT City

FROM SouthAmericanCustomers

ORDER BY Cities

GO

g. Use UNION of three SELECT statements showing the effects of ALL and parentheses

These examples use UNION to combine the results of three tables, in which all have the same 5 rows of data. The first example uses UNION ALL to show the duplicated records, and returns all 15 rows. The second example uses UNION without ALL to eliminate the duplicate rows from the combined results of the three SELECT statements, and returns 5 rows.

The final example uses ALL with the first UNION, and parentheses around the second UNION that is not using ALL. The second UNION is processed first because it is in parentheses, and returns 5 rows because the ALL option is not used and the duplicates are removed. These 5 rows are combined with the results of the first SELECT through the UNION ALL keywords, which does not remove the duplicates between the two sets of 5 rows. The final result has 10 rows.

USE Northwind

GO

IF EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES

        WHERE TABLE_NAME = 'CustomersOne')

    DROP TABLE CustomersOne

GO

IF EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES

        WHERE TABLE_NAME = 'CustomersTwo')

    DROP TABLE CustomersTwo

GO

IF EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES

        WHERE TABLE_NAME = 'CustomersThree')

    DROP TABLE CustomersThree

GO

USE Northwind

GO

SELECT ContactName, CompanyName, City, Phone INTO CustomersOne

FROM Customers

WHERE Country = 'Mexico'

GO

SELECT ContactName, CompanyName, City, Phone INTO CustomersTwo

FROM Customers

WHERE Country = 'Mexico'

GO

SELECT ContactName, CompanyName, City, Phone INTO CustomersThree

FROM Customers

WHERE Country = 'Mexico'

GO

-- Union ALL

SELECT ContactName

FROM CustomersOne

    UNION ALL

SELECT ContactName

FROM CustomersTwo

    UNION ALL

SELECT ContactName

FROM CustomersThree

GO

USE Northwind

GO

SELECT ContactName

FROM CustomersOne

    UNION

SELECT ContactName

FROM CustomersTwo

    UNION

SELECT ContactName

FROM CustomersThree

GO

USE Northwind

GO

SELECT ContactName

FROM CustomersOne

    UNION ALL

    (

        SELECT ContactName

        FROM CustomersTwo

            UNION

        SELECT ContactName

        FROM CustomersThree

    )

GO

See Also
DELETE | sp_dboption
EXECUTE | UNION
Expressions | UPDATE
CREATE TRIGGER | LIKE
CREATE VIEW | WHERE
INSERT |


SESSION_USER

Is a niladic function that allows a system-supplied value for the current session’s username to be inserted into a table when no default value is specified. Also allows the username to be used in queries, error messages, and so on.

Syntax

SESSION_USER

Return Types

nchar

Remarks

Use SESSION_USER with DEFAULT constraints in either the CREATE TABLE or ALTER TABLE statements, or use as any standard function.

Examples
A. Use SESSION_USER to return the session’s current username

This example declares a variable as char, assigns the current value of SESSION_USER, and then prints the variable with a text description.

DECLARE @session_usr char(30)

SET @session_usr = SESSION_USER

SELECT 'This session's current user is: '+ @session_usr

GO

Here is the result set:

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

This session's current user is: dbo

(1 row(s) affected)

B. Use SESSION_USER with DEFAULT constraints

This example creates a table using the SESSION_USER niladic function as a DEFAULT constraint for the delivery person.

USE pubs

GO

CREATE TABLE deliveries2

(

 order_id int IDENTITY(5000, 1) NOT NULL,

 cust_id  int NOT NULL,

 order_date datetime NOT NULL DEFAULT GETDATE(),

 delivery_date datetime NOT NULL DEFAULT DATEADD(dd, 10, GETDATE()),

 delivery_person char(30) NOT NULL DEFAULT SESSION_USER

)

GO

INSERT deliveries2 (cust_id)

VALUES (7510)

INSERT deliveries2 (cust_id)

VALUES (7231)

INSERT deliveries2 (cust_id)

VALUES (7028)

INSERT deliveries2 (cust_id)

VALUES (7392)

INSERT deliveries2 (cust_id)

VALUES (7452)

GO

This query selects all information from the deliveries2 table.

SELECT order_id AS 'Ord#', cust_id AS 'Cust#', order_date,

    delivery_date, delivery_person AS 'Delivery'

FROM deliveries2

ORDER BY order_id

GO

Here is the result set:

Ord#  Cust#  order_date          delivery_date        Delivery

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

5000  7510   Mar 4 1998 10:21AM  Mar 14 1998 10:21AM  dbo

5001  7231   Mar 4 1998 10:21AM  Mar 14 1998 10:21AM  dbo

5002  7028   Mar 4 1998 10:21AM  Mar 14 1998 10:21AM  dbo

5003  7392   Mar 4 1998 10:21AM  Mar 14 1998 10:21AM  dbo

5004  7452   Mar 4 1998 10:21AM  Mar 14 1998 10:21AM  dbo

(5 row(s) affected)

See Also
ALTER TABLE | SYSTEM_USER
CREATE TABLE | USER
CURRENT_TIMESTAMP | USER_NAME
CURRENT_USER | System Functions


SET @local_variable

Sets the specified local variable, previously created with the DECLARE @local_variable statement, to the given value.

Syntax

SET
{
{@local_variable = expression}
| { @cursor_variable =
{ @cursor_variable
 | cursor_name
 | { CURSOR
[FORWARD_ONLY | SCROLL]
[STATIC | KEYSET | DYNAMIC | FAST_FORWARD]
[READ_ONLY | SCROLL_LOCKS | OPTIMISTIC]
[TYPE_WARNING]
FOR select_statement
[FOR {READ ONLY
| UPDATE [OF column_name [,…n]] } ]
}
}
}
}

Arguments
@local_variable
Is the name of a variable of any type except cursor. Variable names must begin with one at sign (@). Variable names must conform to the rules for identifiers.
expression
Is any valid Microsoft® SQL Server™ expression.
cursor_variable
Is the name of a cursor variable. If the target cursor variable previously referenced a different cursor, that previous reference is removed.
cursor_name
Is the name of the a cursor declared using the DECLARE CURSOR statement.
CURSOR
Specifies that the SET statement contains a declaration of a cursor.
SCROLL
Specifies that the cursor supports all fetch options (FIRST, LAST, NEXT, PRIOR, RELATIVE, and ABSOLUTE). SCROLL cannot be specified if FAST_FORWARD is also specified.
FORWARD_ONLY
Specifies that the cursor supports only the FETCH NEXT option. The cursor can be retrieved only in one direction, from the first to the last row. If FORWARD_ONLY is specified without the STATIC, KEYSET, or DYNAMIC keywords, the cursor is implemented as DYNAMIC. When neither FORWARD_ONLY nor SCROLL is specified, FORWARD_ONLY is the default, unless the keywords STATIC, KEYSET, or DYNAMIC are specified. STATIC, KEYSET, and DYNAMIC cursors default to SCROLL. FAST_FORWARD and FORWARD_ONLY are mutually exclusive, if one is specified the other cannot be specified.
STATIC
Defines a cursor that makes a temporary copy of the data to be used by the cursor. All requests to the cursor are answered from this temporary table in tempdb; therefore, modifications made to base tables are not reflected in the data returned by fetches made to this cursor, and this cursor does not allow modifications.
KEYSET
Specifies that the membership and order of rows in the cursor are fixed when the cursor is opened. The set of keys that uniquely identify the rows is built into a table in tempdb known as the keyset. Changes to nonkey values in the base tables, either made by the cursor owner or committed by other users, are visible as the owner scrolls around the cursor. Inserts made by other users are not visible (inserts cannot be made through a Transact-SQL server cursor). If a row is deleted, an attempt to fetch the row returns an @@FETCH_STATUS of -2. Updates of key values from outside the cursor resemble a delete of the old row followed by an insert of the new row. The row with the new values is not visible, and attempts to fetch the row with the old values return an @@FETCH_STATUS of -2. The new values are visible if the update is done through the cursor by specifying the WHERE CURRENT OF clause.
DYNAMIC
Defines a cursor that reflects all data changes made to the rows in its result set as you scroll around the cursor. The data values, order, and membership of the rows can change on each fetch. The absolute and relative fetch options are not supported with dynamic cursors.
FAST_FORWARD
Specifies a FORWARD_ONLY, READ_ONLY cursor with optimizations enabled. FAST_FORWARD cannot be specified if SCROLL is also specified. FAST_FORWARD and FORWARD_ONLY are mutually exclusive, if one is specified the other cannot be specified.
READ_ONLY
Prevents updates from being made through this cursor. The cursor cannot be referenced in a WHERE CURRENT OF clause in an UPDATE or DELETE statement. This option overrides the default capability of a cursor to be updated.
SCROLL LOCKS
Specifies that positioned updates or deletes made through the cursor are guaranteed to succeed. SQL Server locks the rows as they are read into the cursor to ensure their availability for later modifications. SCROLL_LOCKS cannot be specified if FAST_FORWARD is also specified.
OPTIMISTIC
Specifies that positioned updates or deletes made through the cursor do not succeed if the row has been updated since it was read into the cursor. SQL Server does not lock rows as they are read into the cursor. It instead uses comparisons of timestamp column values, or a checksum value if the table has no timestamp column, to determine if the row was modified after it was read into the cursor. If the row was modified, the attempted positioned update or delete fails. OPTIMISTIC cannot be specified if FAST_FORWARD is also specified.
TYPE_WARNING
Specifies that a warning message is sent to the client if the cursor is implicitly converted from the requested type to another.
FOR select_statement
Is a standard SELECT statement that defines the result set of the cursor. The keywords COMPUTE, COMPUTE BY, FOR BROWSE, and INTO are not allowed within the select_statement of a cursor declaration.

If DISTINCT, UNION, GROUP BY, or HAVING are used, or an aggregate expression is included in the select_list, the cursor will be created as STATIC.

If each of the underlying tables does not have a unique index and an SQL-92 SCROLL cursor or a Transact-SQL KEYSET cursor is requested, it will automatically be a STATIC cursor.

If the select_statement contains an ORDER BY where the columns are not unique row identifiers, a DYNAMIC cursor is converted to a KEYSET cursor, or to a STATIC cursor if a KEYSET cursor cannot be opened. This also happens for a cursor defined using SQL-92 syntax but without the STATIC keyword.

READ ONLY
Prevents updates from being made through this cursor. The cursor cannot be referenced in a WHERE CURRENT OF clause in an UPDATE or DELETE statement. This option overrides the default capability of a cursor to be updated. This keyword varies from the earlier READ_ONLY by having a space instead of an underscore between READ and ONLY.
UPDATE [OF column_name [,…n]]
Defines updatable columns within the cursor. If OF column_name [,…n] is supplied, only the columns listed will allow modifications. If no list is supplied, all columns can be updated unless the cursor has been defined as READ_ONLY.
Remarks

After declaration, all variables are initialized to NULL. Use the SET statement to assign a value that is not NULL to a declared variable. The SET statement that assigns a value to the variable returns a single value. When initializing multiple variables use a separate SET statement for each local variable.

Variables can be used only in expressions, not in place of object names or keywords. To construct dynamic SQL statements, use EXECUTE.

The syntax rules for SET @cursor_variable do not include the LOCAL and GLOBAL keywords. When using the SET @cursor_variable = CURSOR… syntax, the cursor is created as GLOBAL or LOCAL depending on the setting of the default to local cursor database option.

Cursor variables are always local, even if they reference a global cursor. When a cursor variable references a global cursor, the cursor has both a global and a local cursor reference. For more information, see Example C.

Permissions

SET @local_variable permissions default to all users.

Examples
A. Print the value of a variable initialized with SET

    This example creates the @myvar variable, places a string value into the variable, and prints the value of the @myvar variable.

    DECLARE @myvar char(20)

    SET @myvar = 'This is a test'

    SELECT @myvar

    GO

    B. Use a local variable assigned a value with SET in a SELECT statement

      This example creates a local variable named @state and uses this local variable in a SELECT statement to find all author first and last names where the author resides in the state of Utah.

      USE pubs

      GO

      DECLARE @state char(2)

      SET @state = 'UT'

      SELECT RTRIM(au_fname) + ' ' + RTRIM(au_lname) AS Name, state

      FROM authors

      WHERE state = @state

      GO

      C. Use SET with a global cursor

      This example creates a local variable and then sets the cursor variable to the global cursor name.

      DECLARE my_cursor CURSOR GLOBAL FOR SELECT * FROM authors

         DECLARE @my_variable CURSOR

         SET @my_variable = my_cursor
                           /* There is a GLOBAL declared
                              reference (my_cursor) and a LOCAL variable
                              reference (@my_variable) to the my_cursor
                              cursor.                                    */

         DEALLOCATE my_cursor  /* There is now only a LOCAL variable
                              reference (@my_variable) to the my_cursor
                              cursor.                                    */

      D. Define a cursor with SET

      This example uses the SET statement to define a cursor.

      DECLARE @CursorVar CURSOR

      SET @CursorVar = CURSOR SCROLL DYNAMIC

      FOR

      SELECT LastName, FirstName

      FROM Northwind.dbo.Employees

      WHERE LastName like 'B%'

      OPEN @CursorVar

      FETCH NEXT FROM @CursorVar

      WHILE @@FETCH_STATUS = 0

      BEGIN

          FETCH NEXT FROM @CursorVar

      END

      CLOSE @CursorVar

      DEALLOCATE @CursorVar

      E. Assign a value from a query

      This example uses a query to assign a value to a variable.

      USE Northwind

      GO

      DECLARE @rows int

      SET @rows = (SELECT COUNT(*) FROM Customers)

      See Also
      DECLARE @local_variable | SELECT
EXECUTE | SET


SET

The Transact-SQL programming language provides several SET statements that alter the current session handling of specific information.

The SET statements are grouped into these categories.

Category | Alters the current session settings for
Date and time | Handling date and time data
Locking | Handling Microsoft® SQL Server™ locking
Miscellaneous | Miscellaneous SQL Server functionality
Query execution | Query execution and processing
SQL-92 settings | Using the SQL-92 default settings
Statistics | Displaying statistics information
Transactions | Handling SQL Server transactions

Date and Time Statements
SET DATEFIRST SET DATEFORMAT

Locking Statements
SET DEADLOCK_PRIORITY SET LOCK_TIMEOUT

Miscellaneous Statements
SET CONCAT_NULL_YIELDS_NULL | SET LANGUAGE
SET CURSOR_CLOSE_ON_COMMIT | SET OFFSETS
SET DISABLE_DEF_CNST_CHK | SET PROCID
SET FIPS_FLAGGER | SET QUOTED_IDENTIFIER
SET IDENTITY_INSERT |

Query Execution Statements
SET ARITHABORT | SET NUMERIC_ROUNDABORT
SET ARITHIGNORE | SET PARSEONLY
SET FMTONLY | SET QUERY_GOVERNOR_COST_LIMIT
SET NOCOUNT | SET ROWCOUNT
SET NOEXEC | SET TEXTSIZE

SQL-92 Settings Statements
SET ANSI_DEFAULTS | SET ANSI_NULLS
SET ANSI_NULL_DFLT_OFF | SET ANSI_PADDING
SET ANSI_NULL_DFLT_ON | SET ANSI_WARNINGS

Statistics Statements
SET FORCEPLAN | SET STATISTICS IO
SET SHOWPLAN_ALL | SET STATISTICS PROFILE
SET SHOWPLAN_TEXT | SET STATISTICS TIME

Transactions Statements
SET IMPLICIT_TRANSACTIONS | SET TRANSACTION ISOLATION LEVEL
SET REMOTE_PROC_TRANSACTIONS | SET XACT_ABORT

Considerations When Using the SET Statements
  • Except for SET FIPS_FLAGGER, SET OFFSETS, SET PARSEONLY, and SET QUOTED_IDENTIFIER, all other SET statements are set at execute or run time. SET FIPS_FLAGGER, SET OFFSETS, SET PARSEONLY, and SET QUOTED_IDENTIFIER are all set at parse time.
  • If a SET statement is set in a stored procedure, the value of the SET option is restored after control is returned from the stored procedure. Therefore, a SET statement specified in dynamic SQL does not have any effect on any statements following the dynamic SQL statement.
  • Stored procedures execute with the SET settings specified at execute time except for SET ANSI_NULLS and SET QUOTED_IDENTIFIER. Stored procedures specifying SET ANSI_NULLS or SET QUOTED_IDENTIFIER use the setting specified at stored procedure creation time. If used inside a stored procedure, any SET setting is ignored.
  • The user options setting of sp_configure allows server-wide settings and works across multiple databases. This setting also behaves like an explicit SET statement behaves except that it occurs at login time.
  • Database settings (set by using sp_dboption) are valid only at the database level and only take effect if not explicitly set. Database settings override server option settings (set using a SET statement) when an option appears at more than one level.
  • With any of the SET statements with ON and OFF settings, it is possible to specify either an ON or OFF setting for multiple SET options. For example, SET QUOTED_IDENTIFIER, ANSI_NULLS ON sets both SET QUOTED_IDENTIFIER and SET ANSI_NULLS to ON.
  • SET statement settings override database option settings (set by using sp_dboption). In addition, some connection settings are set ON automatically when a user connects to a database based on the values put into effect by the prior use of the sp_configure user options setting or the values that apply to all ODBC and OLE/DB connections.
  • When a global or shortcut SET statement (for example, SET ANSI_DEFAULTS) sets a number of settings, issuing the shortcut SET statement resets the prior settings for all those options affected by the shortcut SET statement. If an individual SET option (affected by a shortcut SET statement) is explicitly set after the shortcut SET statement is issued, the individual SET statement overrides the corresponding shortcut settings.
  • When using batches, the database context is determined by the batch established with the USE statement. Ad hoc queries and all other statements that are executed outside of the stored procedure and that are in batches inherit the option settings of the database and connection established with the USE statement.
  • When a stored procedure is executed either from a batch or from another stored procedure, it is executed under the option values that are currently set in the database which contains the stored procedure. For example, when stored procedure db1.dbo.sp1 calls stored procedure db2.dbo.sp2, then stored procedure sp1 is executed under the current compatibility level setting of database db1 and stored procedure sp2 is executed under the current compatibility level setting of database db2.
  • When a Transact-SQL statement refers to objects that reside in multiple databases, then the current database context and the current connection context (the database defined by the USE statement if it is in a batch, or the database which contains the stored procedure if it is in a stored procedure) applies to that statement.
  • With the exception of the SET QUOTED_IDENTIFIER and the SET ANSI_NULLS options, all SET options apply immediately after being set. Therefore, most Transact-SQL SET statements are interpreted during execution.


SET ANSI_DEFAULTS

Controls a group of Microsoft® SQL Server™ settings that collectively specify some SQL-92 standard behavior.

Syntax

SET ANSI_DEFAULTS {ON | OFF}

Remarks

When enabled (ON), this option enables the following SQL-92 settings:

SET ANSI_NULLS | SET CURSOR_CLOSE_ON_COMMIT
SET ANSI_NULL_DFLT_ON | SET IMPLICIT_TRANSACTIONS
SET ANSI_PADDING | SET QUOTED_IDENTIFIER
SET ANSI_WARNINGS |

Together, these SQL-92 standard SET options define the query processing environment for the duration of the user’s work session, a running trigger, or a stored procedure. These SET options, however, do not include all of the options required to conform to the SQL-92 standard.

The SQL Server ODBC driver and OLE DB Provider for SQL Server automatically set ANSI_DEFAULTS to ON when connecting. The driver and provider then set CURSOR_CLOSE_ON_COMMIT and set IMPLICIT_TRANSACTIONS both OFF. The OFF settings for SET CURSOR_CLOSE_ON_COMMIT and SET IMPLICIT_TRANSACTIONS can be configured in ODBC data sources, in ODBC connection attributes, or in OLE DB connection properties which are set in the application before connecting to SQL Server. SET ANSI_DEFAULTS defaults to OFF for connections from DB-Library applications.

When SET ANSI_DEFAULTS is issued, SET QUOTED_IDENTIFIER is set at parse time and these options are set at execute time:

SET ANSI_NULLS | SET ANSI_WARNINGS
SET ANSI_NULL_DFLT_ON | SET CURSOR_CLOSE_ON_COMMIT
SET ANSI_PADDING | SET IMPLICIT_TRANSACTIONS

Permissions

SET ANSI_DEFAULTS permissions default to all users.

Examples

This example sets SET ANSI_DEFAULTS ON and uses the DBCC USEROPTIONS statement to display the settings that are affected.

-- SET ANSI_DEFAULTS ON.

SET ANSI_DEFAULTS ON

GO

-- Display the current settings.

DBCC USEROPTIONS

GO

-- SET ANSI_DEFAULTS OFF.

SET ANSI_DEFAULTS OFF

GO

See Also
DBCC USEROPTIONS | SET CURSOR_CLOSE_ON_COMMIT
SET ANSI_NULL_DFLT_ON | SET IMPLICIT_TRANSACTIONS
SET ANSI_NULLS | SET QUOTED_IDENTIFIER
SET ANSI_PADDING | SET
SET ANSI_WARNINGS |


SET ANSI_NULL_DFLT_OFF

Alters the session’s behavior to override default nullability of new columns when the ANSI null default option for the database is true. For more information about setting the value for ANSI null default, see sp_dboption.

Syntax

SET ANSI_NULL_DFLT_OFF {ON | OFF}

Remarks

This setting only affects the nullability of new columns when the nullability of the column is not specified in the CREATE TABLE and ALTER TABLE statements. When SET ANSI_NULL_DFLT_OFF is ON, new columns created with the ALTER TABLE and CREATE TABLE statements are, by default, NOT NULL if the nullability status of the column is not explicitly specified. SET ANSI_NULL_DFLT_OFF has no effect on columns created with an explicit NULL or NOT NULL.

Both SET ANSI_NULL_DFLT_OFF and SET ANSI_NULL_DFLT_ON cannot be set ON simultaneously. If one option is set ON, then the other option is set OFF. Therefore, either SET ANSI_NULL_DFLT_OFF or SET ANSI_NULL_DFLT_ON can be set ON, or both can be set OFF. If either option is ON, then that setting (SET ANSI_NULL_DFLT_OFF or SET ANSI_NULL_DFLT_ON) takes effect. If both options are set OFF, SQL Server uses the value of the ANSI null default option of sp_dboption.

Note SET ANSI_NULL_DFLT_ON and SET ANSI_NULL_DFLT_OFF are mutually exclusive options, yet both options exist to determine whether or not the database option should be overridden. When ON, each option forces the opposite option OFF. Neither option, when set OFF, turns the opposite option ON. Instead, turning an option OFF only discontinues the current ON setting.

For the most reliable operation of Transact-SQL scripts that may be used in databases with different nullability settings, it is best to always specify NULL or NOT NULL in CREATE TABLE and ALTER TABLE statements.

The setting of SET ANSI_NULL_DFLT_OFF is set at execute or run time and not at parse time.

Permissions

SET ANSI_NULL_DFLT_OFF permissions default to all users.

Examples

This example shows the effects of SET ANSI_NULL_DFLT_OFF with both settings for the ANSI null default database option.

USE pubs

GO

-- Set the 'ANSI null default' database option to true by executing

-- sp_dboption.

GO

EXEC sp_dboption 'pubs','ANSI null default','true'

GO

-- Create table t1.

CREATE TABLE t1 (a tinyint)

GO

-- NULL INSERT should succeed.

INSERT INTO t1 (a) VALUES (null)

GO

-- SET ANSI_NULL_DFLT_OFF to ON and create table t2.

SET ANSI_NULL_DFLT_OFF ON

GO

CREATE TABLE t2 (a tinyint)

GO

-- NULL INSERT should fail.

INSERT INTO t2 (a) VALUES (null)

GO

-- SET ANSI_NULL_DFLT_OFF to OFF and create table t3.

SET ANSI_NULL_DFLT_OFF off

GO

CREATE TABLE t3 (a tinyint)

GO

-- NULL INSERT should succeed.

INSERT INTO t3 (a) VALUES (null)

GO

-- This illustrates the effect of having both the sp_dboption and SET

-- option disabled.

-- Set the 'ANSI null default' database option to false.

EXEC sp_dboption 'pubs','ANSI null default','false'

GO

-- Create table t4.

CREATE TABLE t4 (a tinyint)

GO

-- NULL INSERT should fail.

INSERT INTO t4 (a) VALUES (null)

GO

-- SET ANSI_NULL_DFLT_OFF to ON and create table t5.

SET ANSI_NULL_DFLT_OFF ON

GO

CREATE TABLE t5 (a tinyint)

GO

-- NULL insert should fail.

INSERT INTO t5 (a) VALUES (null)

GO

-- SET ANSI_NULL_DFLT_OFF to OFF and create table t6.

SET ANSI_NULL_DFLT_OFF OFF

GO

CREATE TABLE t6 (a tinyint)

GO

-- NULL insert should fail.

INSERT INTO t6 (a) VALUES (null)

GO

-- Drop tables t1 through t6.

DROP TABLE t1

DROP TABLE t2

DROP TABLE t3

DROP TABLE t4

DROP TABLE t5

DROP TABLE t6

GO

See Also
ALTER TABLE | SET ANSI_NULL_DFLT_ON
CREATE TABLE | SET


SET ANSI_NULL_DFLT_ON

Alters the session’s behavior to override default nullability of new columns when the ANSI null default option for the database is false. For more information about setting the value for ANSI null default, see sp_dboption.

Syntax

SET ANSI_NULL_DFLT_ON {ON | OFF}

Remarks

This setting only affects the nullability of new columns when the nullability of the column is not specified in the CREATE TABLE and ALTER TABLE statements. When SET ANSI_NULL_DFLT_ON is ON, new columns created with the ALTER TABLE and CREATE TABLE statements allow null values if the nullability status of the column is not explicitly specified. SET ANSI_NULL_DFLT_ON has no effect on columns created with an explicit NULL or NOT NULL.

Both SET ANSI_NULL_DFLT_OFF and SET ANSI_NULL_DFLT_ON cannot be set ON simultaneously. If one option is set ON, then the other option is set OFF. Therefore, either SET ANSI_NULL_DFLT_OFF or SET ANSI_NULL_DFLT_ON can be set ON, or both can be set OFF. If either option is ON, then that setting (SET ANSI_NULL_DFLT_OFF or SET ANSI_NULL_DFLT_ON) takes effect. If both options are set OFF, SQL Server uses the value of the ANSI null default option of sp_dboption.

Note SET ANSI_NULL_DFLT_ON and SET ANSI_NULL_DFLT_OFF are mutually exclusive options, yet both options exist to determine whether or not the database option should be overridden. When ON, each option forces the opposite option OFF. Neither option, when set OFF, turns the opposite option ON. Instead, turning an option OFF only discontinues the current ON setting.

For the most reliable operation of Transact-SQL scripts used in databases with different nullability settings, it is best to specify NULL or NOT NULL in CREATE TABLE and ALTER TABLE statements.

The SQL Server ODBC driver and OLE DB Provider for SQL Server automatically set ANSI_NULL_DFLT_ON to ON when connecting. SET ANSI_NULL_DFLT_ON defaults to OFF for connections from DB-Library applications.

When SET ANSI_DEFAULTS is ON, SET ANSI_NULL_DFLT_ON is enabled.

The setting of SET ANSI_NULL_DFLT_ON is set at execute or run time and not at parse time.

Permissions

SET ANSI_NULL_DFLT_ON permissions default to all users.

Examples

This example shows the effects of SET ANSI_NULL_DFLT_ON with both settings for the ANSI null default database option.

USE pubs

GO

-- The code from this point on demonstrates that SET ANSI_NULL_DFLT_ON

-- has an effect when the 'ANSI null default' for the database is false.

-- Set the 'ANSI null default' database option to false by executing

-- sp_dboption.

EXEC sp_dboption 'pubs','ANSI null default','false'

GO

-- Create table t1.

CREATE TABLE t1 (a tinyint)

GO

-- NULL INSERT should fail.

INSERT INTO t1 (a) VALUES (null)

GO

-- SET ANSI_NULL_DFLT_ON to ON and create table t2.

SET ANSI_NULL_DFLT_ON ON

GO

CREATE TABLE t2 (a tinyint)

GO

-- NULL insert should succeed.

INSERT INTO t2 (a) VALUES (null)

GO

-- SET ANSI_NULL_DFLT_ON to OFF and create table t3.

SET ANSI_NULL_DFLT_ON OFF

GO

CREATE TABLE t3 (a tinyint)

GO

-- NULL insert should fail.

INSERT INTO t3 (a) VALUES (null)

GO

-- The code from this point on demonstrates that SET ANSI_NULL_DFLT_ON

-- has no effect when the 'ANSI null default' for the database is true.

-- Set the 'ANSI null default' database option to true.

EXEC sp_dboption 'pubs','ANSI null default','true'

GO

-- Create table t4.

CREATE TABLE t4 (a tinyint)

GO

-- NULL INSERT should succeed.

INSERT INTO t4 (a) VALUES (null)

GO

-- SET ANSI_NULL_DFLT_ON to ON and create table t5.

SET ANSI_NULL_DFLT_ON ON

GO

CREATE TABLE t5 (a tinyint)

GO

-- NULL INSERT should succeed.

INSERT INTO t5 (a) VALUES (null)

GO

-- SET ANSI_NULL_DFLT_ON to OFF and create table t6.

SET ANSI_NULL_DFLT_ON OFF

GO

CREATE TABLE t6 (a tinyint)

GO

-- NULL INSERT should succeed.

INSERT INTO t6 (a) VALUES (null)

GO

-- Set the 'ANSI null default' database option to false.

EXEC sp_dboption 'pubs','ANSI null default','false'

GO

-- Drop tables t1 through t6.

DROP TABLE t1

DROP TABLE t2

DROP TABLE t3

DROP TABLE t4

DROP TABLE t5

DROP TABLE t6

GO

See Also
ALTER TABLE | SET ANSI_DEFAULTS
CREATE TABLE | SET
SET ANSI_NULL_DFLT_OFF |


SET ANSI_NULLS

Specifies SQL-92 compliant behavior of the Equals (=) and Not Equal to (<>) comparison operators when used with null values.

Syntax

SET ANSI_NULLS {ON | OFF}

Remarks

The SQL-92 standard requires that an equals (=) or not equal to (<>) comparison against a null value evaluates to FALSE. When SET ANSI_NULLS is ON, a SELECT statement using WHERE column_name = NULL returns zero rows even if there are null values in column_name. A SELECT statement using WHERE column_name <> NULL returns zero rows even if there are nonnull values in column_name.

When SET ANSI_NULLS is OFF, the Equals (=) and Not Equal To (<>) comparison operators do not follow the SQL-92 standard. A SELECT statement using WHERE column_name = NULL returns the rows with null values in column_name. A SELECT statement using WHERE column_name <> NULL returns the rows with nonnull values in the column.

Note Whether Microsoft® SQL Server™ interprets an empty string as either a single space or as a true empty string is controlled by the compatibility level setting of sp_dbcmptlevel. If the compatibility level is less than or equal to 65, SQL Server interprets empty strings as single spaces. If the compatibility level is equal to 70, SQL Server interprets empty strings as empty strings. For more information, see sp_dbcmptlevel.

When SET ANSI_NULLS is ON, all comparisons against a null value evaluate to UNKNOWN. When SET ANSI_NULLS is OFF, comparisons of all data against a null value evaluate to TRUE if the data value is NULL. If not specified, the setting of the ANSI nulls option of the current database applies. For more information about the ANSI nulls database option, see sp_dboption.

For a script to work as intended, regardless of the ANSI nulls database option or the setting of SET ANSI_NULLS, use IS NULL and IS NOT NULL in comparisons that may contain null values.

For stored procedures, SQL Server remembers the SET ANSI_NULLS setting value from the initial creation time of the stored procedure. Whenever the stored procedure is subsequently executed, the setting of SET ANSI_NULLS is restored to its originally used value and takes effect. When invoked inside a stored procedure, the setting of SET ANSI_NULLS is not changed.

SET ANSI_NULLS should be set to ON for executing distributed queries.

The SQL Server ODBC driver and OLE DB Provider for SQL Server automatically SET ANSI_NULLS to ON when connecting. This setting can be configured in ODBC data sources, in ODBC connection attributes, or in OLE DB connection properties that are set in the application before connecting to SQL Server. SET ANSI_NULLS defaults to OFF for connections from DB-Library applications.

When SET ANSI_DEFAULTS is ON, SET ANSI_NULLS is enabled.

The setting of SET ANSI_NULLS is set at execute or run time and not at parse time.

Permissions

SET ANSI_NULLS permissions default to all users.

Examples

This example uses the Equals (=) and Not Equal To (<>) comparison operators to make comparisons with NULL and nonnull values in a table. This example also demonstrates that IS NULL is not affected by the SET ANSI_NULLS setting.

-- Create table t1 and insert values.

CREATE TABLE t1 (a int null)

INSERT INTO t1 values (NULL)

INSERT INTO t1 values (0)

INSERT INTO t1 values (1)

GO

-- Print message and perform SELECT statements.

PRINT 'Testing default setting'

DECLARE @varname int

SELECT @varname = NULL

SELECT *

FROM t1

WHERE a = @varname

SELECT *

FROM t1

WHERE a <> @varname

SELECT *

FROM t1

WHERE a IS NULL

GO

-- SET ANSI_NULLS to ON and test.

PRINT 'Testing ANSI_NULLS ON'

SET ANSI_NULLS ON

GO

DECLARE @varname int

SELECT @varname = NULL

SELECT *

FROM t1

WHERE a = @varname

SELECT *

FROM t1

WHERE a <> @varname

SELECT *

FROM t1

WHERE a IS NULL

GO

-- SET ANSI_NULLS to OFF and test.

PRINT 'Testing SET ANSI_NULLS OFF'

SET ANSI_NULLS OFF

GO

DECLARE @varname int

SELECT @varname = NULL

SELECT *

FROM t1

WHERE a = @varname

SELECT *

FROM t1

WHERE a <> @varname

SELECT *

FROM t1

WHERE a IS NULL

GO

-- Drop table t1.

DROP TABLE t1

GO

See Also
<> (Not Equal To) | WHILE
= (Equals) | SET ANSI_DEFAULTS
IF…ELSE | SET
WHERE |


SET ANSI_PADDING

Controls how the column stores values shorter than the defined size of the column, and how the column stores values that have trailing blanks in char, varchar, binary, and varbinary data.

Syntax

SET ANSI_PADDING {ON | OFF}

Remarks

Columns defined with char, varchar, binary, and varbinary data types have a defined size.

This setting affects only the definition of new columns. After the column is created, it stores the values based on the setting when the column was created. Existing columns are not affected by a later change to this setting.

Warning It is recommended that SET ANSI_PADDING always be set to ON.

This table shows the effects of the SET ANSI_PADDING setting when values are inserted into columns with char, varchar, binary, and varbinary data types.

Setting | char(n) NOT NULL or binary(n) NOT NULL | char(n) NULL or binary(n) NULL | varchar(n) or varbinary(n)
ON | Pad original value (with trailing blanks for char columns and with trailing zeros for binary columns) to the length of the column. | Follows same rules as for char(n) or binary(n) NOT NULL when SET ANSI_PADDING is ON. | Trailing blanks in character values inserted into varchar columns are not trimmed. Trailing zeros in binary values inserted into varbinary columns are not trimmed. Values are not padded to the length of the column.
OFF | Pad original value (with trailing blanks for char columns and with trailing zeros for binary columns) to the length of the column. | Follows same rules as for varchar or varbinary when SET ANSI_PADDING is OFF. | Trailing blanks in character values inserted into a varchar column are trimmed. Trailing zeros in binary values inserted into a varbinary column are trimmed.

Note When padded, char columns are padded with blanks, and binary columns are padded with zeros. When trimmed, char columns have the trailing blanks trimmed, and binary columns have the trailing zeros trimmed.

The SQL Server ODBC driver and OLE DB Provider for SQL Server automatically SET ANSI_PADDING to ON when connecting. This can be configured in ODBC data sources, in ODBC connection attributes, or OLE DB connection properties set in the application before connecting. SET ANSI_PADDING defaults to OFF for connections from DB-Library applications.

nchar, nvarchar, and ntext columns always display the SET ANSI_PADDING ON behavior, regardless of the current setting of SET ANSI_PADDING.

When SET ANSI_DEFAULTS is ON, SET ANSI_PADDING is enabled.

The setting of SET ANSI_PADDING is set at execute or run time and not at parse time.

Permissions

SET ANSI_PADDING permissions default to all users.

Examples

This example demonstrates how the setting affects each of these data types.

SET ANSI_PADDING ON

GO

PRINT 'Testing with ANSI_PADDING ON'

GO

CREATE TABLE t1

(charcol char(16) NULL,

varcharcol varchar(16) NULL,

varbinarycol varbinary(8))

GO

INSERT INTO t1 VALUES ('No blanks', 'No blanks', 0x00ee)

INSERT INTO t1 VALUES ('Trailing blank ', 'Trailing blank ', 0x00ee00)

SELECT 'CHAR'='>' + charcol + '<', 'VARCHAR'='>' + varcharcol + '<',
    varbinarycol

FROM t1

GO

SET ANSI_PADDING OFF

GO

PRINT 'Testing with ANSI_PADDING OFF'

GO

CREATE TABLE t2

(charcol char(16) NULL,

varcharcol varchar(16) NULL,

varbinarycol varbinary(8))

GO

INSERT INTO t2 VALUES ('No blanks', 'No blanks', 0x00ee)

INSERT INTO t2 VALUES ('Trailing blank ', 'Trailing blank ', 0x00ee00)

SELECT 'CHAR'='>' + charcol + '<', 'VARCHAR'='>' + varcharcol + '<',

    varbinarycol

FROM t2

GO

DROP TABLE t1

DROP TABLE t2

GO

See Also
CREATE TABLE | SET ANSI_DEFAULTS
INSERT | SET


SET ANSI_WARNINGS

Specifies SQL-92 standard behavior for several error conditions.

Syntax

SET ANSI_WARNINGS {ON | OFF}

Remarks

SET ANSI_WARNINGS affects these conditions:

  • When ON, if null values appear in aggregate functions (such as SUM, AVG, MAX, MIN, STDEV, STDEVP, VAR, VARP, or COUNT) a warning message is generated. When OFF, no warning is issued.
  • When ON, divide-by-zero and arithmetic overflow errors cause the statement to be rolled back and an error message is generated. When OFF, divide-by-zero and arithmetic overflow errors cause null values to be returned. A divide-by-zero or arithmetic overflow error causes null values to be returned occurs if an INSERT or UPDATE is attempted on a character, Unicode, or binary column where the length of a new value exceeds the maximum size of the column. If SET ANSI_WARNINGS is ON, the INSERT or UPDATE is canceled as specified by the SQL-92 standard. Trailing blanks are ignored for character columns and trailing nulls are ignored for binary columns. When OFF, data is truncated to the size of the column and the statement succeeds.

The user options option of sp_configure can be used to set the default setting for ANSI_WARNINGS for all connections to the server. For more information, see sp_configure.

Microsoft® SQL Server™ includes the ANSI warnings database option which is equivalent to SET ANSI_WARNINGS. When SET ANSI_WARNINGS is ON, errors or warnings are raised in divide-by-zero, string too large for database column and other similar errors. When SET ANSI_WARNINGS is OFF, these errors and warnings are not raised. The default value in the model database for SET ANSI_WARNINGS is OFF. If not specified, the setting of ANSI warnings applies. If SET ANSI_WARNINGS is OFF, then SQL Server uses the ANSI warnings setting of sp_dboption. For more information, see sp_dboption.

SET ANSI_WARNINGS should be set to ON for executing distributed queries.

The SQL Server ODBC driver and OLE DB Provider for SQL Server automatically SET ANSI_WARNINGS to ON when connecting. This can be configured in ODBC data sources, in ODBC connection attributes, or OLE DB connection properties set in the application before connecting. SET ANSI_WARNINGS defaults to OFF for connections from DB-Library applications.

When SET ANSI_DEFAULTS is ON, SET ANSI_WARNINGS is enabled.

The setting of SET ANSI_WARNINGS is set at execute or run time and not at parse time.

If either SET ARITHABORT or SET ARITHIGNORE is OFF and SET ANSI_WARNINGS is ON, SQL Server still returns an error message when encountering divide-by-zero or overflow errors.

Permissions

SET ANSI_WARNINGS permissions default to all users.

Examples

This example demonstrates the three situations mentioned above with the SET ANSI_WARNINGS to ON and OFF.

USE pubs

GO

CREATE TABLE T1 ( a int, b int NULL, c varchar(20) )

GO

SET NOCOUNT ON

GO

INSERT INTO T1 VALUES (1, NULL, '')

INSERT INTO T1 VALUES (1, 0, '')

INSERT INTO T1 VALUES (2, 1, '')

INSERT INTO T1 VALUES (2, 2, '')

GO

SET NOCOUNT OFF

GO

PRINT '**** Setting ANSI_WARNINGS ON'

GO

SET ANSI_WARNINGS ON

GO

PRINT 'Testing NULL in aggregate'

GO

SELECT a, SUM(b) FROM T1 GROUP BY a

GO

PRINT 'Testing String Overflow in INSERT'

GO

INSERT INTO T1 VALUES (3, 3, 'Text string longer than 20 characters')

GO

PRINT 'Testing Divide by zero'

GO

SELECT a/b FROM T1

GO

PRINT '**** Setting ANSI_WARNINGS OFF'

GO

SET ANSI_WARNINGS OFF

GO

PRINT 'Testing NULL in aggregate'

GO

SELECT a, SUM(b) FROM T1 GROUP BY a

GO

PRINT 'Testing String Overflow in INSERT'

GO

INSERT INTO T1 VALUES (4, 4, 'Text string longer than 20 characters')

GO

PRINT 'Testing Divide by zero'

GO

SELECT a/b FROM T1

GO

DROP TABLE T1

GO

See Also
INSERT | SET ANSI_DEFAULTS
SELECT | SET


SET ARITHABORT

Terminates a query when an overflow or divide-by-zero error occurs during query execution.

Syntax

SET ARITHABORT {ON | OFF}

Remarks

If SET ARITHABORT is ON, these error conditions cause the query or batch to terminate. If the errors occur in a transaction, the transaction is rolled back. If SET ARITHABORT is OFF and one of these errors occur, a warning message is displayed, but the query, batch, or transaction continues to process as if no error occurred.

Note If neither SET ARITHABORT nor SET ARITHIGNORE is set, Microsoft® SQL Server™ returns NULL and returns a warning message after the query is executed.

When an INSERT, DELETE or UPDATE statement encounters an arithmetic error (overflow, divide-by-zero, or a domain error) during expression evaluation, SQL Server handles these errors as if SET ARITHABORT is ON. The query and the remainder of the batch is aborted and an error message is returned.

If either SET ARITHABORT or SET ARITHIGNORE is OFF and SET ANSI_WARNINGS is ON, SQL Server still returns an error message when encountering divide-by-zero or overflow errors.

The setting of SET ARITHABORT is set at execute or run time and not at parse time.

Permissions

SET ARITHABORT permissions default to all users.

Examples

This example demonstrates divide-by-zero and overflow errors with both SET ARITHABORT settings.

-- Create tables t1 and t2 and insert data values.

CREATE TABLE t1 (a tinyint, b tinyint)

CREATE TABLE t2 (a tinyint)

GO

INSERT INTO t1 VALUES (1, 0)

INSERT INTO t1 VALUES (255, 1)

GO

PRINT '*** SET ARITHABORT ON'

GO

-- SET ARITHABORT ON and testing.

SET ARITHABORT ON

GO

PRINT '*** Testing divide by zero during SELECT'

GO

SELECT a/b

FROM t1

GO

PRINT '*** Testing divide by zero during INSERT'

GO

INSERT INTO t2

SELECT a/b

FROM t1

GO

PRINT '*** Testing tinyint overflow'

GO

INSERT INTO t2

SELECT a+b

FROM t1

GO

PRINT '*** Resulting data - should be no data'

GO

SELECT *

FROM t2

GO

-- Truncate table t2.

TRUNCATE TABLE t2

GO

-- SET ARITHABORT OFF and testing.

PRINT '*** SET ARITHABORT OFF'

GO

SET ARITHABORT OFF

GO

-- This works properly.

PRINT '*** Testing divide by zero during SELECT'

GO

SELECT a/b

FROM t1

GO

-- This works as if SET ARITHABORT was ON.

PRINT '*** Testing divide by zero during INSERT'

GO

INSERT INTO t2

SELECT a/b

FROM t1

GO

PRINT '*** Testing tinyint overflow'

GO

INSERT INTO t2

SELECT a+b

FROM t1

GO

PRINT '*** Resulting data - should be 0 rows'

GO

SELECT *

FROM t2

GO

-- Drop tables t1 and t2.

DROP TABLE t1

DROP TABLE t2

GO

See Also
SET ARITHIGNORE SET


SET ARITHIGNORE

Controls whether error messages are returned from overflow or divide-by-zero errors during a query.

Syntax

SET ARITHIGNORE {ON | OFF}

Remarks

The SET ARITHIGNORE setting only controls whether an error message is returned. Microsoft® SQL Server™ returns a NULL in a calculation involving an overflow or divide-by-zero error, regardless of this setting. The SET ARITHABORT setting can be used to determine whether or not the query is terminated. This setting has no effect on errors occurring during INSERT, UPDATE, and DELETE statements.

If either SET ARITHABORT or SET ARITHIGNORE is OFF and SET ANSI_WARNINGS is ON, SQL Server still returns an error message when encountering divide-by-zero or overflow errors.

The setting of SET ARITHIGNORE is set at execute or run time and not at parse time.

Permissions

SET ARITHIGNORE permissions default to all users.

Examples

This example demonstrates both SET ARITHIGNORE settings with both types of query errors.

PRINT 'Setting ARITHIGNORE ON'

GO

-- SET ARITHIGNORE ON and testing.

SET ARITHIGNORE ON

GO

SELECT 1/0

GO

SELECT CAST(256 AS tinyint)

GO

PRINT 'Setting ARITHIGNORE OFF'

GO

-- SET ARITHIGNORE OFF and testing.

SET ARITHIGNORE OFF

GO

SELECT 1/0

GO

SELECT CAST(256 AS tinyint)

GO

See Also
SET ARITHABORT SET


SET CONCAT_NULL_YIELDS_NULL

Controls whether or not concatenation results are treated as null or empty string values.

Syntax

SET CONCAT_NULL_YIELDS_NULL {ON | OFF}

Remarks

When SET CONCAT_NULL_YIELDS_NULL is ON, concatenating a null value with a string yields a NULL result. For example, SELECT ‘abc’ + NULL yields NULL. When SET CONCAT_NULL_YIELDS_NULL is OFF, concatenating a null value with a string yields the string itself (the null value is treated as an empty string). For example, SELECT ‘abc’ + NULL yields abc.

If not specified, the setting of the concat null yields null database option applies.

Note SET CONCAT_NULL_YIELDS_NULL is the same setting as the concat null yields null setting of sp_dboption.

The setting of SET CONCAT_NULL_YIELDS_NULL is set at execute or run time and not at parse time.

See Also
sp_dboption SET


SET CURSOR_CLOSE_ON_COMMIT

Controls whether or not a cursor is closed when a transaction is committed.

Syntax

SET CURSOR_CLOSE_ON_COMMIT {ON | OFF}

Remarks

When SET CURSOR_CLOSE_ON_COMMIT is ON, this setting closes any open cursors on commit in compliance with SQL-92. When SET CURSOR_CLOSE_ON_COMMIT is OFF, the cursor is not closed when a transaction is committed.

When SET CURSOR_CLOSE_ON_COMMIT is ON, a ROLLBACK statement closes all open cursors. When SET CURSOR_CLOSE_ON_COMMIT is OFF, a ROLLBACK statement closes all open cursors except those defined as INSENSITIVE or STATIC. STATIC or INSENSITIVE cursors that were opened after modifications were made will no longer reflect the state of the data if the modifications are rolled back.

SET CURSOR_CLOSE_ON_COMMIT controls the same behavior as the cursor close on commit database option of sp_dboption. If SET CURSOR_CLOSE_ON_COMMIT is OFF, SQL Server uses the cursor close on commit setting. If SET CURSOR_CLOSE_ON_COMMIT has not been specified, the cursor close on commit setting of sp_dboption applies.

The Microsoft OLE DB Provider for SQL Server and the Microsoft SQL Server ODBC driver both SET CURSOR_CLOSE_ON_COMMIT OFF when they connect. DB-Library does not automatically set the CURSOR_CLOSE_ON_COMMIT value.

When SET ANSI_DEFAULTS is ON, SET CURSOR_CLOSE_ON_COMMIT is enabled.

The setting of SET CURSOR_CLOSE_ON_COMMIT is set at execute or run time and not at parse time.

Permissions

SET CURSOR_CLOSE_ON_COMMIT permissions default to all users.

Examples

This example defines a cursor in a transaction and attempts to use it after the transaction is committed.

SET NOCOUNT ON

CREATE TABLE t1 ( a int )

GO

INSERT INTO t1 values (1)

INSERT INTO t1 values (2)

GO

PRINT '-- SET CURSOR_CLOSE_ON_COMMIT ON'

GO

SET CURSOR_CLOSE_ON_COMMIT ON

GO

PRINT '-- BEGIN TRAN'

BEGIN TRAN

PRINT '-- Declare and open cursor'

DECLARE testcursor CURSOR FOR

SELECT a

FROM t1

OPEN testcursor

PRINT '-- Commit tran'

COMMIT TRAN

PRINT '-- Try to use cursor'

FETCH NEXT FROM testcursor

CLOSE testcursor

DEALLOCATE testcursor

GO

PRINT '-- SET CURSOR_CLOSE_ON_COMMIT OFF'

GO

SET CURSOR_CLOSE_ON_COMMIT OFF

GO

PRINT '-- BEGIN TRAN'

BEGIN TRAN

PRINT '-- Declare and open cursor'

DECLARE testcursor CURSOR FOR

SELECT a

FROM t1

OPEN testcursor

PRINT '-- Commit tran'

COMMIT TRAN

PRINT '-- Try to use cursor'

FETCH NEXT FROM testcursor

CLOSE testcursor

DEALLOCATE testcursor

GO

DROP TABLE t1

GO

See Also
BEGIN TRANSACTION | SET ANSI_DEFAULTS
CLOSE | sp_dboption
COMMIT TRANSACTION | SET
ROLLBACK TRANSACTION |


SET DATEFIRST

Sets the first day of the week to a number from 1 through 7.

Syntax

SET DATEFIRST {number | @number_var}

Arguments
number | @number_var
Is the an integer indicating the first day of the week, and can be one of these values.

Value | First day of the week is
1 | Monday
2 | Tuesday
3 | Wednesday
4 | Thursday
5 | Friday
6 | Saturday
7 (default, U.S. English) | Sunday

Remarks

Use the @@DATEFIRST function to check the current setting of SET DATEFIRST.

The setting of SET DATEFIRST is set at execute or run time and not at parse time.

Permissions

SET DATEFIRST permissions default to all users.

Examples

This example displays the day of the week for a date value and shows the effects of changing the DATEFIRST setting.

-- SET DATEFIRST to U.S. English default value of 7.

SET DATEFIRST 7

GO

SELECT CAST('1/1/99' AS datetime), DATEPART(dw, '1/1/99')

-- January 1, 1999 is a Friday. Because the U.S. English default

-- specifies Sunday as the first day of the week, DATEPART of 1/1/99

-- (Friday) yields a value of 6, because Friday is the sixth day of the

-- week when starting with Sunday as day 1.

SET DATEFIRST 3

-- Because Wednesday is now considered the first day of the week,

-- DATEPART should now show that 1/1/99 (a Friday) is the third day of the -- week. The following DATEPART function should return a value of 3.

SELECT CAST('1/1/99' AS datetime), DATEPART(dw, '1/1/99')

GO

See Also
@@DATEFIRST | datetime and smalldatetime
Data Types | SET


SET DATEFORMAT

Sets the order of the date parts (month/day/year) for entering datetime or smalldatetime data.

Syntax

SET DATEFORMAT {format | @format_var}

Arguments
format | @format_var
Is the order of the dateparts. Can be either Unicode or DBCS converted to Unicode. Valid parameters include mdy, dmy, ymd, ydm, myd, and dym. The U.S. English default is mdy.
Remarks

This setting is used only in the interpretation of character strings as they are converted to date values. It has no effect on the display of date values.

The setting of SET DATEFORMAT is set at execute or run time and not at parse time.

Permissions

SET DATEFORMAT permissions default to all users.

Examples

This example uses different date formats to handle date strings in different formats.

SET DATEFORMAT mdy

GO

DECLARE @datevar datetime

SET @datevar = '12/31/98'

SELECT @datevar

GO

SET DATEFORMAT ydm

GO

DECLARE @datevar datetime

SET @datevar = '98/31/12'

SELECT @datevar

GO

SET DATEFORMAT ymd

GO

DECLARE @datevar datetime

SET @datevar = '98/12/31'

SELECT @datevar

GO

See Also
Data Types | SET
datetime and smalldatetime |


SET DEADLOCK_PRIORITY

Controls how this session reacts when in a deadlock situation. Deadlock situations arise when two processes have data locked, and each process cannot release its lock until other processes have released theirs.

Syntax

SET DEADLOCK_PRIORITY {LOW | NORMAL | @deadlock_var}

Arguments
LOW
Specifies that the current session is the preferred deadlock victim. The deadlock victim’s transaction is automatically rolled back by Microsoft® SQL Server™, and the deadlock error message 1204 is returned to the client application.
NORMAL
Specifies that the session return to the default deadlock-handling method.
@deadlock_var
Is a character variable specifying the deadlock-handling method. @deadlock_var is 3 if LOW is specified, and 6 if NORMAL is specified.
Remarks

The setting of SET DEADLOCK_PRIORITY is set at execute or run time and not at parse time.

Permissions

SET DEADLOCK_PRIORITY permissions default to all users.

See Also
@@LOCK_TIMEOUT | SET
SET LOCK_TIMEOUT |


SET DISABLE_DEF_CNST_CHK

Specified interim deferred violation checking and was used for efficiency purposes in Microsoft® SQL Server™ version 6.x.

Important SET DISABLE_DEF_CNST_CHK is included for backward compatibility only. The functionality of this statement is now built into Microsoft SQL Server version 7.0. In a future version of SQL Server, SET DISABLE_DEF_CNST_CHK may not be supported.

Remarks

If the compatibility level setting of sp_dbcmptlevel is set to 60 or 65, executing this statement does nothing. However, if the compatibility level setting of sp_dbcmptlevel is set to 70, executing this statement does nothing, and SQL Server returns a warning message.

See Also
CREATE TABLE | UPDATE
DELETE | sp_dbcmptlevel
INSERT | SET


SET FIPS_FLAGGER

Specifies checking for compliance with the FIPS 127-2 standard, which is based on the SQL-92 standard.

Syntax

SET FIPS_FLAGGER level

Arguments
level
Is the level of compliance against the FIPS 127-2 standard for which all database operations are checked. If a database operation conflicts with the level of SQL-92 standards chosen, SQL Server generates a warning.

level must be one of these values.

Value | Description
ENTRY | Standards checking for SQL-92 entry-level compliance.
FULL | Standards checking for SQL-92 full compliance.
INTERMEDIATE | Standards checking for SQL-92 intermediate-level compliance.
OFF | No standards checking.

Remarks

The setting of SET FIPS_FLAGGER is set at parse time and not at execute or run time. Setting at parse time means that if the SET statement is present in the batch or stored procedure, it takes effect, regardless of whether code execution actually reaches that point; and the SET statement takes effect before any statements are executed. For example, even if the SET statement is in an IF…ELSE statement block that is never reached during execution, the SET statement still takes effect because the IF…ELSE statement block is parsed.

If SET FIPS_FLAGGER is set in a stored procedure, the value of SET FIPS_FLAGGER is restored after control is returned from the stored procedure. Therefore, a SET FIPS_FLAGGER statement specified in dynamic SQL does not have any effect on any statements following the dynamic SQL statement.

Permissions

SET FIPS_FLAGGER permissions default to all users.

See Also
SET


SET FMTONLY

Returns only metadata to the client.

Syntax

SET FMTONLY {ON | OFF}

Remarks

No rows are processed or sent to the client as a result of the request when SET FMTONLY is turned ON.

The setting of SET FMTONLY is set at execute or run time and not at parse time.

Permissions

SET FMTONLY permissions default to all users.

Examples

This example changes the SET FMTONLY setting to ON and executes a SELECT statement. The setting causes the statement to return the column information only; no rows of data are returned.

SET FMTONLY ON

GO

USE pubs

GO

SELECT *

FROM pubs.dbo.authors

GO

See Also
SET


SET FORCEPLAN

Makes the Microsoft® SQL Server™ optimizer process join in the same order as tables appear in the FROM clause of a SELECT statement only.

Syntax

SET FORCEPLAN {ON | OFF}

Remarks

SET FORCEPLAN essentially overrides the logic used by the optimizer to process a Transact-SQL SELECT statement. The data returned by the SELECT statement is the same regardless of this setting. The only difference is how SQL Server processes the tables to satisfy the query.

Optimizer hints can also be used in queries to affect how SQL Server processes the SELECT statement.

The setting of SET FORCEPLAN is set at execute or run time and not at parse time.

Permissions

SET FORCEPLAN permissions default to all users.

Examples

This example performs a join between three tables. The SHOWPLAN_TEXT setting is enabled so SQL Server returns information about how it is processing the query differently after the SET FORCE_PLAN setting is enabled.

-- SET SHOWPLAN_TEXT to ON.

SET SHOWPLAN_TEXT ON

GO

USE pubs

GO

-- Inner join.

SELECT a.au_lname, a.au_fname, t.title

FROM authors a INNER JOIN titleauthor ta

    ON a.au_id = ta.au_id INNER JOIN titles t

    ON ta.title_id = t.title_id

GO

-- SET FORCEPLAN to ON.

SET FORCEPLAN ON

GO

-- Reexecute inner join to see the effect of SET FORCEPLAN ON.

SELECT a.au_lname, a.au_fname, t.title

FROM authors a INNER JOIN titleauthor ta

    ON a.au_id = ta.au_id INNER JOIN titles t

    ON ta.title_id = t.title_id

GO

SET SHOWPLAN_TEXT OFF

GO

SET FORCEPLAN OFF

GO

See Also
SELECT | SET SHOWPLAN_TEXT
SET SHOWPLAN_ALL | SET


SET IDENTITY_INSERT

Allows explicit values to be inserted into the identity column of a table.

Syntax

SET IDENTITY_INSERT [database.[owner.]]{table} {ON | OFF}

Arguments
database
Is the name of the database in which the specified table resides.
owner
Is the name of the table owner.
table
Is the name of a table with an identity column.
Remarks

At any time, only one table in a session can have the IDENTITY_INSERT property set to ON. If a table already has this property set to ON, and a SET IDENTITY_INSERT ON statement is issued for another table, Microsoft® SQL Server™ returns an error message that states SET IDENTITY_INSERT is already ON and reports the table it is set ON for.

If the value inserted is larger than the current identity value for the table, SQL Server automatically uses the new inserted value as the current identity value.

The setting of SET IDENTITY_INSERT is set at execute or run time and not at parse time.

Permissions

SET IDENTITY_INSERT permissions default to all users.

Examples

This example creates a table with an identity column and shows how the SET IDENTITY_INSERT setting can be used to fill a gap in the identity values caused by a DELETE statement.

-- Create products table.

CREATE TABLE products (id int IDENTITY PRIMARY KEY, product varchar(40))

GO

-- Inserting values into products table.

INSERT INTO products (product) VALUES ('screwdriver')

INSERT INTO products (product) VALUES ('hammer')

INSERT INTO products (product) VALUES ('saw')

INSERT INTO products (product) VALUES ('shovel')

GO

-- Create a gap in the identity values.

DELETE products

WHERE product = 'saw'

GO

SELECT *

FROM products

GO

-- Attempt to insert an explicit ID value of 3;

-- should return a warning.

INSERT INTO products (id, product) VALUES(3, 'garden shovel')

GO

-- SET IDENTITY_INSERT to ON.

SET IDENTITY_INSERT products ON

GO

-- Attempt to insert an explicit ID value of 3

INSERT INTO products (id, product) VALUES(3, 'garden shovel').

GO

SELECT *

FROM products

GO

-- Drop products table.

DROP TABLE products

GO

See Also
CREATE TABLE | INSERT
IDENTITY (Property) | SET


SET IMPLICIT_TRANSACTIONS

Sets implicit transaction mode for the connection.

Syntax

SET IMPLICIT_TRANSACTIONS {ON | OFF}

Remarks

When ON, SET IMPLICIT_TRANSACTIONS sets the connection into implicit transaction mode. When OFF, returns the connection to autocommit transaction mode.

When a connection is in implicit transaction mode and the connection is not currently in a transaction, executing any of the following statements start of a transaction:

ALTER TABLE | FETCH | REVOKE
CREATE | GRANT | SELECT
DELETE | INSERT | TRUNCATE TABLE
DROP | OPEN | UPDATE

If the connection is already in an open transaction, the statements do not start a new transaction.

Transactions that are automatically opened as the result of this setting being ON must be explicitly committed or rolled back by the user at the end of the transaction. Otherwise, the transaction and all the data changes it contains are rolled back when the user disconnects. After a transaction is committed, executing one of the statements above starts a new transaction.

Implicit transaction mode remains in effect until the connection executes a SET IMPLICIT_TRANSACTIONS OFF statement, which returns the connection to autocommit mode. In autocommit mode, all individual statements are committed if they complete successfully.

The Microsoft OLE DB Provider for SQL Server and the Microsoft SQL Server ODBC driver automatically SET IMPLICIT_TRANSACTIONS to OFF when connecting. SET IMPLICIT_TRANSACTIONS defaults to OFF for connections from DB-Library applications.

When SET ANSI_DEFAULTS is ON, SET IMPLICIT_TRANSACTIONS is enabled.

The setting of SET IMPLICIT_TRANSACTIONS is set at execute or run time and not at parse time.

Examples

This example demonstrates transactions that are started explicitly and implicitly with the IMPLICIT_TRANSACTIONS set ON. It uses the @@TRANCOUNT function to demonstrate open and closed transactions.

USE pubs

GO

CREATE table t1 (a int)

GO

INSERT INTO t1 VALUES (1)

GO

PRINT 'Use explicit transaction'

BEGIN TRAN

INSERT INTO t1 VALUES (2)

SELECT 'Tran count in transaction'= @@TRANCOUNT

COMMIT TRAN

SELECT 'Tran count outside transaction'= @@TRANCOUNT

GO

PRINT 'Setting IMPLICIT_TRANSACTIONS ON'

GO

SET IMPLICIT_TRANSACTIONS ON

GO

PRINT 'Use implicit transactions'

GO

-- No BEGIN TRAN needed here.

INSERT INTO t1 VALUES (4)

SELECT 'Tran count in transaction'= @@TRANCOUNT

COMMIT TRAN

SELECT 'Tran count outside transaction'= @@TRANCOUNT

GO

PRINT 'Use explicit transactions with IMPLICIT_TRANSACTIONS ON'

GO

BEGIN TRAN

INSERT INTO t1 VALUES (5)

SELECT 'Tran count in transaction'= @@TRANCOUNT

COMMIT TRAN

SELECT 'Tran count outside transaction'= @@TRANCOUNT

GO

SELECT * FROM t1

GO

-- Need to commit this tran too!

DROP TABLE t1

COMMIT TRAN

GO

See Also
ALTER TABLE | OPEN
BEGIN TRANSACTION | REVOKE
CREATE TABLE | SELECT
DELETE | SET ANSI_DEFAULTS
DROP TABLE | @@TRANCOUNT
FETCH | TRUNCATE TABLE
GRANT | UPDATE
INSERT | SET


SET LANGUAGE

Specifies the language environment for the session. The session language determines the datetime formats and system messages.

Syntax

SET LANGUAGE {[N]'language' | @language_var}

Arguments
[N]'language' | @language_var
Is the name of the language as stored in syslanguages, with a default of us_english. This argument can be either Unicode or DBCS converted to Unicode. To specify a language in Unicode, use N’language’. If specified as a variable, the variable must be sysname.
Remarks

The setting of SET LANGUAGE is set at execute or run time and not at parse time.

Permissions

SET LANGUAGE permissions default to all users.

Examples

This example sets the default language to us_english.

SET LANGUAGE us_english

GO

See Also
Data Types syslanguages (master database only)


SET LOCK_TIMEOUT

Specifies the number of milliseconds a statement waits for a lock to be released.

Syntax

SET LOCK_TIMEOUT timeout_period

Arguments
timeout_period
Is the number of milliseconds that will pass before Microsoft® SQL Server™ returns a locking error. A value of -1 (default) indicates no time-out period (that is, wait forever).

When a wait for a lock exceeds the time-out value, an error is returned. A value of 0 means not to wait at all and return a message as soon as a lock is encountered.

Remarks

At the beginning of a connection, this setting has a value of -1. After it is changed, the new setting stays in effect for the remainder of the connection.

The setting of SET LOCK_TIMEOUT is set at execute or run time and not at parse time.

The READPAST locking hint provides an alternative to this SET option.

Permissions

SET LOCK_TIMEOUT permissions default to all users.

Examples

This example sets the lock time-out period to 1,800 milliseconds.

SET LOCK_TIMEOUT 1800

GO

See Also
@@LOCK_TIMEOUT SET


SET NOCOUNT

Stops the message indicating the number of rows affected by a Transact-SQL statement from being returned as part of the results.

Syntax

SET NOCOUNT {ON | OFF}

Remarks

When SET NOCOUNT is ON, the count (indicating the number of rows affected by a Transact-SQL statement) is not returned. When SET NOCOUNT is OFF, the count is returned.

The @@ROWCOUNT function is updated even when SET NOCOUNT is ON.

SET NOCOUNT ON eliminates the sending of DONE_IN_PROC messages to the client for each statement in a stored procedure. When using the utilities provided with SQL Server to execute queries, the results prevent “nn rows affected” from being displayed at the end Transact-SQL statements such as SELECT, INSERT, UPDATE, and DELETE.

For stored procedures that contain several statements that do not return much actual data, this can provide a significant performance boost because network traffic is greatly reduced.

The setting of SET NOCOUNT is set at execute or run time and not at parse time.

Permissions

SET NOCOUNT permissions default to all users.

Examples

This example (when executed in osql or SQL Server Query Analyzer) prevents the message (about the number of rows affected) from being displayed.

USE pubs

GO

-- Display the count message.

SELECT au_lname

FROM authors

GO

USE pubs

GO

-- SET NOCOUNT to ON and no longer display the count message.

SET NOCOUNT ON

GO

SELECT au_lname

FROM authors

GO

-- Reset SET NOCOUNT to OFF.

SET NOCOUNT OFF

GO

See Also
@@ROWCOUNT SET


SET NOEXEC

Compiles each query but does not execute it.

Syntax

SET NOEXEC {ON | OFF}

Remarks

When SET NOEXEC is ON, Microsoft® SQL Server™ compiles each batch of Transact-SQL statements but does not execute them. When SET NOEXEC is OFF, all batches are executed after compilation.

The execution of statements in SQL Server consists of two phases, compilation and execution. This setting is useful for having SQL Server validate the syntax and object names in Transact-SQL code when executing. It is also useful for debugging statements that would usually be part of a larger batch of statements.

The setting of SET NOEXEC is set at execute or run time and not at parse time.

Permissions

SET NOEXEC permissions default to all users.

Examples

This example uses NOEXEC with a valid query, a query with an invalid object name, and a query with incorrect syntax.

USE pubs

GO

PRINT 'Valid query'

GO

-- SET NOEXEC to ON.

SET NOEXEC ON

GO

-- Inner join.

SELECT a.au_lname, a.au_fname, t.title

FROM authors a INNER JOIN titleauthor ta

    ON a.au_id = ta.au_id INNER JOIN titles t

    ON ta.title_id = t.title_id

GO

-- SET NOEXEC to OFF.

SET NOEXEC OFF

GO

PRINT 'Invalid object name'

GO

-- SET NOEXEC to ON.

SET NOEXEC ON

GO

-- Inner join.

SELECT a.au_lname, a.au_fname, t.title

FROM authors a INNER JOIN titleauthor ta

    ON a.au_id = ta.au_id INNER JOIN titles t

    ON ta.title_id = t.title_id

GO

-- SET NOEXEC to OFF.

SET NOEXEC OFF

GO

PRINT 'Invalid syntax'

GO

-- SET NOEXEC to ON.

SET NOEXEC ON

GO

-- Inner join.

SELECT a.au_lname, a.au_fname, t.title

FROM authors a INNER JOIN titleauthor ta

    ON a.au_id = ta.au_id INNER JOIN titles t

    ON ta.title_id = t.title_id

GO

-- Reset SET NOEXEC to OFF.

SET NOEXEC OFF

GO

See Also
SET SHOWPLAN_ALL | SET
SET SHOWPLAN_TEXT |


SET NUMERIC_ROUNDABORT

Specifies the level of error reporting generated when rounding in an expression causes a loss of precision.

Syntax

SET NUMERIC_ROUNDABORT {ON | OFF}

Remarks

When SET NUMERIC_ROUNDABORT is ON, an error is generated when a loss of precision occurs in an expression. When OFF, losses of precision do not generate error messages and the result is rounded to the precision of the column or variable storing the result.

Loss of precision occurs when attempting to store a value with a fixed precision in a column or variable with less precision.

If SET NUMERIC_ROUNDABORT is ON, SET ARITHABORT determines the severity of the generated error. This table shows the effects of these two settings when a loss of precision occurs.

Setting | SET NUMERIC_ ROUNDABORT ON | SET NUMERIC_ ROUNDABORT OFF
SET ARITHABORT ON | Error is generated; no result set returned. | No errors or warnings, result is rounded.
SET ARITHABORT OFF | Warning is returned; expression returns NULL. | No errors or warnings, result is rounded.

The setting of SET NUMERIC_ROUNDABORT is set at execute or run time and not at parse time.

Permissions

SET NUMERIC_ROUNDABORT permissions default to all users.

Examples

This example shows two values with a precision of four decimal places that are added and stored in a variable with a precision of two decimal places. The expressions demonstrate the effects of the different SET NUMERIC_ROUNDABORT and SET ARITHABORT settings.

-- SET NOCOUNT to ON,

-- SET NUMERIC_ROUNDABORT to ON, and SET ARITHABORT to ON.

SET NOCOUNT ON

PRINT 'SET NUMERIC_ROUNDABORT ON'

PRINT 'SET ARITHABORT ON'

SET NUMERIC_ROUNDABORT ON

SET ARITHABORT ON

GO

DECLARE @result decimal(5,2),

@value_1 decimal(5,4), @value_2 decimal(5,4)

SET @value_1 = 1.1234

SET @value_2 = 1.1234

SELECT @result = @value_1 + @value_2

SELECT @result

GO

-- SET NUMERIC_ROUNDABORT to ON and SET ARITHABORT to OFF.

PRINT 'SET NUMERIC_ROUNDABORT ON'

PRINT 'SET ARITHABORT OFF'

SET NUMERIC_ROUNDABORT ON

SET ARITHABORT OFF

GO

DECLARE @result decimal(5,2),

@value_1 decimal(5,4), @value_2 decimal(5,4)

SET @value_1 = 1.1234

SET @value_2 = 1.1234

SELECT @result = @value_1 + @value_2

SELECT @result

GO

-- SET NUMERIC_ROUNDABORT to OFF and SET ARITHABORT to ON.

PRINT 'SET NUMERIC_ROUNDABORT OFF'

PRINT 'SET ARITHABORT ON'

SET NUMERIC_ROUNDABORT OFF

SET ARITHABORT ON

GO

DECLARE @result decimal(5,2),

@value_1 decimal(5,4), @value_2 decimal(5,4)

SET @value_1 = 1.1234

SET @value_2 = 1.1234

SELECT @result = @value_1 + @value_2

SELECT @result

GO

-- SET NUMERIC_ROUNDABORT to OFF and SET ARITHABORT to OFF.

PRINT 'SET NUMERIC_ROUNDABORT OFF'

PRINT 'SET ARITHABORT OFF'

SET NUMERIC_ROUNDABORT OFF

SET ARITHABORT OFF

GO

DECLARE @result decimal(5,2),

@value_1 decimal(5,4), @value_2 decimal(5,4)

SET @value_1 = 1.1234

SET @value_2 = 1.1234

SELECT @result = @value_1 + @value_2

SELECT @result

GO

See Also
Data Types | SET
SET ARITHABORT |


SET OFFSETS

Returns the offset (position relative to the start of a statement) of specified keywords in Transact-SQL statements to DB-Library applications.

Syntax

SET OFFSETS keyword_list

Arguments
keyword_list
Is a comma-separated list of Transact-SQL constructs including SELECT, FROM, ORDER, COMPUTE, TABLE, PROCEDURE, STATEMENT, PARAM, and EXECUTE.
Remarks

SET OFFSETS is used only in DB-Library applications.

The setting of SET OFFSETS is set at parse time and not at execute time or run time. Setting at parse time means that if the SET statement is present in the batch or stored procedure, it takes effect, regardless of whether code execution actually reaches that point; and the SET statement takes effect before any statements are executed. For example, even if the set statement is in an IF…ELSE statement block that is never reached during execution, the SET statement still takes effect because the IF…ELSE statement block is parsed.

If SET OFFSETS is set in a stored procedure, the value of SET OFFSETS is restored after control is returned from the stored procedure. Therefore, a SET OFFSETS statement specified in dynamic SQL does not have any effect on any statements following the dynamic SQL statement.

Permissions

SET OFFSETS permissions default to all users.

See Also
SET PARSEONLY SET


SET PARSEONLY

Checks the syntax of each Transact-SQL statement and returns any error messages without compiling or executing the statement.

Syntax

SET PARSEONLY {ON | OFF}

Remarks

When SET PARSEONLY is ON, Microsoft® SQL Server™ only parses the statement. When SET PARSEONLY is OFF, SQL Server compiles and executes the statement.

The setting of SET PARSEONLY is set at parse time and not at execute or run time.

Do not use PARSEONLY in a stored procedure or a trigger. SET PARSEONLY returns offsets if the OFFSETS option is ON and no errors occur.

Permissions

SET PARSEONLY permissions default to all users.

See Also
SET OFFSETS SET


SET PROCID

Returns the identification number of the stored procedure to DB-Library applications before sending the result sets generated by that stored procedure.

Syntax

SET PROCID {ON | OFF}

Remarks

When SET PROCID is ON, Microsoft® SQL Server™ returns the ID of the stored procedure. When SET PROCID is OFF, SQL Server does not return the stored procedure’s ID.

The SET PROCID setting is used only in DB-Library applications.

The setting of SET PROCID is set at execute or run time and not at parse time.

Permissions

SET PROCID permissions default to all users.

See Also
CREATE PROCEDURE SET


SET QUERY_GOVERNOR_COST_LIMIT

Overrides the currently configured value for the current connection.

Syntax

SET QUERY_GOVERNOR_COST_LIMIT value

Arguments
value
Is a numeric or integer value indicating if all queries are allowed to run (value of 0) or if no queries are allowed to run with an estimated cost greater than the specified non-zero value. If a numeric value is specified, Microsoft® SQL Server™ truncates it to an integer.
Remarks

Using SET QUERY_GOVERNOR_COST_LIMIT applies to the current connection only and lasts the duration of the current connection. Use the query governor cost limit option of sp_configure to change the server-wide query governor cost limit value. For more information about configuring this option, see sp_configure.

The setting of SET QUERY_GOVERNOR_COST_LIMIT is set at execute or run time and not at parse time.

Permissions

SET QUERY_GOVERNOR_COST_LIMIT permissions default to members of the sysadmin fixed server role.

See Also
SET


SET QUOTED_IDENTIFIER

Causes Microsoft® SQL Server™ to follow the SQL-92 rules regarding quotation mark delimiting identifiers and literal strings. Identifiers delimited by double quotation marks can be either Transact-SQL reserved keywords or can contain characters not usually allowed by the Transact-SQL syntax rules for identifiers.

Syntax

SET QUOTED_IDENTIFIER {ON | OFF}

Remarks

When SET QUOTED_IDENTIFIER is ON, identifiers can be delimited by double quotation marks and literals must be delimited by single quotation marks. When SET QUOTED_IDENTIFIER is OFF, identifiers cannot be quoted and must follow all Transact-SQL rules for identifiers. Literals can be delimited by either single or double quotation marks.

When SET QUOTED_IDENTIFIER is ON, all strings delimited by double quotation marks are interpreted as object identifiers. Therefore, quoted identifiers do not have to follow the Transact-SQL rules for identifiers. They can be reserved keywords and can include characters not usually allowed in Transact-SQL identifiers. Double quotation marks cannot be used to delimit literal string expressions, single quotation marks must be used to enclose literal strings. If a single quotation mark (‘) is part of the literal string, it can be represented by two single quotation marks (“). SET QUOTED_IDENTIFIER must be ON when reserved keywords are used for object names in the database.

When SET QUOTED_IDENTIFIER is OFF (default), literal strings in expressions can be delimited by single or double quotation marks. If a literal string is delimited by double quotation marks, the string can contain embedded single quotation marks, such as apostrophes.

The SQL Server ODBC driver and OLE DB Provider for SQL Server automatically SET QUOTED_IDENTIFIER to ON when connecting. This can be configured in ODBC data sources, in ODBC connection attributes, or OLE DB connection properties. SET QUOTED_IDENTIFIER defaults to OFF for connections from DB-Library applications.

When a stored procedure is created, the SET QUOTED_IDENTIFIER and SET ANSI_NULLS settings are captured and used for subsequent invocations of that stored procedure.

When executed inside a stored procedure, the setting of SET QUOTED_IDENTIFIER is not changed.

When SET ANSI_DEFAULTS is ON, SET QUOTED_IDENTIFIER is enabled.

SET QUOTED_IDENTIFIER also corresponds to the quoted identifier setting of sp_dboption. If SET QUOTED_IDENTIFIER is OFF, then SQL Server uses the quoted identifier setting of sp_dboption. For more information about database settings, see sp_dboption.

SET QUOTED_IDENTIFIER is set at parse time. Setting at parse time means that if the SET statement is present in the batch or stored procedure, it takes effect, regardless of whether code execution actually reaches that point; and the SET statement takes effect before any statements are executed.

Permissions

SET QUOTED_IDENTIFIER permissions default to all users.

Examples
A. Quoted identifier setting and reserved word object names

This example shows that the SET QUOTED_IDENTIFIER setting must be ON, and the keywords in table names must be in double quotation marks to create and use objects with reserved keyword names.

SET QUOTED_IDENTIFIER OFF

GO

-- Attempt to create a table with a reserved keyword as a name

-- should fail.

CREATE TABLE "select" ("identity" int IDENTITY, "order" int)

GO

SET QUOTED_IDENTIFIER ON

GO

-- Will succeed.

CREATE TABLE "select" ("identity" int IDENTITY, "order" int)

GO

SELECT "identity","order"

FROM "select"

ORDER BY "order"

GO

DROP TABLE "SELECT"

GO

SET QUOTED_IDENTIFIER OFF

GO

B. Quoted identifier setting and the interpretation of single and double quotes

This example shows how single and double quotation marks are used in string expressions with SET QUOTED_IDENTIFIER set to ON and OFF.

SET QUOTED_IDENTIFIER OFF

GO

USE pubs

IF EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS

        WHERE TABLE_NAME = 'Test')

    DROP TABLE Test

GO

USE pubs

CREATE TABLE Test ( Id int, String varchar (30) )

GO

-- Literal strings can be in single or double quotation marks.

INSERT INTO Test VALUES (1,"'Text in single quotes'")

INSERT INTO Test VALUES (2,'''Text in single quotes''')

INSERT INTO Test VALUES (3,'Text with 2 '''' single quotes')

INSERT INTO Test VALUES (4,'"Text in double quotes"')

INSERT INTO Test VALUES (5,"""Text in double quotes""")

INSERT INTO Test VALUES (6,"Text with 2 """" double quotes")

GO

SET QUOTED_IDENTIFIER ON

GO

-- Strings inside double quotation marks are now treated

-- as object names, so they cannot be used for literals.

INSERT INTO "Test" VALUES (7,'Text with a single '' quote')

GO

-- Object identifiers do not have to be in double quotation marks

-- if they are not reserved keywords.

SELECT *

FROM Test

GO

DROP TABLE Test

GO

SET QUOTED_IDENTIFIER OFF

GO

Here is the result set:

Id          String

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

1           'Text in single quotes'

2           'Text in single quotes'

3           Text with 2 '' single quotes

4           "Text in double quotes"

5           "Text in double quotes"

6           Text with 2 "" double quotes

7           Text with a single ' quote

See Also
CREATE DATABASE | Data Types
CREATE DEFAULT | EXECUTE
CREATE PROCEDURE | SELECT
CREATE RULE | sp_rename
CREATE TABLE | SET ANSI_DEFAULTS
CREATE TRIGGER | SET
CREATE VIEW |


SET REMOTE_PROC_TRANSACTIONS

Specifies that when a local transaction is active, executing a remote stored procedure starts a Transact-SQL distributed transaction managed by the Microsoft Distributed Transaction Manager (MS DTC).

Syntax

SET REMOTE_PROC_TRANSACTIONS {ON | OFF}

Arguments
ON | OFF
When ON, a Transact-SQL distributed transaction is started when a remote stored procedure is executed from a local transaction. When OFF, calling a remote stored procedures from a local transaction does not start a Transact-SQL distributed transaction.
Remarks

When REMOTE_PROC_TRANSACTIONS is ON, calling a remote stored procedure starts a distributed transaction and enlists the transaction with MS DTC. The server making the remote stored procedure call is the transaction originator and controls the completion of the transaction. When a subsequent COMMIT TRANSACTION or ROLLBACK TRANSACTION statement is issued for the connection, the controlling server requests that MS DTC manage the completion of the distributed transaction across the servers involved.

After a Transact-SQL distributed transaction has been started, remote stored procedure calls can be made to other remote servers. The remote servers are all enlisted in the Transact-SQL distributed transaction and MS DTC ensures that the transaction is completed against each server.

REMOTE_PROC_TRANSACTIONS is a connection-level setting that can be used to override the server-level sp_configure remote proc trans option.

When REMOTE_PROC_TRANSACTIONS is set OFF, remote stored procedure calls are not made part of a local transaction. The modifications made by the remote stored procedure are committed or rolled back at the time the stored procedure completes. Subsequent COMMIT TRANSACTION or ROLLBACK TRANSACTION statements issued by the connection that called the remote stored procedure have no effect on the processing done by the procedure.

The REMOTE_PROC_TRANSACTIONS option is a compatibility option that affects only remote stored procedure calls made to remote servers defined using sp_addserver. The option does not apply to distributed queries that execute a stored procedure on a linked server defined using sp_addlinkedserver.

The setting of SET REMOTE_PROC_TRANSACTIONS is set at execute or run time and not at parse time.

Permissions

SET REMOTE_PROC_TRANSACTIONS permissions default to all users.

See Also
BEGIN DISTRIBUTED TRANSACTION SET


SET ROWCOUNT

Causes Microsoft® SQL Server™ to stop processing the query after the specified number of rows are returned.

Syntax

SET ROWCOUNT {number | @number_var}

Arguments
number | @number_var
Is the number (an integer) of rows to be processed before stopping the given query.
Remarks

It is recommended that DELETE, INSERT, and UPDATE statements currently using SET ROWCOUNT be rewritten to use the TOP syntax. For more information, see DELETE, INSERT, or UPDATE.

To turn this option off (so that all rows are returned), specify SET ROWCOUNT 0.

Note Setting the SET ROWCOUNT option causes most Transact-SQL statements to stop processing when they have each affected by the specified number of rows. This includes triggers and data modification statements such as INSERT, UPDATE, and DELETE. The ROWCOUNT option has no effect on dynamic cursors, but it limits the rowset of keyset and insensitive cursors. This option should be used with caution and primarily with the SELECT statement.

SET ROWCOUNT overrides the SELECT statement TOP keyword if the rowcount is the smaller value.

The setting of SET ROWCOUNT is set at execute or run time and not at parse time.

Permissions

SET ROWCOUNT permissions default to all users.

Examples

SET ROWCOUNT stops processing after the specified number of rows. In this example, note that x rows meet the criteria of advances less than or equal to $5,000; however, from the number of rows returned by the update, you can see that not all rows were processed. ROWCOUNT affects all Transact-SQL statements.

USE pubs

GO

SELECT count(*) AS Cnt

FROM titles

WHERE advance >= 5000

GO

Here is the result set:

Cnt
-----------
11

(1 row(s) affected)

Now, SET ROWCOUNT to 4 and update all rows with an advance of $5,000 or more.

-- SET ROWCOUNT to 4.

SET ROWCOUNT 4

GO

UPDATE titles

SET advance = 5000

WHERE advance >= 5000

GO

Here is the result set:

The command(s) completed successfully.

See Also
DELETE | UPDATE
INSERT | SET


SET SHOWPLAN_ALL

Causes Microsoft® SQL Server™ not to execute Transact-SQL statements. Instead, SQL Server returns detailed information about how the statements are executed and estimates of the resource requirements for the statements.

Syntax

SET SHOWPLAN_ALL {ON | OFF}

Remarks

The setting of SET SHOWPLAN_ALL is set at execute or run time and not at parse time.

When SET SHOWPLAN_ALL is ON, SQL Server returns execution information for each statement without executing it and Transact-SQL statements are not executed. After this option is set ON, is all subsequent Transact-SQL statements are returned until the option is set OFF. For example, if a CREATE TABLE statement is executed while SET SHOWPLAN_ALL is ON, SQL Server returns an error message from a subsequent SELECT statement involving that same table; the specified table does not exist. Therefore, subsequent references to this table fail. When SET SHOWPLAN_ALL is OFF, SQL Server executes the statements without generating a report.

SET SHOWPLAN_ALL is intended to be used by applications written to handle its output. Use SET SHOWPLAN_TEXT to return readable output for Microsoft MS-DOS® applications, such as the osql utility.

SET SHOWPLAN_TEXT and SET SHOWPLAN_ALL cannot be specified inside a stored procedure. They must be the only statements in a batch.

SET SHOWPLAN_ALL returns information as a set of rows that form a hierarchical tree representing the steps taken by the SQL Server query processor as it executes each statement. Each statement reflected in the output contains a single row with the text of the statement, followed by several rows with the details of the execution steps. The output contains these columns.

Column name | Description
StmtText | For rows which are not of type PLAN_ROW, this column contains the text of the Transact-SQL statement. For rows of type PLAN_ROW, this column contains a description of the operation. This column contains the physical operator and may optionally also contain the logical operator. This column may also be followed by a description which is determined by the physical operator.
StmtId | Number of the statement in the current batch.
NodeId | ID of the node in the current query.
Parent | Node ID of the parent step.
PhysicalOp | Physical implementation algorithm for the node. For rows of type PLAN_ROWS only.
LogicalOp | Relational algebraic operator this node represents. For rows of type PLAN_ROWS only.
Argument | Provides supplemental information about the operation being performed. The contents of this column depend on the physical operator.
DefinedValues | Contains a comma-separated list of values introduced by this operator. These values may be computed expressions which were present in the current query (for example, in the SELECT list or WHERE clause), or internal values introduced by the query processor in order to process this query. These defined values may then be referenced elsewhere within this query. For rows of type PLAN_ROWS only.
EstimateRows | Estimated number of rows output by this operator. For rows of type PLAN_ROWS only.
EstimateIO | Estimated I/O cost for this operator. For rows of type PLAN_ROWS only.
EstimateCPU | Estimated CPU cost for this operator. For rows of type PLAN_ROWS only.
AvgRowSize | Estimated average row size (in bytes) of the row being passed through this operator.
TotalSubtreeCost | Estimated (cumulative) cost of this operation and all child operations.
OutputList | Contains a comma-separated list of columns being projected by the current operation.
Warnings | Contains a comma-separated list of warning messages relating to the current operation. Warning messages may include the string “NO STATS:()” with a list of columns. This warning message means that the query optimizer attempted to make a decision based on the statistics for this column, but none were available. Consequently, the query optimizer had to make a guess, which may have resulted in the selection of an inefficient query plan. For more information about creating or updating column statistics (which help the query optimizer choose a more efficient query plan), see UPDATE STATISTICS. This column may optionally include the string “MISSING JOIN PREDICATE” which means that a join (involving tables) is taking place without a join predicate. Accidentally dropping a join predicate may result in a query which takes much longer to run than expected, and returns a huge result set. If this warning is present, verify that the absence of a join predicate is intentional.
Type | Node type. For the parent node of each query, this is the Transact-SQL statement type (for example, SELECT, INSERT, EXECUTE, and so on). For subnodes representing execution plans, the type is PLAN_ROW.
Parallel | 0 = Operator is not running in parallel. 1 = Operator is running in parallel.
EstimateExecutions | Estimated number of times this operator will be executed while running the current query.

Permissions

SET SHOWPLAN_ALL permissions default to all users.

Examples

The two statements that follow use the SET SHOWPLAN_ALL settings to show how SQL Server analyzes and optimizes the use of indexes in queries.

The first query uses the Equals comparison operator (=) in the WHERE clause on an indexed column. This results in the Clustered Index Seek value in the LogicalOp column and the name of the index in the Argument column.

The second query uses the LIKE operator in the WHERE clause. This forces SQL Server to use a clustered index scan and find the data meeting the WHERE clause condition. This results in the Clustered Index Scan value in the LogicalOp column with the name of the index in the Argument column, and the Filter value in the LogicalOp column with the WHERE clause condition in the Argument column.

The values in the EstimateRows and the TotalSubtreeCost columns are smaller for the first indexed query, indicating that it is processed much faster and uses less resources than the nonindexed query.

USE pubs

GO

SET SHOWPLAN_ALL ON

GO

-- First query.

SELECT au_id

FROM authors

WHERE au_id = '409-56-7008'

GO

-- Second query.

SELECT city

FROM authors

WHERE city LIKE 'San%'

GO

SET SHOWPLAN_ALL OFF

GO

See Also
SET SHOWPLAN_TEXT SET


SET SHOWPLAN_TEXT

Causes Microsoft® SQL Server™ not to execute Transact-SQL statements. Instead, SQL Server returns detailed information about how the statements are executed.

Syntax

SET SHOWPLAN_TEXT {ON | OFF}

Remarks

The setting of SET SHOWPLAN_TEXT is set at execute or run time and not at parse time.

When SET SHOWPLAN_TEXT is ON, SQL Server returns execution information for each Transact-SQL statement without executing it. After this option is set ON, information about all subsequent Transact-SQL statements is returned until the option is set OFF. For example, if a CREATE TABLE statement is executed while SET SHOWPLAN_TEXT is ON, SQL Server returns an error message from a subsequent SELECT statement involving that same table; the specified table does not exist. Therefore, subsequent references to this table fail. When SET SHOWPLAN_TEXT is OFF, SQL Server executes statements without generating a report.

SET SHOWPLAN_TEXT is intended to return readable output for Microsoft MS-DOS® applications such as the osql utility. SET SHOWPLAN_ALL returns more detailed output intended to be used with programs designed to handle its output.

SET SHOWPLAN_TEXT and SET SHOWPLAN_ALL cannot be specified in a stored procedure. They must be the only statements in a batch.

SET SHOWPLAN_TEXT returns information as a set of rows that form a hierarchical tree representing the steps taken by the SQL Server query processor as it executes each statement. Each statement reflected in the output contains a single row with the text of the statement, followed by several rows with the details of the execution steps. The output contains this column.

Column name | Description
StmtText | For rows which are not of type PLAN_ROW, this column contains the text of the Transact-SQL statement. For rows of type PLAN_ROW, this column contains a description of the operation. This column contains the physical operator and may optionally also contain the logical operator. This column may also be followed by a description which is determined by the physical operator. For more information about physical operators, see the Argument column in SET SHOWPLAN_ALL.

Permissions

SET SHOWPLAN_TEXT permissions default to all users.

Examples

This example shows how indexes are used by SQL Server as it processes the statements.

Here is the query using an index:

SET SHOWPLAN_TEXT ON

GO

USE pubs

SELECT *

FROM roysched

WHERE title_id = 'PS1372'

GO

SET SHOWPLAN_TEXT OFF

GO

Here is the result set:

StmtText

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

USE pubs

SELECT *

FROM roysched

WHERE title_id = 'PS1372'

(2 row(s) affected)

StmtText

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

  |--Bookmark Lookup(BOOKMARK:([Bmk1000]), OBJECT:([pubs].[dbo].[roysched]))

       |--Index Seek(OBJECT:([pubs].[dbo].[roysched].[titleidind]), SEEK:([roysched].[title_id]='PS1372') ORDERED)

(2 row(s) affected)

Here is the query not using an index:

SET SHOWPLAN_TEXT ON

GO

USE pubs

SELECT *

FROM roysched

WHERE lorange < 5000

GO

SET SHOWPLAN_TEXT OFF

GO

Here is the result set:

StmtText

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

USE pubs

SELECT *

FROM roysched

WHERE lorange < 5000

(2 row(s) affected)

StmtText

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

  |--Table Scan(OBJECT:([pubs].[dbo].[roysched]), WHERE:([roysched].[lorange]<5000))

(1 row(s) affected)

See Also
Operators | SET
SET SHOWPLAN_ALL |


SET STATISTICS IO

Causes Microsoft® SQL Server™ to display information regarding the amount of disk activity generated by Transact-SQL statements.

Syntax

SET STATISTICS IO {ON | OFF}

Remarks

When STATISTICS IO is ON, statistical information is displayed. When OFF, the information is not displayed.

After this option is set ON, all subsequent Transact-SQL statements return the statistical information until the option is set to OFF.

There are five output items.

Output item | Meaning
table | Name of the table.
scan count | Number of scans performed.
logical reads | Number of pages read from the data cache.
physical reads | Number of pages read from disk.
read-ahead reads | Number of pages placed into the cache for the query.

The setting of SET STATISTICS IO is set at execute or run time and not at parse time.

Permissions

SET STATISTICS IO permissions default to all users.

See Also
SET SHOWPLAN_ALL | SET
SET STATISTICS TIME |


SET STATISTICS PROFILE

Displays the profile information for a statement. STATISTICS PROFILE works for ad hoc queries, views, triggers, and stored procedures.

Syntax

SET STATISTICS PROFILE {ON | OFF}

Remarks

When STATISTICS PROFILE is ON, each executed query returns its regular result set, followed by an additional result set that shows a profile of the query execution.

The additional result set contains the SHOWPLAN_ALL columns for the query and these additional columns.

Column name | Description
Rows | Actual number of rows produced by each operator.
Reuse | Actual number of times this operator was told to reuse its data.

Permissions

SET STATISTICS PROFILE permissions default to all users.

See Also
SET STATISTICS IO | SET STATISTICS TIME
SET | SET SHOWPLAN_ALL


SET STATISTICS TIME

Displays the number of milliseconds required to parse, compile, and execute each statement.

Syntax

SET STATISTICS TIME {ON | OFF}

Remarks

When SET STATISTICS TIME is ON, the time statistics for a statement are displayed. When OFF, the time statistics are not displayed.

The setting of SET STATISTICS TIME is set at execute or run time and not at parse time.

Microsoft® SQL Server™ is unable to provide accurate statistics in fiber mode, which is activated when you enable the lightweight pooling configuration option.

The cpu column is only updated when a query executes with SET STATISTICS TIME ON. When SET STATISTICS TIME is OFF, a 0 is returned.

ON and OFF settings also affect the CPU column in the Process Info View for Current Activity in SQL Server Enterprise Manager.

Permissions

SET STATISTICS TIME permissions default to all users.

See Also
SET STATISTICS IO SET


SET TEXTSIZE

Specifies the size of text and ntext data returned with a SELECT statement.

Syntax

SET TEXTSIZE {number | @number_var}

Arguments
number | @number_var
Is the size (an integer) of text data, in bytes. The maximum setting for SET TEXTSIZE is 2 GB, specified in bytes. A setting of 0 resets the size to the default (4 KB).
Remarks

Setting SET TEXTSIZE affects the @@TEXTSIZE function.

The DB-Library variable DBTEXTLIMIT also limits the size of text data returned with a SELECT statement. If DBTEXTLIMIT is set to a smaller size than TEXTSIZE, only the amount specified by DBTEXTLIMIT is returned. For more information, see Programming DB-Library for C.

The Microsoft® SQL Server™ ODBC driver and OLE DB Provider for SQL Server automatically SET TEXTSIZE to 2147483647 when connecting.

The setting of SET TEXTSIZE is set at execute or run time and not at parse time.

Permissions

SET TEXTSIZE permissions default to all users.

See Also
Data Types | SET
@@TEXTSIZE |


SET TRANSACTION ISOLATION LEVEL

Controls the default transaction locking behavior for all Microsoft® SQL Server™ SELECT statements issued by a connection.

Syntax

SET TRANSACTION ISOLATION LEVEL
{
READ COMMITTED
| READ UNCOMMITTED
| REPEATABLE READ
| SERIALIZABLE
}

Arguments
READ COMMITTED
Shared locks are held while the data is being read to avoid dirty reads, but the data can be changed before the end of the transaction, resulting in nonrepeatable reads or phantom data. This option is the SQL Server default.
READ UNCOMMITTED
Implements dirty read, or isolation level 0 locking, which means that no shared locks are issued and no exclusive locks are honored. When this option is set, it is possible to read uncommitted or dirty data; values in the data can be changed and rows can appear or disappear in the data set before the end of the transaction. This option has the same effect as setting NOLOCK on all tables in all SELECT statements in a transaction. This is the least restrictive of the four isolation levels.
REPEATABLE READ
Locks are placed on all data that is used in a query, preventing other users from updating the data, but new phantom rows can be inserted into the data set by another user and are included in later reads in the current transaction. Because concurrency is lower than the default isolation level, use this option only when necessary.
SERIALIZABLE
A range lock is placed on the data set preventing other users from updating or inserting rows into the data set until the transaction is complete. This is the most restrictive of the four isolation levels. Because concurrency is lower, use this option only when necessary. This option has the same effect as setting HOLDLOCK on all tables in all SELECT statements in a transaction.
Remarks

Only one of the options can be set at a time, and it remains set for that connection until it is explicitly changed. This becomes the default behavior unless an optimization option is specified at the table level in the FROM clause of your statement.

The setting of SET TRANSACTION ISOLATION LEVEL is set at execute or run time and not at parse time.

Examples

This example sets the TRANSACTION ISOLATION LEVEL for the session. For each Transact-SQL statement that follows, SQL Server holds all of the shared locks until the end of the transaction.

SET TRANSACTION ISOLATION LEVEL REPEATABLE READ

GO

BEGIN TRANSACTION

SELECT * FROM publishers

SELECT * FROM authors

…

COMMIT TRANSACTION

See Also
DBCC USEROPTIONS | SET
SELECT |


SET XACT_ABORT

Specifies whether Microsoft® SQL Server™ automatically rolls back the current transaction if a Transact-SQL statement raises a run time error.

Syntax

SET XACT_ABORT{ON | OFF}

Remarks

When SET XACT_ABORT is ON, if a Transact-SQL statement raises a run time error, the entire transaction is terminated and rolled back. When OFF, only the Transact-SQL statement that raised the error is rolled back and transaction continues processing. Compile errors, such as syntax errors, are not affected by SET XACT_ABORT.

It is recommended that XACT_ABORT be set ON when executing data modification statements against remote tables in an implicit or explicit transaction.

The setting of SET XACT_ABORT is set at execute or run time and not at parse time.

Examples

This example causes a foreign key violation error in a transaction that has other Transact-SQL statements. In the first set of statements, the error is generated, but the other statements execute successfully and the transaction is successfully committed. In the second set of statements, the SET XACT_ABORT setting is turned ON. This causes the statement error to terminate the batch and the transaction is rolled back.

CREATE TABLE t1 (a int PRIMARY KEY)

CREATE TABLE t2 (a int REFERENCES t1(a))

GO

INSERT INTO t1 VALUES (1)

INSERT INTO t1 VALUES (3)

INSERT INTO t1 VALUES (4)

INSERT INTO t1 VALUES (6)

GO

SET XACT_ABORT OFF

GO

BEGIN TRAN

INSERT INTO t2 VALUES (1)

INSERT INTO t2 VALUES (2) /* Foreign key error */

INSERT INTO t2 VALUES (3)

COMMIT TRAN

GO

SET XACT_ABORT ON

GO

BEGIN TRAN

INSERT INTO t2 VALUES (4)

INSERT INTO t2 VALUES (5) /* Foreign key error */

INSERT INTO t2 VALUES (6)

COMMIT TRAN

GO

/* Select shows only keys 1 and 3 added.

   Key 2 insert failed and was rolled back, but

   XACT_ABORT was OFF and rest of transaction

   succeeded.

   Key 5 insert error with XACT_ABORT ON caused

   all of the second transaction to roll back. */

SELECT *

FROM t2

GO

DROP TABLE t2

DROP TABLE t1

GO

See Also
BEGIN TRANSACTION | @@TRANCOUNT
COMMIT TRANSACTION | SET
ROLLBACK TRANSACTION |


SETUSER

Allows a member of the sysadmin fixed server role or db_owner fixed database role to impersonate another user.

Important SETUSER is included in Microsoft® SQL Server™ version 7.0 only for backward compatibility, and is not recommended to be used. SETUSER may not be supported in a future release of SQL Server.

Syntax

SETUSER ['username' [WITH NORESET]]

Arguments
'username'
Is the name of a SQL Server or Microsoft Windows NT® user in the current database that is impersonated. When username is not specified, the original identity of the system administrator or database owner impersonating the user is reestablished.
WITH NORESET
Specifies that subsequent SETUSER statements (with no specified username) do not reset to the system administrator or database owner.
Remarks

SETUSER can be used by members of the sysadmin or db_owner roles to adopt the identity of another user in order to test the permissions of the other user.

Only use SETUSER with SQL Server users. SETUSER cannot fully reflect the permissions of Windows NT users. When SETUSER is used to assume the permissions of a Windows NT user, the permissions of the Windows NT groups that contain the user are not included.

When SETUSER has been used to assume the identity of another user, any objects that are created are owned by the user being impersonated. For example, if the database owner assumes the identity of user Margaret and creates a table called orders, the orders table is owned by Margaret not the system administrator.

SETUSER is not required to create an object owned by another user, because the object can be created with a qualified name that specifies the other user as the owner of the new object. For example, if user Andrew, who is a member of the db_owner database role, creates a table Margaret.customers, user Margaret owns customers, not user Andrew.

SETUSER remains in effect until another SETUSER statement is issued or until the current database is changed with the USE statement.

Permissions

SETUSER permissions default to members of the sysadmin fixed server role or db_owner fixed database role, and are not transferable.

Examples
A. Use SETUSER

This example shows how the database owner can adopt the identity of another user. User mary has created a table called computer_types. Using SETUSER, the database owner impersonates mary to grant user joe access to the computer_types table.

SETUSER 'mary'

go

GRANT SELECT ON computer_types TO joe

go

SETUSER

B. Use the NORESET option

This example shows how a database owner must create some objects and then test their usability with minimal permissions. For simplicity, the database owner wants to maintain only the permission granted to mary for the entire session.

SETUSER 'mary' WITH NORESET

go

CREATE TABLE computer_types2

.

.

.

GRANT …

go

SETUSER        /* This statement has no effect. */

Note If SETUSER WITH NORESET is used, the database owner or system administrator must log off and then log on again to reestablish his or her own rights.

See Also
DENY | REVOKE
GRANT | USE


SHUTDOWN

Immediately stops Microsoft® SQL Server™.

Syntax

SHUTDOWN [WITH NOWAIT]

Arguments
WITH NOWAIT
Shuts down SQL Server immediately, without performing checkpoints in every database. SQL Server exits after attempting to terminate all user processes, and a rollback operation occurs for each active transaction.
Remarks

Unless members of the sysadmin fixed server role specify the WITH NOWAIT option, SHUTDOWN tries to shut down SQL Server in an orderly fashion by:

  1. Disabling logins (except for members of the sysadmin fixed server role). To see a listing of all current users, execute sp_who.
  2. Waiting for currently executing Transact-SQL statements or stored procedures to finish. To see a listing of all active processes and locks, execute sp_lock and sp_who.
  3. Performing a checkpoint in every database.

Using the SHUTDOWN statement minimizes the amount of automatic recovery work needed when members of the sysadmin fixed server role restart SQL Server.

These tools and methods can also be used to stop SQL Server. Each of these performs a checkpoint in all databases. All committed data from data cache is flushed, and then the server is stopped:

  • By using SQL Server Enterprise Manager.
  • By using net stop mssqlserver from a command prompt.
  • By using Services in Control Panel.
  • By using SQL Server Service Manager.

If sqlservr.exe was started from the command-prompt, pressing CTRL+C shuts down SQL Server. However, pressing CTRL+C does not perform a checkpoint.

Note The SQL Server Enterprise Manager, net stop, Control Panel, and SQL Server Service Manager methods of stopping SQL Server produce the identical service control message of SERVICE_CONTROL_STOP to SQL Server.

Permissions

SHUTDOWN permissions default to members of the sysadmin fixed server role, and are not transferable.

See Also
CHECKPOINT | sp_who
sp_lock |


SIGN

Returns the positive (+1), zero (0), or negative (-1) sign of the given expression.

Syntax

SIGN(numeric_expression)

Arguments
numeric_expression
Is an expression of the exact numeric or approximate numeric data type category, except for the bit data type.
Return Types

float

Examples

This example returns the SIGN values of numbers from -1 to 1.

DECLARE @value real

SET @value = -1

WHILE @value < 2

    BEGIN

        SELECT SIGN(@value)

        SET NOCOUNT ON

        SELECT @value = @value + 1

        SET NOCOUNT OFF

    END

SET NOCOUNT OFF

GO

Here is the result set:

(1 row(s) affected)

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

-1.0

(1 row(s) affected)

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

0.0

(1 row(s) affected)

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

1.0

(1 row(s) affected)

See Also

Mathematical Functions


SIN

Returns the trigonometric sine of the given angle (in radians) in an approximate numeric (float) expression.

Syntax

SIN(float_expression)

Arguments
float_expression
Is an expression of type float.
Return Types

float

Examples

This example calculates the SIN for a given angle.

DECLARE @angle float

SET @angle = 45.175643

SELECT 'The SIN of the angle is: ' + CONVERT(varchar,SIN(@angle))

GO

Here is the result set:

The SIN of the angle is: 0.929607

(1 row(s) affected)

See Also

Mathematical Functions


smalldatetime

For information about the smalldatetime data type, see datetime and smalldatetime.

See Also
Data Types


smallint

For information about the smallint data type, see int, smallint, and tinyint.

See Also
Data Types


smallmoney

For information about the smallmoney data type, see money and smallmoney.

See Also
Data Types


SOME | ANY

Compares a scalar value with a single-column set of values.

Syntax

scalar_expression { = | <> | != | > | >= | !> | < | <= | !< }
{SOME | ANY} (subquery)

Arguments
scalar_expression
Is any valid Microsoft® SQL Server™ expression.
{ = | <> | != | > | >= | !> | < | <= | !< }
Is any valid comparison operator.
SOME | ANY
Specifies that a comparison should be made.
subquery
Is a subquery that has a result set of one column. The data type of the column returned must be the same data type as scalar_expression.
Result Types

Boolean

Result Value

SOME or ANY returns TRUE when the comparison specified is TRUE for ANY pair (scalar_expression, x) where x is a value in the single-column set. Otherwise, returns FALSE.

See Also
CASE Operators (Logical Operators)


SOUNDEX

Returns a four-character (SOUNDEX) code to evaluate the similarity of two strings.

Syntax

SOUNDEX(character_expression)

Arguments
character_expression
Is an alphanumeric expression of character data. character_expression can be a constant, variable, or column.
Return Types

char

Remarks

SOUNDEX converts an alpha string to a four-character code to find similar-sounding words or names. The first character of the code is the first character of character_expression and the second through fourth characters of the code are numbers. Vowels in character_expression are ignored unless they are the first letter of the string. String functions can be nested.

Examples

This example shows the SOUNDEX function and the related DIFFERENCE function. In the first example, the standard SOUNDEX values are returned for all consonants. Returning the SOUNDEX for Smith and Smythe returns the same SOUNDEX result because all vowels, the letter y, doubled letters, and the letter h, are not included.

-- Using SOUNDEX

SELECT SOUNDEX ('Smith'), SOUNDEX ('Smythe')

Here is the result set:

----- -----

S530  S530

(1 row(s) affected)

The DIFFERENCE function compares the difference of the SOUNDEX pattern results. The first example shows two strings that differ only in vowels. The difference returned is 4 (lowest possible difference).

-- Using DIFFERENCE

SELECT DIFFERENCE('Smithers', 'Smythers')

GO

Here is the result set:

-----------

4

(1 row(s) affected)

In this example, the strings differ in consonants, so the difference returned is 2 (higher difference).

SELECT DIFFERENCE('Anothers', 'Brothers')

GO

Here is the result set:

-----------

2

(1 row(s) affected)

See Also
String Functions


SPACE

Returns a string of repeated spaces.

Syntax

SPACE(integer_expression)

Arguments
integer_expression
Is a positive integer that indicates the number of spaces. If integer_expression is negative, a null string is returned.
Return Types

char

Remarks

To include spaces in Unicode data, use REPLICATE instead of SPACE.

Examples

This example trims the authors’ last names and concatenates a comma, two spaces, and the authors’ first names.

USE pubs

GO

SELECT RTRIM(au_lname) + ',' + SPACE(2) +  LTRIM(au_fname)

FROM authors

ORDER BY au_lname, au_fname

GO

Here is the result set:

Name

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

Bennet,  Abraham

Blotchet-Halls,  Reginald

Carson,  Cheryl

DeFrance,  Michel

del Castillo,  Innes

Dull,  Ann

Green,  Marjorie

Greene,  Morningstar

Gringlesby,  Burt

Hunter,  Sheryl

Karsen,  Livia

Locksley,  Charlene

MacFeather,  Stearns

McBadden,  Heather

O'Leary,  Michael

Panteley,  Sylvia

Ringer,  Albert

Ringer,  Anne

Smith,  Meander

Straight,  Dean

Stringer,  Dirk

White,  Olivier

Yokomoto,  Akiko

(23 row(s) affected)

See Also
String Functions


SQUARE

Returns the square of the given expression.

Syntax

SQUARE(float_expression)

Arguments
float_expression
Is an expression of type float.
Return Types

float

Examples

This example returns the volume of a cylinder having a radius of 1 inch and a height of 5 inches.

DECLARE @h float, @r float

SET @h = 5

SET @r = 1

SELECT PI()* SQUARE(@r)* @h AS 'Cyl Vol'

Here is the result:

Cyl Vol

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

15.707963267948966

See Also
Mathematical Functions


SQRT

Returns the square root of the given expression.

Syntax

SQRT(float_expression)

Arguments
float_expression
Is an expression of type float.
Return Types

float

Examples

This example returns the square root of numbers between 1.00 and 10.00.

DECLARE @myvalue float

SET @myvalue = 1.00

WHILE @myvalue < 10.00

    BEGIN

        SELECT SQRT(@myvalue)

        SELECT @myvalue = @myvalue + 1

    END

GO

Here is the result set:

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

1.0

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

1.4142135623731

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

1.73205080756888

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

2.0

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

2.23606797749979

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

2.44948974278318

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

2.64575131106459

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

2.82842712474619

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

3.0

See Also

Mathematical Functions


STATS_DATE

Returns the date that the statistics for the specified index were last updated.

Syntax

STATS_DATE(table_id, index_id)

Arguments
table_id
Is the ID of the table used.
index_id
Is the ID of the index used.
Return Types

datetime

Remarks

System functions can be used in the select list, in the WHERE clause, and anywhere an expression is allowed.

Examples

This example returns the date of the last time that the statistics were updated for the specified object.

USE master

GO

SELECT 'Index Name' = i.name,

    'Statistics Date' = STATS_DATE(i.id, i.indid)

FROM sysobjects o, sysindexes i

WHERE o.name = 'employee' AND o.id = i.id

GO

See Also
WHERE System Functions


STDEV

Returns the statistical standard deviation of all values in the given expression.

Syntax

STDEV(expression)

Arguments
expression

Is a numeric expression. Aggregate functions and subqueries are not permitted. expression is an expression of the exact numeric or approximate numeric data type category, except for the bit data type.

Return Types

float

Remarks

If STDEV is used on all items in a SELECT statement, each value in the result set is included in the calculation. STDEV can be used with numeric columns only. Null values are ignored.

Examples

This example returns the standard deviation for all royalty payments in the titles table.

USE pubs

SELECT STDEV(royalty)

FROM titles

See Also

Aggregate Functions


STDEVP

Returns the statistical standard deviation for the population for all values in the given expression.

Syntax

STDEVP(expression)

Arguments
expression
Is a numeric expression. Aggregate functions and subqueries are not permitted. expression is an expression of the exact numeric or approximate numeric data type category, except for the bit data type.
Return Types

float

Remarks

If STDEVP is used on all items in a SELECT statement, each value in the result set is included in the calculation. STDEVP can be used with numeric columns only. Null values are ignored.

Examples

This example returns the standard deviation for the population for all royalty values in the titles table.

USE pubs

SELECT STDEVP(royalty)

FROM titles

See Also

Aggregate Functions


STR

Returns character data converted from numeric data.

Syntax

STR(float_expression[, length[, decimal]])

Arguments
float_expression
Is an expression of approximate numeric (float) data type with a decimal point. Do not use a function or subquery as the float_expression in the STR function.
length
Is the total length, including decimal point, sign, digits, and spaces. The default is 10.
decimal
Is the number of places to the right of the decimal point.
Return Types

char

Remarks

If supplied, the values for length and decimal parameters to STR should be positive. The number is rounded to an integer by default or if the decimal parameter is 0. The specified length should be greater than or equal to the part of the number before the decimal point plus the number’s sign (if any). A short float_expression is right-justified in the specified length, and a long float_expression is truncated to the specified number of decimal places. For example, STR(12,10) yields the result of 12, which is right-justified in the result set. However, STR(1223, 2) truncates the result set to **. String functions can be nested.

Note To convert to Unicode data, use STR inside a CONVERT or CAST conversion function.

Examples
A. Use STR

This example converts an expression consisting of five digits and a decimal point to a six-position character string. The fractional part of the number is rounded to one decimal place.

SELECT STR(123.45, 6, 1)

GO

Here is the result set:

------

 123.5

(1 row(s) affected)

When the expression exceeds the specified length, the string returns ** for the specified length.

SELECT STR(123.45, 2, 2)

GO

Here is the result set:

--

**

(1 row(s) affected)

Even when numeric data is nested within STR, the result is character data with the specified format.

SELECT STR (FLOOR (123.45), 8, 3)

GO

Here is the result set:

--------

 123.000

(1 row(s) affected)

B. Use the STR and CONVERT functions

This example compares the results of STR and CONVERT.

SELECT STR(3.147) AS 'STR',

       STR(3.147, 5, 2) AS '2 decimals',

       STR(3.147, 5, 3) AS '3 decimals'

GO

Here is the result set:

STR        2 decimals 3 decimals

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

         3  3.15      3.147

(1 row(s) affected)

-- Use CONVERT.

SELECT CONVERT(char(1), 3.147) AS 'CHAR(1)',

       CONVERT(char(3), 3.147) AS 'CHAR(3)',

       CONVERT(char(5), 3.147) AS 'CHAR(5)'

GO

Here is the result set:

CHAR(1) CHAR(3) CHAR(5)

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

(null)  (null)  3.147

(1 row(s) affected)

See Also
String Functions


STUFF

Deletes a specified length of characters and inserts another set of characters at a specified starting point.

Syntax

STUFF(character_expression, start, length, character_expression)

Arguments
character_expression
Is an expression of character data. character_expression can be a constant, variable, or column of either character or binary data.
start
Is an integer value that specifies the location to begin deletion and insertion. If start or length is negative, a null string is returned. If start is longer than the first character_expression, a null string is returned.
length
Is an integer that specifies the number of characters to delete. If length is longer than the first character_expression, deletion occurs up to the last character in the last character_expression.
Return Types

Returns character data if character_expression is one of the supported character data types. Returns binary data if character_expression is one of the supported binary data types.

Remarks

String functions can be nested.

Examples

This example returns a character string created by deleting three characters from the first string (abcdef) starting at position 2 (at b) and inserting the second string at the deletion point.

SELECT STUFF('abcdef', 2, 3, 'ijklmn')

GO

Here is the result set:

---------

aijklmnef

(1 row(s) affected)

See Also
Data Types String Functions


SUBSTRING

Returns part of a character, binary, text, or image expression. For more information about the valid Microsoft® SQL Server™ data types that can be used with this function, see Data Types.

Syntax

SUBSTRING(expression, start, length)

Arguments
expression
Is a character string, binary string, text, image, a column, or an expression that includes a column. Do not use expressions that include aggregate functions.
start
Is an integer that specifies where the substring begins.
length
Is an integer that specifies the length of the substring (the number of characters or bytes to return).

Note Because start and length specify the number of bytes when SUBSTRING is used on text data, DBCS data, such as Kanji, may result in split characters at the beginning or end of the result. This behavior is consistent with the way in which READTEXT handles DBCS; however, because of the occasional strange result, it is advisable to use ntext instead of text for DBCS characters.

Return Types

Returns character data if expression is one of the supported character data types. Returns binary data if expression is one of the supported binary data types.

The returned string is the same type as the given expression with the exceptions shown in the table.

Given expression | Return type
text | varchar
image | varbinary
ntext | nvarchar

Remarks

Offsets (start and length) using the ntext, char, or varchar data types must be specified in number of characters. Offsets using the text, image, binary, or varbinary data types must be specified in number of bytes.

Note Compatibility levels can affect return values. For more information about compatibility levels, see sp_dbcmptlevel.

Examples
A. Use SUBSTRING with a character string

This example shows how to return only a portion of a character string. From the authors table, this query returns the last name in one column with only the first initial in the second column.

USE pubs

SELECT au_lname, SUBSTRING(au_fname, 1, 1)

FROM authors

ORDER BY au_lname

Here is the result set:

au_lname

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

Bennet                                   A

Blotchet-Halls                           R

Carson                                   C

DeFrance                                 M

del Castillo                             I

…

Yokomoto                                 A

(23 row(s) affected)

Here is how to display the second, third, and fourth characters of the string constant abcdef.

SELECT x = SUBSTRING('abcdef', 2, 3)

Here is the result set:

x

----------

bcd

(1 row(s) affected)

B. Use SUBSTRING with text, ntext, and image data

This example shows how to return the first 200 characters from each of a text and image data column in the publishers table of the pubs database. text data is returned as varchar, and image data is returned as varbinary.

USE pubs

SELECT pub_id, SUBSTRING(logo, 1, 10) AS logo,

    SUBSTRING(pr_info, 1, 10) AS pr_info

FROM pub_info

WHERE pub_id = '1756'

Here is the result set:

pub_id logo                   pr_info

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

1756   0x474946383961E3002500 This is sa

(1 row(s) affected)

This example shows the effect of SUBSTRING on both text and ntext data. First, this example creates a new table in the pubs database named npr_info. Second, the example creates the pr_info column in the npr_info table from the first 80 characters of the pub_info.pr_info column and adds an ü as the first character. Lastly, an INNER JOIN retrieves all publisher identification numbers, and the SUBSTRING of both the text and ntext publisher information columns.

IF EXISTS (SELECT table_name FROM INFORMATION_SCHEMA.TABLES

        WHERE table_name = 'npub_info')

    DROP TABLE npub_info

GO

-- Create npub_info table in pubs database. Borrowed from instpubs.sql.

USE pubs

GO

CREATE TABLE npub_info

(

 pub_id         char(4)           NOT NULL

         REFERENCES publishers(pub_id)

         CONSTRAINT UPKCL_npubinfo PRIMARY KEY CLUSTERED,

 pr_info        ntext             NULL

)

GO

-- Fill the pr_info column in npub_info with international data.

RAISERROR('Now at the inserts to pub_info…',0,1)

GO

INSERT npub_info VALUES('0736', N'üThis is sample text data for New Moon Books, publisher 0736 in the pubs database')

INSERT npub_info values('0877', N'üThis is sample text data for Binnet & Hardley, publisher 0877 in the pubs databa')

INSERT npub_info values('1389', N'üThis is sample text data for Algodata Infosystems, publisher 1389 in the pubs da')

INSERT npub_info values('9952', N'üThis is sample text data for Scootney Books, publisher 9952 in the pubs database')

INSERT npub_info values('1622', N'üThis is sample text data for Five Lakes Publishing, publisher 1622 in the pubs d')

INSERT npub_info values('1756', N'üThis is sample text data for Ramona Publishers, publisher 1756 in the pubs datab')

INSERT npub_info values('9901', N'üThis is sample text data for GGG&G, publisher 9901 in the pubs database. GGG&G i')

INSERT npub_info values('9999', N'üThis is sample text data for Lucerne Publishing, publisher 9999 in the pubs data')

GO

-- Join between npub_info and pub_info on pub_id.

SELECT pr.pub_id, SUBSTRING(pr.pr_info, 1, 35) AS pr_info,

    SUBSTRING(npr.pr_info, 1, 35) AS npr_info

FROM pub_info pr INNER JOIN npub_info npr

    ON pr.pub_id = npr.pub_id

ORDER BY pr.pub_id ASC

See Also
String Functions


SUM

Returns the sum of all the values, or only the DISTINCT values, in the expression. SUM can be used with numeric columns only. Null values are ignored.

Syntax

SUM([ALL | DISTINCT] expression)

Arguments
ALL
Applies the aggregate function to all values. ALL is the default.
DISTINCT
Specifies that SUM return the sum of unique values.
expression
Is a constant, column, or function, and any combination of arithmetic, bitwise, and string operators. expression is an expression of the exact numeric or approximate numeric data type category, except for the bit data type. Aggregate functions and subqueries are not permitted.
Return Types

Returns the summation of all expression values in the most precise expression data type.

Expression result | Return type
integer category | int
decimal category (p, s) | decimal(38, s)
money and smallmoney category | money
float and real category | float

Important Distinct aggregates, for example AVG(DISTINCT column_name), COUNT(DISTINCT column_name), MAX(DISTINCT column_name), MIN(DISTINCT column_name), and SUM(DISTINCT column_name), are not supported when using CUBE or ROLLUP. If used, Microsoft® SQL Server™ returns an error message and cancels the query.

Examples
A. Use SUM for aggregates and row aggregates

These examples show the differences between aggregate functions and row aggregate functions. The first shows aggregate functions giving summary data only, and the second shows row aggregate functions giving detail and summary data.

USE pubs

GO

-- Aggregate functions

SELECT type, SUM(price), SUM(advance)

FROM titles

WHERE type LIKE '%cook'

GROUP BY type

ORDER BY type

GO

Here is the result set:

type

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

mod_cook     22.98                      15,000.00

trad_cook    47.89                      19,000.00

(2 row(s) affected)

USE pubs

GO

-- Row aggregates

SELECT type, price, advance

FROM titles

WHERE type LIKE '%cook'

ORDER BY type

COMPUTE SUM(price), SUM(advance) BY type

Here is the result set:

type         price                      advance

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

mod_cook     19.99                      0.00

mod_cook     2.99                       15,000.00

             sum

             ==========================

             22.98

                                        sum

                                        ==========================

                                        15,000.00

type         price                      advance

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

trad_cook    20.95                      7,000.00

trad_cook    11.95                      4,000.00

trad_cook    14.99                      8,000.00

             sum

             ==========================

             47.89

                                        sum

                                        ==========================

                                        19,000.00

(7 row(s) affected)

B. Calculate group totals with more than one column

This example calculates the sum of the prices and advances for each type of book.

USE pubs

GO

SELECT type, SUM(price), SUM(advance)

FROM titles

GROUP BY type

ORDER BY type

GO

Here is the result set:

type

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

business     54.92                      25,125.00

mod_cook     22.98                      15,000.00

popular_comp 42.95                      15,000.00

psychology   67.52                      21,275.00

trad_cook    47.89                      19,000.00

UNDECIDED    (null)                     (null)

(6 row(s) affected)

See Also

Aggregate Functions


SUSER_ID

Returns the user’s login identification number. The SUSER_ID system function is included in Microsoft® SQL Server™ version 7.0 for backward compatibility. Use SUSER_SID instead.

Syntax

SUSER_ID(['login'])

Arguments
'login'
Is the user’s login identification name. login, which is optional, is nchar. If login is specified as char, it is implicitly converted to nchar. login can be any SQL Server login or Microsoft Windows NT® user or group that has permission to connect to SQL Server. If login is not specified, the login identification number for the current user is returned.
Return Types

int

Remarks

In SQL Server 7.0, the security identification number (SID) replaces the server user identification number (SUID).

SUSER_SID returns a SUID only for a login that has an entry in the syslogins system table.

System functions can be used in the select list, in the WHERE clause, and anywhere an expression is allowed, and must always be followed by parentheses (even if no parameter is specified).

Examples

This example returns the login identification number for the sa login.

SELECT SUSER_ID('sa')

See Also
System Functions


SUSER_NAME

Returns the user’s login identification name. The SUSER_NAME system function is included in Microsoft® SQL Server™ version 7.0 for backward compatibility only. Use SUSER_SNAME instead.

Syntax

SUSER_NAME([server_user_id])

Arguments
server_user_id
Is the user’s login identification number. server_user_id, which is optional, is int. server_user_id can be the login identification number of any SQL Server login or Microsoft Windows NT® user or group that has permission to connect to SQL Server. If server_user_id is not specified, the login identification name for the current user is returned.
Return Types

nchar

Remarks

In SQL Server 7.0, the security identification number (SID) replaces the server user identification number (SUID).

SUSER_NAME returns a login name only for a login that has an entry in the syslogins system table.

System functions can be used in the select list, in the WHERE clause, and anywhere an expression is allowed, and must always be followed by parentheses (even if no parameter is specified).

Examples

This example returns the user’s login identification name for a login identification number of 1.

SELECT SUSER_NAME(1)

See Also
System Functions


SUSER_SID

Returns the security identification number (SID) for the user’s login name.

Syntax

SUSER_SID(['login'])

Arguments
'login'
Is the user’s login name. login is sysname. login, which is optional, can be a Microsoft® SQL Server™ login or Microsoft Windows NT® user or group. If login is not specified, information about the current user is returned.
Return Types

int

Remarks

When specifying a SQL Server login using SQL Server Authentication, the user must be granted permission to connect to SQL Server. Use sp_addlogin or SQL Server Enterprise Manager to grant this permission. However, when specifying a Windows NT user or group using Windows NT Authentication, this user or group does not have to be granted permission to connect to SQL Server.

SUSER_SID can be used as a DEFAULT constraint in either ALTER TABLE or CREATE TABLE.

System functions can be used in the select list, in the WHERE clause, and anywhere an expression is allowed, and must always be followed by parentheses (even if no parameter is specified).

Examples
A. Use SUSER_SID

This example returns the security identification number for the SQL Server sa login.

SELECT SUSER_SID('sa')

Or

SELECT SUSER_SID([sa])

GO

B. Use SUSER_SID with a Windows NT username

This example returns the security identification number for the Windows NT user London\Workstation1.

SELECT SUSER_SID('London\Workstation1')

Or

SELECT SUSER_SID([London\Workstation1])

GO

C. Use SUSER_SID as a DEFAULT constraint

This example uses SUSER_SID as a DEFAULT constraint in a CREATE TABLE statement.

USE pubs

GO

CREATE TABLE sid_example

(

 login_sid   varbinary(85) DEFAULT SUSER_SID(),

 login_name  varchar(30) DEFAULT SYSTEM_USER,

 login_dept  varchar(10) DEFAULT 'SALES',

 login_date  datetime DEFAULT GETDATE()

)

GO

INSERT sid_example DEFAULT VALUES

GO

See Also
ALTER TABLE | sp_addlogin
binary and varbinary | sp_grantlogin
CREATE TABLE | System Functions


SUSER_SNAME

Returns the login identification name from a user’s security identification number (SID).

Syntax

SUSER_SNAME([server_user_sid])

Arguments
server_user_sid
Is the user security identification number. server_user_sid, which is optional, is varbinary(85). server_user_sid can be the security identification number of any Microsoft® SQL Server™ login or Microsoft Windows NT® user or group. If server_user_sid is not specified, information about the current user is returned.
Return Types

nchar

Remarks

When specifying a SQL Server login using SQL Server Authentication, the user must be granted permission to connect to SQL Server. Use sp_addlogin or SQL Server Enterprise Manager to grant this permission. However, when specifying a Windows NT user or group using Windows NT Authentication, this user or group does not have to be granted permission to connect to SQL Server.

SUSER_SNAME can be used as a DEFAULT constraint in either ALTER TABLE or CREATE TABLE.

System functions can be used in the select list, in the WHERE clause, and anywhere an expression is allowed, and must always be followed by parentheses (even if no parameter is specified).

Examples
A. Use SUSER_SNAME

This example returns the login name for the security identification number with a value of 0x01.

SELECT SUSER_SNAME(0x01)

B. Use SUSER_SNAME with a Windows NT user’s security identification number

This example returns the login name for the Windows NT user’s security identification number, obtained by using SUSER_SID.

SELECT SUSER_SNAME(0x010500000000000515000000a065cf7e784b9b5fe77c87705a2e0000)

C. Use SUSER_SNAME as a DEFAULT constraint

This example uses SUSER_SNAME as a DEFAULT constraint in a CREATE TABLE statement.

USE pubs

GO

CREATE TABLE sname_example

(

 login_sname sysname DEFAULT SUSER_SNAME(),

 employee_id uniqueidentifier DEFAULT NEWID(),

 login_date  datetime DEFAULT GETDATE()

)

GO

INSERT sname_example DEFAULT VALUES

GO

See Also
ALTER TABLE | sp_addlogin
binary and varbinary | sp_grantlogin
CREATE TABLE | System Functions


System Stored Procedures

Many administrative and informational activities in Microsoft® SQL Server™ can be performed through system stored procedures. The system stored procedures are grouped into these categories.

Category | Description
Catalog Procedures | Implements ODBC data dictionary functions and isolates ODBC applications from changes to underlying system tables.
Cursor Procedures | Implements cursor variable functionality.
Distributed Queries Procedures | Used to implement and manage Distributed Queries.
SQL Server Agent Procedures | Used by SQL Server Agent to manage scheduled and event driven activities.
Replication Procedures | Used to manage replication.
Security Procedures | Used to manage security.
System Procedures | Used for general maintenance of SQL Server.
Web Assistant Procedures | Used by the Web Assistant.
General Extended Procedures | Provides an interface from SQL Server to external programs for various maintenance activities.
SQL Mail Extended Procedures | Used to perform e-mail operations from within SQL Server.
SQL Server Profiler Extended Procedures | Used by SQL Server Profiler. To execute a SQL Server Profiler Extended Procedure against a local server through SQL Server Query Analyzer, use Windows NT Authentication. When using the shared memory network library, SQL Server does not support impersonation unless connected by using Windows NT Authentication.
OLE Automation Procedures | Allows standard OLE automation objects to be used within a standard Transact-SQL batch.
Data Transformation Services Procedures | Used to manage Data Transformation Services persistence methods and the namespace.

Note Unless specifically documented otherwise, all system stored procedures return a value of 0, which indicates success. To indicate failure, a nonzero value is returned.

Catalog Procedures |
sp_column_privileges | sp_special_columns
sp_columns | sp_sproc_columns
sp_databases | sp_statistics
sp_fkeys | sp_stored_procedures
sp_pkeys | sp_table_privileges
sp_server_info | sp_tables

Cursor Procedures |
sp_cursor_list | sp_describe_cursor_tables
sp_describe_cursor | sp_describe_cursor_columns

SQL Server Agent Procedures |
sp_add_alert | sp_help_jobschedule
sp_add_category | sp_help_jobserver
sp_add_job | sp_help_jobstep
sp_add_jobschedule | sp_help_notification
sp_add_jobserver | sp_help_operator
sp_add_jobstep | sp_help_targetserver
sp_add_notification | sp_help_targetservergroup
sp_add_operator | sp_helphistory
sp_add_targetservergroup | sp_helptask
sp_add_targetsvrgrp_member | sp_manage_jobs_by_login
sp_addtask | sp_msx_defect
sp_apply_job_to_targets | sp_msx_enlist
sp_delete_alert | sp_post_msx_operation
sp_delete_category | sp_purge_jobhistory
sp_delete_job | sp_purgehistory
sp_delete_jobschedule | sp_reassigntask
sp_delete_jobserver | sp_remove_job_from_targets
sp_delete_jobstep | sp_resync_targetserver
sp_delete_notification | sp_start_job
sp_delete_operator | sp_stop_job
sp_delete_targetserver | sp_update_alert
sp_delete_targetservergroup | sp_update_category
sp_delete_targetsvrgrp_member | sp_update_job
sp_droptask | sp_update_jobschedule
sp_help_alert | sp_update_jobstep
sp_help_category | sp_update_notification
sp_help_downloadlist | sp_update_operator
sp_help_job | sp_update_targetservergroup
sp_help_jobhistory | sp_updatetask

Replication Procedures |
sp_add_agent_parameter | sp_dsninfo
sp_add_agent_profile | sp_dumpparamcmd
sp_addarticle | sp_enumcustomresolvers
sp_adddistpublisher | sp_enumdsn
sp_adddistributiondb | sp_enumfullsubscribers
sp_adddistributor | sp_generatefilters
sp_addmergearticle | sp_getmergedeletetype
sp_addmergefilter | sp_get_distributor
sp_addmergepublication | sp_grant_publication_access
sp_addmergepullsubscription | sp_help_agent_default
sp_addmergepullsubscription_agent | sp_help_agent_parameter
sp_addmergesubscription | sp_help_agent_profile
sp_addpublication | sp_help_publication_access
sp_addpublication_snapshot | sp_helparticle
sp_addpublisher70 | sp_helparticlecolumns
sp_addpullsubscription | sp_helpdistpublisher
sp_addpullsubscription_agent | sp_helpdistributiondb
sp_addsubscriber | sp_helpdistributor
sp_addsubscriber_schedule | sp_helpmergearticle
sp_addsubscription | sp_helpmergearticleconflicts
sp_addsynctriggers | sp_helpmergeconflictrows
sp_addtabletocontents | sp_helpmergedeleteconflictrows
sp_article_validation | sp_helpmergefilter
sp_articlecolumn | sp_helpmergepublication
sp_articlefilter | sp_helpmergepullsubscription
sp_articlesynctranprocs | sp_helpmergesubscription
sp_articleview | sp_helppublication
sp_browsereplcmds | sp_helppullsubscription
sp_change_agent_parameter | sp_helpreplicationdboption
sp_change_agent_profile | sp_helpsubscriberinfo
sp_changearticle | sp_helpsubscription
sp_changedistpublisher | sp_helpsubscription_properties
sp_changedistributiondb | sp_link_publication
sp_changedistributor_password | sp_mergedummyupdate
sp_changedistributor_property | sp_mergesubscription_cleanup
sp_changemergearticle | sp_publication_validation
sp_changemergefilter | sp_refreshsubscriptions
sp_changemergepublication | sp_reinitmergepullsubscription
sp_changemergepullsubscription | sp_reinitmergesubscription
sp_changemergesubscription | sp_reinitpullsubscription
sp_changepublication | sp_reinitsubscription
sp_changesubscriber | sp_removedbreplication
sp_changesubscriber_schedule | sp_replcmds
sp_changesubstatus | sp_replcounters
sp_change_subscription_properties | sp_repldone
sp_deletemergeconflictrow | sp_replflush
sp_drop_agent_parameter | sp_replicationdboption
sp_drop_agent_profile | sp_replication_agent_checkup
sp_droparticle | sp_replsetoriginator
sp_dropdistpublisher | sp_replshowcmds
sp_dropdistributiondb | sp_repltrans
sp_dropdistributor | sp_revoke_publication_access
sp_dropmergearticle | sp_script_synctran_commands
sp_dropmergefilter | sp_scriptdelproc
sp_dropmergepublication | sp_scriptinsproc
sp_dropmergepullsubscription | sp_scriptmappedupdproc
sp_dropmergesubscription | sp_scriptupdproc
sp_droppublication | sp_subscription_cleanup
sp_droppullsubscription | sp_table_validation
sp_dropsubscriber | sp_update_agent_profile
sp_dropsubscription |

Security Procedures |
sp_addalias | sp_droprole
sp_addapprole | sp_droprolemember
sp_addgroup | sp_dropserver
sp_addlinkedsrvlogin | sp_dropsrvrolemember
sp_addlogin | sp_dropuser
sp_addremotelogin | sp_grantdbaccess
sp_addrole | sp_grantlogin
sp_addrolemember | sp_helpdbfixedrole
sp_addserver | sp_helpgroup
sp_addsrvrolemember | sp_helplinkedsrvlogin
sp_adduser | sp_helplogins
sp_approlepassword | sp_helpntgroup
sp_change_users_login | sp_helpremotelogin
sp_changedbowner | sp_helprole
sp_changegroup | sp_helprolemember
sp_changeobjectowner | sp_helprotect
sp_dbfixedrolepermission | sp_helpsrvrole
sp_defaultdb | sp_helpsrvrolemember
sp_defaultlanguage | sp_helpuser
sp_denylogin | sp_password
sp_dropalias | sp_remoteoption
sp_dropapprole | sp_revokedbaccess
sp_dropgroup | sp_revokelogin
sp_droplinkedsrvlogin | sp_setapprole
sp_droplogin | sp_srvrolepermission
sp_dropremotelogin | sp_validatelogins

System Procedures |
sp_add_data_file_recover_suspect_db | sp_helpconstraint
sp_add_log_file_recover_suspect_db | sp_helpdb
sp_addextendedproc | sp_helpdevice
sp_addmessage | sp_helpextendedproc
sp_addtype | sp_helpfile
sp_addumpdevice | sp_helpfilegroup
sp_altermessage | sp_help_fulltext_catalogs
sp_autostats | sp_help_fulltext_catalogs_cursor
sp_attach_db | sp_help_fulltext_columns
sp_attach_single_file_db | sp_help_fulltext_columns_cursor
sp_bindefault | sp_help_fulltext_tables
sp_bindrule | sp_help_fulltext_tables_cursor
sp_bindsession | sp_helpindex
sp_certify_removable | sp_helplanguage
sp_configure | sp_helpserver
sp_create_removable | sp_helpsort
sp_createstats | sp_helptext
sp_cycle_errorlog | sp_helptrigger
sp_datatype_info | sp_indexoption
sp_dbcmptlevel | sp_lock
sp_dboption | sp_monitor
sp_delete_backuphistory | sp_processmail
sp_depends | sp_procoption
sp_detach_db | sp_recompile
sp_dropdevice | sp_refreshview
sp_dropextendedproc | sp_rename
sp_dropmessage | sp_renamedb
sp_droptype | sp_serveroption
sp_executesql | sp_setnetname
sp_getbindtoken | sp_spaceused
sp_fulltext_catalog | sp_tableoption
sp_fulltext_column | sp_unbindefault
sp_fulltext_database | sp_unbindrule
sp_fulltext_service | sp_updatestats
sp_fulltext_table | sp_validname
sp_help | sp_who

Distributed Queries Procedures |
sp_addlinkedserver | sp_indexes
sp_addlinkedsrvlogin | sp_linkedservers
sp_catalogs | sp_primarykeys
sp_column_privileges_ex | sp_serveroption
sp_columns_ex | sp_table_privileges_ex
sp_droplinkedsrvlogin | sp_tables_ex
sp_foreignkeys |

Web Assistant Procedures |
sp_dropwebtask | sp_makewebtask
sp_enumcodepages | sp_runwebtask

General Extended Procedures |
xp_cmdshell | xp_revokelogin
xp_enumgroups | xp_sprintf
xp_findnextmsg | xp_sqlinventory
xp_grantlogin | xp_sscanf
xp_loginconfig | xp_logevent
xp_logininfo |
xp_msver |
xp_sqlmaint |

SQL Mail Extended Procedures |
xp_deletemail | xp_startmail
xp_readmail | xp_stopmail
xp_sendmail | xp_findnextmsg

SQL Server Profiler Extended Procedures
xp_sqltrace | xp_trace_getuserfilter
xp_trace_addnewqueue | xp_trace_getwritefilter
xp_trace_deletequeuedefinition | xp_trace_loadqueuedefinition
xp_trace_destroyqueue | xp_trace_pausequeue
xp_trace_enumqueuedefname | xp_trace_restartqueue
xp_trace_enumqueuehandles | xp_trace_savequeuedefinition
xp_trace_eventclassrequired | xp_trace_setappfilter
xp_trace_flushqueryhistory | xp_trace_setconnectionidfilter
xp_trace_generate_event | xp_trace_setcpufilter
xp_trace_getappfilter | xp_trace_setdbidfilter
xp_trace_getconnectionidfilter | xp_trace_setdurationfilter
xp_trace_getcpufilter | xp_trace_seteventclassrequired
xp_trace_getdbidfilter | xp_trace_seteventfilter
xp_trace_getdurationfilter | xp_trace_sethostfilter
xp_trace_geteventfilter | xp_trace_sethpidfilter
xp_trace_geteventnames | xp_trace_setindidfilter
xp_trace_getevents | xp_trace_setntdmfilter
xp_trace_gethostfilter | xp_trace_setntnmfilter
xp_trace_gethpidfilter | xp_trace_setobjidfilter
xp_trace_getindidfilter | xp_trace_setqueryhistory
xp_trace_getntdmfilter | xp_trace_setqueueautostart
xp_trace_getntnmfilter | xp_trace_setqueuecreateinfo
xp_trace_getobjidfilter | xp_trace_setqueuedestination
xp_trace_getqueueautostart | xp_trace_setreadfilter
xp_trace_getqueuedestination | xp_trace_setserverfilter
xp_trace_getqueueproperties | xp_trace_setseverityfilter
xp_trace_getreadfilter | xp_trace_setspidfilter
xp_trace_getserverfilter | xp_trace_setsysobjectsfilter
xp_trace_getseverityfilter | xp_trace_settextfilter
xp_trace_getspidfilter | xp_trace_setuserfilter
xp_trace_getsysobjectsfilter | xp_trace_setwritefilter
xp_trace_gettextfilter |

OLE Automation Extended Stored Procedures
sp_OACreate | sp_OAMethod
sp_OADestroy | sp_OASetProperty
sp_OAGetErrorInfo | sp_OAStop
sp_OAGetProperty | Object Hierarchy Syntax

API System Stored Procedures

Users running SQL Server Profiler against ADO, OLE DB, ODBC, and DB-Library applications may notice the use of system stored procedures that are not covered in the Transact-SQL Reference. These stored procedures are used by the Microsoft OLE DB Provider for SQL Server, the SQL Server ODBC driver, and the DB-Library dynamic-link library (DLL) to implement the functionality of a database API. These stored procedures are simply the mechanism the provider or drivers use to communicate user requests to SQL Server. They are intended only for the internal use of the OLE DB Provider for SQL Server, the SQL Server ODBC driver, and the DB-Library DLL. Calling them explicitly from a SQL Server application is not supported.

The complete functionality from these stored procedures is made available to SQL Server applications through the API functions they support. For example, the cursor functionality of the sp_cursor system stored procedures is made available to OLE DB applications through the OLE DB API cursor properties and methods, to ODBC applications through the ODBC cursor attributes and functions, and to DB-Library applications through the DB-Library Cursor Library.

These system stored procedures support the cursor functionality of ADO, OLE DB, ODBC, and the DB-Library Cursor Library:

sp_cursor | sp_cursorclose | sp_cursorexecute
sp_cursorfetch | sp_cursoropen | sp_cursoroption
sp_cursorprepare | sp_cursorunprepare |

These system stored procedures support the prepare/execute model of executing Transact-SQL statements in ADO, OLE DB, and ODBC:

sp_execute sp_prepare sp_unprepare

The sp_createorphan and sp_droporphans stored procedures are used for ODBC ntext, text, and image processing.

The sp_reset_connection stored procedure is used by SQL Server to support remote stored procedure calls in a transaction.

The sp_sdidebug stored procedure is used by SQL Server for debugging Transact-SQL statements.


Object Hierarchy Syntax

The propertyname parameter of sp_OAGetProperty and sp_OASetProperty and the methodname of sp_OAMethod support object hierarchy syntax similar to Microsoft® Visual Basic®. When this special syntax is used, these parameters have the general form:

Syntax

'TraversedObject.PropertyOrMethod'

Argument
TraversedObject
Is an OLE object in the hierarchy under the objecttoken specified in the stored procedure. Use Visual Basic syntax to specify a series of collections, object properties, and methods that return objects. Each object specifier in the series must be separated by a period (.).

An item in the series can be the name of a collection. Use this syntax to specify a collection:

Collection("item")

The double quotation marks (") around item are required. The Visual Basic exclamation point (!) syntax for collections is not supported.

PropertyOrMethod
Is the name of a property or method of the TraversedObject.

To specify all index or method parameters by using sp_OAGetProperty, sp_OASetProperty, or sp_OAMethod parameters (including support for sp_OAMethod output parameters), use this syntax:

PropertyOrMethod

To specify all index or method parameters inside the parentheses (causing all index or method parameters of sp_OAGetProperty, sp_OASetProperty, or sp_OAMethod to be ignored) use this syntax:

PropertyOrMethod( [ParameterName :=] "parameter" [,…] )

The double quotation marks (") around each parameter are required. All named parameters must be specified after all positional parameters are specified.

Remarks

If TraversedObject is not specified, PropertyOrMethod is required.

If PropertyOrMethod is not specified, the TraversedObject is returned as an object token output parameter from the OLE Automation stored procedure. If PropertyOrMethod is specified, the property or method of the TraversedObject is called, and the property value or method return value is returned as an output parameter from the OLE Automation stored procedure.

If any item in the TraversedObject list does not return an OLE object, an error occurs.

For more information about Visual Basic OLE object syntax, see your Visual Basic documentation.

For more information about HRESULT Return Codes, see HRESULT Return Codes in sp_OACreate.

Example

These are examples of object hierarchy syntax using a SQL-DMO SQLServer object.

-- Call the Connect method of the SQLServer object.

EXEC @hr = sp_OAMethod @object,

    'Connect("my_server", "my_login", "my_password")'

-- Get the pubs..authors Table object.

EXEC @hr = sp_OAGetProperty @object,
   'Databases("pubs").Tables("authors")',
   @table OUT

-- Get the Rows property of the pubs..authors table.

EXEC @hr = sp_OAGetProperty @object,

    'Databases("pubs").Tables("authors").Rows',

    @rows OUT

-- Call the CheckTable method of the pubs..authors table.

EXEC @hr = sp_OAMethod @object,
   'Databases("pubs").Tables("authors").CheckTable',
   @checkoutput OUT

See Also
System Stored Procedures (OLE Automation Extended Stored Procedures)


sp_add_agent_parameter

Adds a new parameter and its value to an agent’s profile.

Syntax

sp_add_agent_parameter [@profile_id =] profile_id,
[@parameter_name =] 'parameter_name',
[@parameter_value =] 'parameter_value'

Arguments
[@profile_id =] profile_id
Is the ID of the configuration from the MSagent_profiles table in the msdb database. profile_id is int, with no default.
[@parameter_name =] 'parameter_name'
Is the name of the parameter. parameter_name is sysname, with no default.
[@parameter_value =] 'parameter_value'
Is the value to be assigned to the parameter. parameter_value is nvarchar(255), with no default.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_add_agent_parameter is used in snapshot, transactional, and merge replication.

Permissions

Only members of the sysadmin fixed server role can execute sp_add_agent_parameter.

See Also
sp_add_agent_profile | sp_help_agent_parameter
sp_drop_agent_parameter | System Stored Procedures


sp_add_agent_profile

Creates a new profile for a replication agent.

Syntax

sp_add_agent_profile [[@profile_id =] profile_id OUTPUT]
{,[@profile_name =] 'profile_name' [,[@agent_type =] 'agent_type'}
[,[@profile_type =] profile_type] {,[@description =] 'description',}
[,[@default =] default]

Arguments
[@profile_id =] profile_id
Is the ID associated with the newly inserted profile. profile_id is int and is an optional OUTPUT parameter. If specified, the value is set to the new profile ID.
[@profile_name =] 'profile_name'
Is the name of the profile. profile_name is sysname, with no default.
[@agent_type =] agent_type
Is the type of agent. agent_type is int, with no default, and can be one of these values.

Value | Description
1 | Snapshot Agent
2 | Log Reader Agent
3 | Distribution Agent
4 | Merge Agent

[@profile_type =] profile_type
Is the type of profile. profile_type is int, with a default of 0. 0 indicates a system profile. 1 indicates a custom profile.
[@description =] 'description'
Is a description of the profile. description is nvarchar(3000), with no default.
[@default =] default
Indicates whether the profile is the default for agent_type. default is bit, with a default of 0. 0 indicates that the profile is not a default. 1 indicates a default profile.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_add_agent_profile is used in snapshot, transactional, and merge replication.

A row is added for the configuration in the MSagent_profiles table.

Permissions

Only members of the sysadmin fixed server role can execute sp_add_agent_profile.

See Also
sp_add_agent_parameter | sp_change_agent_profile
sp_change_agent_parameter | sp_drop_agent_profile
sp_drop_agent_parameter | sp_help_agent_profile
sp_help_agent_parameter | System Stored Procedures


sp_add_alert

Creates an alert.

Syntax

sp_add_alert [@name =] 'name'
[, [@message_id =] message_id]
[, [@severity =] severity]
[, [@enabled =] enabled]
[, [@delay_between_responses =] delay_between_responses]
[, [@notification_message =] 'notification_message']
[, [@include_event_description_in =] include_event_description_in]
[, [@database_name =] 'database']
[, [@event_description_keyword =] 'event_description_keyword_pattern']
[, {[@job_id =] job_id | [@job_name =] 'job_name'}]
[, [@raise_snmp_trap =] raise_snmp_trap]
[, [@performance_condition =] 'performance_condition']
[, [@category_name =] 'category']

Arguments
[@name =] 'name'
Is the name of the alert. The name appears in the e-mail or page sent in response to the alert. It must be unique and can contain the % character. name is sysname, with no default.
[@message_id =] message_id
Is the message error number that defines the alert. (It usually corresponds to an error number in the sysmessages table.) message_id is int, with a default of 0. If severity is used to define the alert, message_id must be 0 or NULL.

Note Only sysmessages errors written to the Microsoft® Windows NT® application log can cause an alert to be sent.

[@severity =] severity
Is the severity level (1 through 25) that defines the alert. Any Microsoft SQL Server™ message stored in the sysmessages table that is sent to the Microsoft Windows NT application log with the indicated severity causes the alert to be sent. severity is int, with a default of 0. If message_id is used to define the alert, severity must be 0.
[@enabled =] enabled
Indicates the current status of the alert. enabled is tinyint, with a default of 1 (enabled). If 0, the alert is not enabled and does not fire.
[@delay_between_responses =] delay_between_responses
Is the wait period, in seconds, between responses to the alert. delay_between_responses is int, with a default of 0, which means there is no waiting between responses (each occurrence of the alert generates a response). The response can be in either or both of these forms:
  • One or more notifications sent through e-mail or pager
  • A job to execute

By setting this value, it is possible to prevent, for example, unwanted e-mail messages from being sent when an alert repeatedly occurs in a short period of time.

[@notification_message =] 'notification_message'
Is an optional additional message sent to the operator as part of the e-mail, net send, or pager notification. notification_message is nvarchar(512), with a default of NULL. Specifying notification_message is useful for adding special notes such as remedial procedures.
[@include_event_description_in =] include_event_description_in
Is whether the description of the SQL Server error should be included as part of the notification message. include_event_description_in is tinyint, with a default of 5 (e-mail and net send), and can have one or more of these values ORed together.

Value | Description
0 (default) | None
1 | E-mail
2 | Pager
4 | net send

[@database_name =] 'database'
Is the database in which the error must occur for the alert to fire. If database is not supplied, the alert fires regardless of where the error occurred. database is sysname, with a default of NULL.
[@event_description_keyword =] 'event_description_keyword_pattern'
Is the sequence of characters that the description of the SQL Server error must be like. Transact-SQL LIKE expression pattern-matching characters can be used. event_description_keyword_pattern is nvarchar(100), with a default of NULL. This parameter is useful for filtering object names (for example, %customer_table%).
[@job_id =] job_id
Is the job identification number of the job to run in response to this alert. job_id is uniqueidentifier, with a default of NULL.
[@job_name =] 'job_name'
Is the name of the job to be executed in response to this alert. job_name is sysname, with a default of NULL.

Note Either job_id or job_name must be specified, but both cannot be specified.

[@raise_snmp_trap =] raise_snmp_trap
Not implemented in SQL Server version 7.0.
[@performance_condition =] 'performance_condition'
Is a value expressed in the format ‘item comparator value’. performance_condition is nvarchar(512) with a default of NULL, and consists of these elements.

Format element | Description
item | A performance object, performance counter, or named instance of the counter
comparator | One of these operators: >, <, =
value | Numeric value of the counter

[@category_name =] 'category'
The name of the alert category. category is sysname with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

sp_add_alert must be run from the msdb database.

These are the circumstances under which errors/messages generated by SQL Server and SQL Server applications are sent to the Windows NT application log and can therefore raise alerts:

  • Severity 19 or higher sysmessages errors
  • Any RAISERROR statement invoked with WITH LOG syntax
  • Any sysmessages error modified or created using sp_altermessage
  • Any event logged using xp_logevent

SQL Server Enterprise Manager provides an easy, graphical way to manage the entire alerting system and is the recommended way to configure an alert infrastructure.

If an alert is not functioning properly, check whether:

  • The SQL Server Agent service is running.
  • The event appeared in the Windows NT application log.
  • The alert is enabled.
Permissions

Only members of the sysadmin fixed server role can execute sp_add_alert.

Examples

This example adds an alert (Test Alert) that invokes the Back up the Customer Database job when fired.

Note This example assumes that the message 55001 and the Back up the Customer Database job already exist. The example is shown for illustrative purposes only.

USE msdb

EXEC sp_add_alert @name = 'Test Alert', @message_id = 55001,
    @severity = 0, @notification_message = 'Error 55001 has occurred.     The database will be backed up…', @job_name = 'Back up the
    Customer Database'

See Also
sp_add_notification | sp_help_alert
sp_addtask | sp_update_alert
sp_altermessage | sysperfinfo
sp_delete_alert | System Stored Procedures


sp_addalias

Maps a login to a user in a database. sp_addalias is provided for backward compatibility. Microsoft® SQL Server™ version 7.0 provides roles and the ability to grant permissions to roles as an alternative to using aliases.

Syntax

sp_addalias [@loginame =] 'login', [@name_in_db =] 'alias_user'

Arguments
[@loginame =] 'login'
Is the name of the login to be aliased. login is sysname with no default. login must be a valid SQL Server login or Microsoft Windows NT® user with permission to connect to SQL Server. login cannot already exist or be aliased to an existing user in the database.
[@name_in_db =] 'alias_user'
Is the name of the user the login is mapped to. alias_user is sysname, with no default. alias_user must be a valid Windows NT or SQL Server user in the database in which the login is aliased. When specifying Windows NT users, specify the name the Windows NT user is known by in the database (added using sp_grantdbaccess).
Return Code Values

0 (success) or 1 (failure)

Remarks

A login can be mapped to users in any database. Execute sp_addalias only in the database in which the user must be aliased. When users connect to SQL Server with login, they can perform activities in the database under the permissions applied to alias_user.

Note The sa login cannot be aliased.

A login can use a database if:

  • The login has an associated user account in the database.
  • The login has a user alias in the database, which has been added by the database owner or member of the sysadmin fixed server role with sp_addalias.
  • The guest account has been added to the database.

sp_addalias cannot be executed from within a user-defined transaction.

The table shows several system stored procedures that can be used in conjunction with sp_addalias.

Stored procedure | Description
sp_helplogins | Returns a list of valid login values.
sp_helpuser | Returns a list of valid alias_user values in the database in which the login is used.
sp_dropalias | Removes an alias mapping.

Permissions

Only members of the db_accessadmin and db_owner fixed database roles can execute sp_addalias.

Examples

This example allows the SQL Server login Victoria, which is not a user in the current database, to use the current database and alias Victoria to an existing user (Albert) in the current database.

EXEC sp_addalias 'Victoria', 'Albert'

See Also
sp_addlogin | sp_helplogins
sp_addrole | sp_helpuser
sp_adduser | System Stored Procedures
sp_dropalias |


sp_addapprole

Adds a special type of role in the current database, which is used for application security.

Syntax

sp_addapprole [@rolename =] 'role', [@password =] 'password'

Arguments
[@rolename =] 'role'
Is the name of the new role. role is sysname, with no default. role must be a valid identifier and cannot already exist in the current database.
[@password =] 'password'
Is the password required to activate the role. password is sysname, with no default. password is stored in encrypted form.
Return Code Values

0 (success) or 1 (failure)

Remarks

Microsoft® SQL Server™ roles can contain from 1 to 128 characters, including letters, symbols, and numbers. However, roles cannot:

  • Contain a backslash character (\).
  • Be NULL or an empty string (‘‘).

The fundamental differences between standard and application roles are:

  • Application roles contain no members. Users, Microsoft Windows NT® groups, and roles cannot be added to application roles; the permissions of the application role are gained when the application role is activated for the user’s connection through a specific application(s). A user’s association with an application role results from being able to run an application that activates the role, rather than being a member of the role.
  • Application roles are inactive by default. They are activated by using sp_setapprole and require a password. The password can be provided by the user, for example, through an application prompt; however, the password is usually incorporated within the application. The password can be encrypted as it is sent to SQL Server.
  • When an application role is activated for a connection by the application, the connection permanently loses all permissions applied to the login, user account, or other groups or database roles in all databases for the duration of the connection. The connection gains the permissions associated with the application role for the database in which the application role exists. Because application roles are applicable only to the database in which they exist, the connection can gain access to another database only through permissions granted to the guest user account in the other database. Therefore, if the guest user account does not exist in a database, the connection cannot gain access to that database. If the guest user account does exist in the database but permissions to access an object are not explicitly granted to guest, the connection cannot access that object, regardless of who created the object. The permissions the user gained from the application role remain in effect until the connection logs out of SQL Server.

sp_addapprole cannot be executed from within a user-defined transaction.

Permissions

Only members of the db_owner and db_securityadmin fixed database roles can execute sp_addapprole.

Examples

This example adds the new application role SalesApp to the current database with the password xyz_123.

EXEC sp_addapprole 'SalesApp', 'xyz_123'

See Also
sp_dropapprole | System Stored Procedures
sp_setapprole |


sp_addarticle

Creates an article and adds it to a publication.

Syntax

sp_addarticle [@publication =] 'publication', [@article =] 'article', [@source_table =] 'source_table'
[,[@destination_table =] 'destination_table']
[,[@vertical_partition =] 'vertical_partition']
[,[@type =] 'type'] [,[@filter =] 'filter'] [,[@sync_object =] 'sync_object']
[,[@ins_cmd =] 'ins_cmd'] [,[@del_cmd =] 'del_cmd']
[,[@upd_cmd =] 'upd_cmd'] [,[@creation_script =] 'creation_script']
[,[@description =] 'description']
[,[@pre_creation_cmd =] 'pre_creation_cmd']
[,[@filter_clause =] 'filter_clause'] [,[@schema_option =] schema_option]
[,[@destination_owner =] 'destination_owner'] [,[@status =] status]
[,[@source_owner =] 'source_owner']
[,[@sync_object_owner =] 'sync_object_owner']
[,[@filter_owner =] 'filter_owner'] [,[@source_object =] 'source_object']

Arguments
[@publication =] 'publication'
Is the name of the publication that contains the article. The name must be unique in the database. publication is sysname, with no default.
[@article =] 'article'
Is the article’s name. The name must be unique within the publication. article is sysname, with no default.
[@source_table =] 'source_table'
Is the name of the underlying table represented by the article or stored procedure. source_table is nvarchar(386), and must be local, conform to the rules for identifiers, and be a table (not a view or another database object). source_table is supported for backward compatibility only; use source_object instead.
[@destination_table =] 'destination_table'
Is the name of the destination (subscription) table, if different from source_table or the stored procedure. destination_table is sysname, with a default of NULL, which means that source_table equals destination_table.
[@vertical_partition =] 'vertical_partition'
Is the column(s) to replicate. vertical_partition is nchar(5), with a default of FALSE. false indicates there is no vertical filtering and publishes all columns. true clears all columns except the declared primary key. Columns are added using sp_articlecolumn.
[@type =] 'type'
Is the type of article. type is sysname, and can be one of these values.

Value | Description
logbased | Log-based article.
logbased manualfilter | Log-based article with manual filter.
logbased manualview | Log-based article with manual view.
logbased manualboth | Log-based article with manual filter and manual view.
proc exec | Replicates the execution of the stored procedure to all Subscribers of the article.
serializable proc exec | Replicates the execution of the stored procedure only if it is executed within the context of a serializable transaction.
NULL (default)

[@filter =] 'filter'
Is the stored procedure (created with FOR REPLICATION) used to horizontally filter the table. filter is nvarchar(386), with a default of NULL. sp_articleview and sp_articlefilter must be executed manually to create the view and filter stored procedure. If not NULL, the filter procedure is not created (assumes the stored procedure is manually created).
[@sync_object =] 'sync_object'
Is the name of the table or view used for producing a synchronization output file. sync_object is nvarchar(386), with a default of NULL. If NULL sp_articleview is called to automatically create the view that synchronizes the output file. This occurs after adding any columns with sp_articlecolumn. If not NULL, a view is not created (assumes the view is manually created).
[@ins_cmd =] 'ins_cmd'
Is the replication mechanism used when replicating inserts. ins_cmd is nvarchar(255), and can be one of these values.

Value | Description
NONE | No action is taken.
CALL sp_MSins_article (default) | Calls a stored procedure to be executed at the Subscriber. To use this method of replication, use @schema_option to specify automatic creation of the stored procedure, or create the specified stored procedure in the destination database of each Subscriber of the article.
SQL or NULL Replicates an INSERT statement. The INSERT statement is provided values for all columns published in the article. This command is replicated on inserts:

INSERT INTO <table name> VALUES (c1value, c2value, c3value, …, cnvalue)

[@del_cmd =] 'del_cmd'
Is the replication mechanism used when replicating deletes. del_cmd is nvarchar(255), and can be one of these values.

Value | Description
NONE | No action is taken.
CALL sp_MSdel_article (default) | Calls a stored procedure to be executed at the Subscriber. To use this method of replication, use @schema_option to specify automatic creation of the stored procedure, or create the specified stored procedure in the destination database of each Subscriber of the article.
SQL or NULL Replicates a DELETE statement. The DELETE statement is provided all primary key column values. This command is replicated on deletes:

DELETE FROM <table name> WHERE pkc1 = pkc1value AND pkc2 = pkc2value AND pkcn = pkcnvalue

[@upd_cmd =] 'upd_cmd'
Is the replication mechanism used when replicating updates. upd_cmd is nvarchar(255), and can be one of these values.

Value | Description
NONE | No action is taken.
CALL sp_MSupd_article | Calls a stored procedure to be executed at the Subscriber. To use this method of replication, use @schema_option to specify automatic creation of the stored procedure, or create the specified stored procedure in the destination database of each Subscriber of the article.
MCALL sp_MSupd_article (default) | Calls a stored procedure taking MCALL style parameters.
SQL or NULL Replicates an UPDATE statement. The UPDATE statement is provided all column values and the primary key column values. This command is replicated on updates:

UPDATE <table name> SET c1 = c1value, SET c2 = c2value, SET cn = cnvalue WHERE pkc1 = pkc1value AND pkc2 = pkc2value AND pkcn = pkcnvalue

[@creation_script =] 'creation_script'
Is the path and name of an article schema script used to create target tables. creation_script is nvarchar(127), with a default of NULL.
[@description =] 'description'
Is a descriptive entry for the article. description is nvarchar(255), with a default of NULL.
[@pre_creation_cmd =] 'pre_creation_cmd'
Is a precreation command for the DROP TABLE, DELETE TABLE, or TRUNCATE TABLE statement. pre_creation_cmd is nvarchar(10), and can be one of these values.

Value | Description
none | Does not use a command.
delete | Deletes the destination table.
drop (default) | Drops the destination table.
truncate | Truncates the destination table. Is not valid for ODBC or OLE BD subscribers.

[@filter_clause =] 'filter_clause'
Is a WHERE clause that specifies the horizontal partitioning. filter_clause is ntext, with a default of NULL.
[@schema_option =] schema_option
Is a bitmask of the schema generation option for the given article. schema_option is binary(8), and can be a combination of these values.

Value | Description
0x0000000000000000 | Disables scripting by the Snapshot Agent and uses the provided CreationScript.
0x0000000000000001 | Generates the object creation (CREATE TABLE, CREATE PROCEDURE, and so on).
0x0000000000000002 | Generates custom stored procedures for the article if defined.
0x0000000000000010 | Generates a corresponding clustered index.
0x0000000000000020 | Converts user-defined data types to base data types.
0x0000000000000040 | Generates corresponding nonclustered index(es).
0x0000000000000080 | Includes declared referential integrity on the primary keys.
0x0000000000000073 (default) | Generates the CREATE TABLE statement, creates clustered index, creates nonclustered index(es), converts user-defined data types to base data types, and generates custom stored procedure scripts to be applied at the Subscriber.
0x0000000000000001 | Default for stored procedure articles.

[@destination_owner =] 'destination_owner'
Is the name of the owner of the destination object. destination_owner is sysname, with a default of NULL. If the publication can be subscribed to by ODBC Subscribers, destination_owner must be NULL.
[@status =] status
Is the bitmask of the article options. status is tinyint, and can be one of these values.

Value | Description
0 | No additional properties.
8 | Include the column name in INSERT statements.
16 (default) | Use parameterized statements.
24 | Both include the column name in INSERT statements and use parameterized statements.

[@source_owner =] 'source_owner'
Is the owner of the source object. source_owner is sysname, with a default of NULL. source_owner is automatically set to NULL for Microsoft® SQL Server™ version 6.5 Publishers.
[@sync_object_owner =] 'sync_object_owner'
Is the owner of the synchronization object. sync_object_owner is sysname, with a default of NULL. sync_object_owner is automatically set to NULL for Microsoft SQL Server 6.5 Publishers.
[@filter_owner =] 'filter_owner'
Is the owner of the filter. filter_owner is sysname, with a default of NULL. filter_owner is automatically set to NULL for Microsoft SQL Server 6.5 Publishers.
[@source_object =] 'source_object'
Is the owner of the source object. source_object is sysname, with a default of NULL. If source_table is NULL, this parameter cannot be NULL. source_object should be used instead of source_table.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_addarticle is used in snapshot, transactional, and merge replication.

If vertical_partition is true, sp_addarticle defers the creation of the view until sp_articleview is called (after the last sp_articlecolumn is added).

If the publication allows immediate-updating subscriptions and the published table does not have a timestamp column, sp_addarticle automatically adds a timestamp column to the table.

Permissions

Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_addarticle.

See Also
sp_addpublication | sp_droppublication
sp_articlecolumn | sp_enumfullsubscribers
sp_articlefilter | sp_helparticle
sp_articleview | sp_helparticlecolumns
sp_changearticle | sp_helppublication
sp_changepublication | System Stored Procedures
sp_droparticle |


sp_add_data_file_recover_suspect_db

Adds a data file to a file group when recovery cannot complete on a database due to an “insufficient space” (1105) error on the filegroup. After the file is added, this stored procedure turns-off the suspect setting and completes the recovery of the database. The parameters are the same as those for ALTER DATABASE ADD FILE.

Important This stored procedure should only be used as described in the Troubleshooting Recovery section.

Syntax

sp_add_data_file_recover_suspect_db [@dbName = ]'database',
[@filegroup = ]'filegroup_name',
[@name = ] 'logical_file_name',
[@filename =] 'os_file_name',
[@size =] 'size',
[@maxsize =] 'max_size',
[@filegrowth =] 'growth_increment'

Arguments
[@dbName = ]'database'
Is the name of the database. database is sysname with no default.
[@filegroup = ]'filegroup_name'
Is the file group in which to add the file. filegroup_name is nvarchar(260) with a default of NULL, which indicates the PRIMARY file.
[@name = ] 'logical_file_name'
Is the name used in Microsoft SQL Server when referencing the file. The name must be unique in the server. logical_file_name is nvarchar(260) with no default.
[@filename =] 'os_file_name'
Is the path and file name used by the operating system for the file. The file must reside in the server in which SQL Server is installed. os_file_name is nvarchar(260) with no default.
[@size =] 'size'
Is the initial size of the file. The MB and KB suffixes can be used to specify megabytes or kilobytes. The default is MB. Specify a whole number; do not include a decimal. The minimum value for size is 512 KB, and the default if size is not specified is 1 MB. size is nvarchar(20) with a default of NULL.
[@maxsize =] 'max_size'
Is the maximum size to which the file can grow. The MB and KB suffixes can be used to specify megabytes or kilobytes. The default is MB. Specify a whole number, do not include a decimal. If max_size is not specified, the file will grow until the disk is full. The Microsoft Windows NT® application log warns an administrator when a disk is about to become full. max_size is nvarchar(20) with a default of NULL.
[@filegrowth =] 'growth_increment'
Is the amount of space added to the file each time new space is needed. A value of 0 indicates no growth. The value can be specified in MB, KB, or %. Specify a whole number; do not include a decimal. When % is specified, the growth increment is the specified percentage of the size of the file at the time the increment occurs. If a number is specified without an MB, KB, or % suffix, the default is MB. The default value if growth_increment is not specified is 10%, and the minimum value is 64 KB. The size specified is rounded to the nearest 64 KB. growth_increment is nvarchar(20) with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

This stored procedure should only be used as described in Troubleshooting Recovery.

Permissions

Execute permissions default to members of the db_owner and db_ddladmin fixed database roles, and to members of the sysadmin and dbcreator fixed server roles. These permissions are not transferable.

Example

In this example, database db1 was marked suspect during recovery due to insufficient space (error 1105) in file group fg1.

sp_add_data_file_recover_suspect_db db1, fg1, file2,
    ‘c:\mssql7\data\db1_file2.mdf’, 1MB

See Also

sp_add_log_file_recover_suspect_db

ALTER DATABASE


sp_adddistpublisher

Creates a remote Publisher that uses the local Distributor.

Syntax

sp_adddistpublisher [@publisher =] 'publisher',
[@distribution_db =] 'distribution_db'
[,[@security_mode =] security_mode]
[,[@login =] 'login'] [,[@password =] 'password']
{,[@working_directory =] 'working_directory'},
[,[@trusted =] 'trusted'] [,[@encrypted_password =] encrypted_password]
[,[@thirdparty_flag =] thirdparty_flag

Arguments
[@publisher =] 'publisher'
Is the Publisher name. publisher is sysname, with no default.
[@distribution_db =] 'distribution_db'
Is the name of the distribution database. distributor_db is sysname, with no default. This parameter is used by replication agents to connect to the Publisher.
[@security_mode =] security_mode
Is the implemented security mode. security_mode is int, and can be one of these values.

Value | Description
0 | SQL Server Authentication security. Used when Distributor is running on Microsoft Windows® 95.
1 | Windows NT Authentication security. Used when Distributor is running on Microsoft® Windows NT®.
NULL (default) | Set to 0 or 1 according to the platform used.

This parameter is used by replication agents to connect to the Publisher.

[@login =] 'login'
Is the login. This parameter is required if security_mode is 0. login is sysname, with a default of sa. This parameter is used by replication agents to connect to the Publisher.
[@password =] 'password']
Is the password. password is sysname, with a default of NULL. This parameter is used by replication agents to connect to the Publisher.
[@working_directory =] 'working_directory'
Is the name of the working directory used to store data and schema files for the publication. working_directory is nvarchar(255). The name should be specified in UNC format.
[@trusted =] 'trusted'
Is whether the remote Publisher uses the same password as the local Distributor. trusted is nvarchar(5), and can be one of these values.

Value | Description
true | One trusted login mapping is added: sa to distributor_admin. Because the mapping is trusted, no password is needed at the remote Publisher to connect to the Distributor. SQL Server 6.x Publishers should be created as trusted.
false | One nontrusted mapping is added, distributor_admin to distributor_admin. A password is needed at the remote Publisher to make a connection.
NULL (default) | If the distribution Publisher is local, the default is nontrusted. Any password set for the Distributor is also set for the local distribution Publisher (linked server connection back to local Distributor). If the distribution Publisher is remote, the default is trusted and no password is needed at the remote Publisher. If the user directly changes the distributor_admin password instead of using sp_changedistributor_password, the local link is broken.

[@encrypted_password =] encrypted_password
Is whether the password is encrypted. encrypted_password is bit, with a default of 0. If 1, password is stored in encrypted form.
[@thirdparty_flag =] thirdparty_flag
Is whether the publication is a Microsoft SQL Server database. thirdparty_flag is bit, and can be one of these values.

Value | Description
0 (default) | Microsoft SQL Server
1 | Data source other than Microsoft SQL Server

Return Code Values

0 (success) or 1 (failure)

Remarks

sp_adddistpublisher is used by snapshot, transactional, and merge replication.

Permissions

Only members of the sysadmin fixed server role can execute sp_adddistpublisher.

See Also
sp_changedistpublisher | sp_helpdistpublisher
sp_dropdistpublisher | System Stored Procedures


sp_adddistributiondb

Creates a new distribution database and installs the Distributor schema. The distribution database stores procedures for distribution and distribution history.

Syntax

sp_adddistributiondb [@database =] 'database'
[,[@data_folder =] 'data_folder'] [,[@data_file =] 'data_file']
[,[@data_file_size =] data_file_size] [,[@log_folder =] 'log_folder']
[,[@log_file =] 'log_file'] [,[@log_file_size =] log_file_size]
[,[@min_distretention =] min_distretention]
[,[@max_distretention =] max_distretention]
[,[@history_retention =] history_retention]
[,[@security_mode =] security_mode] [,[@login =] 'login']
[,[@password =] 'password']
[,[@createmode =] createmode]

Arguments
[@database =] 'database'
Is the database name. database is sysname, with no default.
[@data_folder =] 'data_folder'
Is the name of the directory used to store the database files. data_folder is nvarchar(255), with a default of NULL. If NULL, the data directory for that instance of Microsoft® SQL Server™ is used, for example, '\Mssql7\Data'.
[@data_file =] 'data_file'
Is the name of the database file. data_file is nvarchar(255), with a default of database. If NULL, the stored procedure constructs the new file name using the database name.
[@data_file_size =] data_file_size
Is the initial data file size in megabytes (MB). data_file_size is int, with a default of 2 MB.
[@log_folder =] 'log_folder'
Is the name of the directory for the database log file. log_folder is nvarchar(255), with a default of NULL. If NULL, the data directory for that instance of Microsoft® SQL Server™ is used, for example, '\Mssql7\Data'.
[@log_file =] 'log_file'
Is the name of the log file. log_file is nvarchar(255), with a default of NULL. If NULL, the stored procedure constructs the new file name using the database name.
[@log_file_size =] log_file_size
Is the initial log file size in MB. log_file_size is int, with a default of 0 MB, which means the file size is 512 KB, the smallest allowed.
[@min_distretention =] min_distretention
Is the minimum retention period, in hours, before transactions are deleted. min_distretention is int, with a default of 0 hours.
[@max_distretention =] max_distretention
Is the maximum retention period, in hours, before transactions are deleted. max_distretention is int, with a default of 72 hours. Subscriptions that are inactive beyond this period are automatically deactivated. RAISERROR 21011 is issued for each deactivated subscription.
[@history_retention =] history_retention
Is the number of hours to retain history. history_retention is int, with a default of 48 hours.
[@security_mode =] security_mode
Is the security mode implemented by the Distributor. security_mode is int, with a default of 0. 0 specifies SQL Server Authentication. 1 specifies Windows NT Authentication.
[@login =] 'login'
Is the login name used when connecting to the Distributor. This is required if security_mode is set to 0. login is sysname, with a default of sa.
[@password =] 'password'
Is the password used when connecting to the Distributor. This is required if security_mode is set to 0. password is sysname, with a default of NULL.
[@createmode =] createmode
createmode is int, with a default of 0, and can be one of these values.

Value | Description
0 (default) | Use CREATE DATABASE for attach.
1 | CREATE DATABASE or use existing but no attach.
2 | For internal use only.

Return Code Values

0 (success) or 1 (failure)

Remarks

sp_adddistributiondb is used in all types of replication.

Permissions

Only members of the sysadmin fixed server role can execute sp_adddistributiondb.

See Also
sp_changedistributiondb | sp_helpdistributiondb
sp_dropdistributiondb | System Stored Procedures


sp_adddistributor

Creates an entry in the sysservers table (if there is not one), marks it as the Distributor, and stores property information.

Syntax

sp_adddistributor [@distributor =] 'distributor'
[,[@heartbeat_interval =] heartbeat_interval]
[,[@password =] 'password']

Arguments
[@distributor =] 'distributor'
Is the Distributor server name. distributor is sysname, with no default. If setting up a remote Distributor, only this parameter is meaningful. It adds entries for the Distributor properties in the msdb..MSdistributor table.
[@heartbeat_interval =] heartbeat_interval
Is the maximum number of minutes that an agent can go without logging a progress message. heartbeat_interval is int, with a default of 10 minutes. A SQL Agent Job is created that wakes up on this interval to check the status of the replication agents that are running.
[@password =] 'password']
Is the password of the distributor_admin login. password is sysname, with a default of NULL. distributor_admin login and password are stored for linked server entry used for a distributor RPC connection, including local connections. If distributor is local, the password for distributor_admin is set to a new value.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_adddistributor is used in snapshot, transactional, and merge replication.

Permissions

Only members of the sysadmin fixed server role can execute sp_adddistributor.

See Also
sp_changedistributor_property | sp_helpdistributor
sp_dropdistributor | System Stored Procedures


sp_addextendedproc

Registers the name of a new extended stored procedure to Microsoft® SQL Server™.

Syntax

sp_addextendedproc [@functname =] 'procedure',
[@dllname =] 'dll'

Arguments
[@functname =] 'procedure'
Is the name of the function to call within the dynamic-link library (DLL). procedure is nvarchar(517), with no default. procedure optionally can include the owner name in the form owner.function.
[@dllname =] 'dll'
Is the name of the DLL containing the function. dll is varchar(255), with no default.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

Programmers using Microsoft Open Data Services can create extended stored procedures. After an extended stored procedure is created, it must be added to SQL Server by using sp_addextendedproc.

Only add an extended stored procedure to the master database. To execute an extended stored procedure from a database other than master, qualify the name of the extended stored procedure with master.

sp_addextendedproc adds entries to the sysobjects table, registering the name of the new extended stored procedure with SQL Server. It also adds an entry in the syscomments table.

Permissions

Only members of the sysadmin fixed server role can execute sp_addextendedproc.

Examples

This example adds the xp_diskfree extended stored procedure.

USE master

EXEC sp_addextendedproc xp_diskfree, '\mssql7\binn\mydll.dll'

See Also
EXECUTE | sp_dropextendedproc
GRANT | sp_helpextendedproc
REVOKE | System Stored Procedures


sp_addgroup

Creates a group in the current database. sp_addgroup is included for backward compatibility. Microsoft® SQL Server™ version 7.0 uses roles instead of groups. Use sp_addrole to add a role.

Syntax

sp_addgroup [@grpname =] 'group'

Arguments
[@grpname =] 'group'
Is the name of the group to add. group is sysname, with no default.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_addgroup calls sp_addrole to add the new group.

Permissions

Only members of the db_securityadmin and db_owner fixed database roles can execute sp_addgroup.

Examples

This example creates the group accounting.

EXEC sp_addgroup 'accounting'

See Also
sp_addrole | sp_helpgroup
sp_changegroup | sp_helprole
sp_dropgroup | System Stored Procedures


sp_add_category

Adds the specified category of jobs, alerts, or operators to the server.

Syntax

sp_add_category [[@class =] 'class',]
[[@type =] 'type',]
{[@name =] 'name'}

Arguments
[@class =] 'class'
Is the class of the category to be added. class is varchar(8) with a default value of JOB, and can be one of these values.

Value | Description
JOB | Adds a job category.
ALERT | Adds an alert category.
OPERATOR | Adds an operator category.

[@type =] 'type'
Is the type of category to be added. type is varchar(12), with a default value of LOCAL, and can be one of these values.

Value | Description
LOCAL | A local job category.
MULTI -SERVER | A multiserver job category.
NONE | A category for a class other than JOB.

[@name =] 'name'
Is the name of the category to be added. The name must be unique within the specified class. name is sysname, with no default.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

sp_add_category must be executed in the msdb database.

Permissions

Only members of the sysadmin fixed server role or the db_owner fixed database role can execute sp_add_category.

Examples

This example creates a local job category name AdminJobs.

USE msdb

EXEC sp_add_category 'JOB', 'LOCAL', 'AdminJobs'

See Also
sp_delete_category | sysjobs
sp_help_category | sysjobservers
sp_update_category | System Stored Procedures


sp_add_job

Adds a new job that can be executed by SQL Server Agent.

Syntax

sp_add_job [@job_name =] 'job_name'
[,[@enabled =] enabled]
[,[@description =] 'description']
[,[@start_step_id =] step_id]
[,[@category_name =] 'category']
[,[@category_id =] category_id]
[,[@owner_login_name =] 'login']
[,[@notify_level_eventlog =] eventlog_level]
[,[@notify_level_email =] email_level]
[,[@notify_level_netsend =] netsend_level]
[,[@notify_level_page =] page_level]
[,[@notify_email_operator_name =] 'email_name']
[,[@notify_netsend_operator_name =] 'netsend_name']
[,[@notify_page_operator_name =] 'page_name']
[,[@delete_level =] delete_level]
[,[@job_id =] job_id OUTPUT]

Arguments
[@job_name =] 'job_name'
Is the name of the job. The name must be unique and cannot contain the % character. job_name is sysname, with no default.
[@enabled =] enabled
Indicates the status of the added job. enabled is tinyint, with a default of 1 (enabled). If 0, the job is not enabled and does not run according to its schedule; however, it can be run manually.
[@description =] 'description'
Is the description of the job. description is nvarchar(512), with a default of NULL. If description is omitted, “No description available.” is used.
[@start_step_id =] step_id
Is the identification number of the first step to execute for the job. step_id is int, with a default of 1.
[@category_name =] 'category'
Is the category for the job. category is sysname, with a default of NULL.
[@category_id =] category_id
Is a language-independent mechanism for specifying a job category. category_id is int, with a default of NULL.
[@owner_login_name =] 'login'
Is the name of the login that owns the job. login is sysname, with a default of NULL, which is interpreted as the current login name.
[@notify_level_eventlog =] eventlog_level
Is a value indicating when to place an entry in the Microsoft® Windows NT® application log for this job. eventlog_level is int, and can be one of these values.

Value | Description
0 | Never
1 | On success
2 (default) | On failure
3 | Always

[@notify_level_email =] email_level
Is a value indicating when to send an e-mail upon the completion of this job. email_level is int, with a default of 0, which indicates on success. email_level uses the same values as eventlog_level.
[@notify_level_netsend =] netsend_level
Is a value indicating when to send a network message upon the completion of this job. netsend_level is int, with a default of 0, which indicates never. netsend_level uses the same values as eventlog_level.
[@notify_level_page =] page_level
Is a value indicating when to send a page upon the completion of this job. page_level is int, with a default of 0, which indicates never. page_level uses the same values as eventlog_level.
[@notify_email_operator_name =] 'email_name'
Is the e-mail name of the person to send e-mail to when email_level is reached. email_name is sysname, with a default of NULL.
[@notify_netsend_operator_name =] 'netsend_name'
Is the name of the operator to whom the network message is sent upon completion of this job. netsend_name is sysname, with a default of NULL.
[@notify_page_operator_name =] 'page_name'
Is the name of the person to page upon completion of this job. page_name is sysname, with a default of NULL.
[@delete_level =] delete_level
Is a value indicating when to delete the job. delete_value is int, with a default of 0, which means never. delete_level uses the same values as eventlog_level.

Note When delete_level is 3, the job is executed only once, regardless of any schedules that have been defined for the job. Furthermore, if a job deletes itself, all history for the job is also deleted.

[@job_id =] job_id OUTPUT
Is the job identification number assigned to the job if it is created successfully. job_id is an output variable of type uniqueidentifer, with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

@originating_server exists in sp_add_job but is not listed under Arguments. @originating_server is reserved for internal use.

After sp_add_job has been executed to add a job, sp_add_jobstep can be used to add steps that perform the activities for the job. sp_add_jobschedule can be used to create the schedule that SQL Server Agent uses to execute the job.

SQL Server Enterprise Manager provides an easy, graphical way to manage jobs, and is the recommended way to create and manage the job infrastructure.

Permissions

Execute permissions default to the public role.

Examples
A. Add a job

This example adds a new job named NightlyBackups.

USE msdb

EXEC sp_add_job @job_name = 'NightlyBackups'

B. Add a job with pager, e-mail, and net send information

This example creates a job named Ad hoc Sales Data Backup that notifies janetl (by pager, e-mail, and a network message) if the job fails, and deletes the job upon successful completion.

USE msdb

EXEC sp_add_job @job_name = 'Ad hoc Sales Data Backup',
    @enabled = 1,
    @description = 'Ad hoc backup of sales data',
    @owner_login_name = 'janet1',
    @notify_level_eventlog = 2,
    @notify_level_email = 2,
    @notify_level_netsend =2,
    @notify_level_page = 2,
    @notify_email_operator_name = 'janet1',
    @notify_netsend_operator_name = 'janet1',
    @notify_page_operator_name = 'janet1',
    @delete_level = 1

See Also
sp_add_jobschedule | sp_help_jobstep
sp_add_jobstep | sp_update_job
sp_delete_job | System Stored Procedures
sp_help_job |


sp_add_jobschedule

Creates a schedule for a job.

Syntax

sp_add_jobschedule [@job_id =] job_id, | [@job_name =] 'job_name',
[@name =] 'name'
[,[@enabled =] enabled]
[,[@freq_type =] freq_type]
[,[@freq_interval =] freq_interval]
[,[@freq_subday_type =] freq_subday_type]
[,[@freq_subday_interval =] freq_subday_interval]
[,[@freq_relative_interval =] freq_relative_interval]
[,[@freq_recurrence_factor =] freq_recurrence_factor]
[,[@active_start_date =] active_start_date]
[,[@active_end_date =] active_end_date]
[,[@active_start_time =] active_start_time]
[,[@active_end_time =] active_end_time]

Arguments
[@jobid =] job_id
Is the job identification number of the job to which the schedule is added. job_id is uniqueidentifier, with a default of NULL.
[@job_name =] 'job_name'
Is the name of the job to which added the schedule is added. job_name is sysname, with a default of NULL.

Note Either job_id or job_name must be specified, but both cannot be specified.

[@name =] 'name'
Is the name of the schedule. name is sysname, with no default.
[@enabled =] enabled
Indicates the current status of the schedule. enabled is tinyint, with a default of 1 (enabled). If 0, the schedule is not enabled. When the schedule is disabled, the job will not be run.
[@freq_type =] freq_type
Is a value indicating when the job is to be executed. freq_type is int, with a default of 0, and can be one of these values.

Value | Description
1 | Once.
4 | Daily.
8 | Weekly.
16 | Monthly.
32 | Monthly, relative to freq interval.
64 | Run when SQL Server Agent starts.
128 | Run when the computer is idle.

[@freq_interval =] freq_interval
Is the days that the job is executed. freq_interval is int, with a default of 0, and depends on the value of freq_type.

Value of freq_type | Effect on freq_interval
1 (once) | freq_interval is unused.
4 (daily) | Every freq_interval days.
8 (weekly) freq_interval is one-or-more of the following (ORed together):
1 = Sunday
2 = Monday
4 = Tuesday
8 = Wednesday
16 = Thursday
32 = Friday
64 = Saturday
16 (monthly) | On the freq_interval day of the month.
32 (monthly relative) freq_interval is one of the following:
1 = Sunday
2 = Monday
3 = Tuesday
4 = Wednesday
5 = Thursday
6 = Friday
7 = Saturday
8 = Day
9 = Week day
10 = Weekend day
64 (When SQL Server Agent starts) | freq_interval is unused.
128 | freq_interval is unused.

[@freq_subday_type =] freq_subday_type
Is the units for freq_subday_interval. freq_subday_type is int, with a default of 0, and can be one of these values.

Value | Description (unit)
0x1 | At the specified time
0x4 | Minutes
0x8 | Hours

[@freq_subday_interval =] freq_subday_interval
Is the number of freq_subday_type periods to occur between each execution of the job. freq_subday_interval is int, with a default of 0.
[@freq_relative_interval =] freq_relative_interval
Is the scheduled job’s occurrence of freq_interval in each month, if freq_interval is 32 (monthly relative). freq_relative_interval is int, with a default of 0, and can be one of these values.

Value | Description (unit)
1 | First
2 | Second
4 | Third
8 | Fourth
16 | Last

[@freq_recurrence_factor =] freq_recurrence_factor
Is the number of weeks or months between the scheduled execution of the job. freq_recurrence_factor is used only if freq_type is 8, 16, or 32. freq_recurrence_factor is int, with a default of 0.
[@active_start_date =] active_start_date
Is the date on which execution of the job can begin. active_start_date is int, with a default of NULL, which indicates today's date. The date is formatted as YYYYMMDD. If active_start_date is not NULL, the date must be greater than or equal to 19900101.
[@active_end_date =] active_end_date
Is the date on which execution of the job can stop. active_end_date is int, with a default of 99991231, which indicates December 31, 9999. Formatted as YYYYMMDD.
[@active_start_time =] active_start_time
Is the time on any day between active_start_date and active_end_date to begin execution of the job. active_start_time is int, with a default of 000000, which indicates 12:00:00 A.M. on a 24-hour clock, and must be entered using the form HHMMSS.
[@active_end_time =] active_end_time
Is the time on any day between active_start_date and active_end_date to end execution of the job. active_end_time is int, with a default of 235959, which indicates 11:59:59 P.M. on a 24-hour clock, and must be entered using the form HHMMSS.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

SQL Server Enterprise Manager provides an easy, graphical way to manage jobs, and is the recommended way to create and manage the job infrastructure.

Permissions

Execute permissions default to the public role.

Examples

This example assumes the job NightlyBackup has been created to back up a database. It adds the job to the schedule with the name ScheduledBackup and executes every day at 1:00 A.M.

USE msdb

EXEC sp_add_jobschedule @job_name = 'NightlyBackup',

    @name = 'ScheduledBackup',
    @freq_type = 4, -- daily
    @freq_interval = 1,
    @active_start_time = '1:00:00'

See Also
sp_delete_jobschedule | sp_update_jobschedule
sp_help_jobschedule | System Stored Procedures


sp_add_jobserver

Targets the specified job at the specified server.

Syntax

sp_add_jobserver [@job_id =] job_id | [@job_name =] 'job_name'
[, [@server_name =] 'server' ]

Arguments
[@job_id =] job_id
Is the identification number of the job. job_id is uniqueidentifer, with a default of NULL.
[@job_name =] 'job_name'
Is the name of the job. job_name is sysname, with a default of NULL.

Note Either job_id or job_name must be specified, but both cannot be specified.

[@server_name =] 'server'
Is the name of the server at which to target the job. server is nvarchar(30), with a default of N’(LOCAL)’. server can be either (LOCAL) for a local server, or the name of an existing target server.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

@automatic_post exists in sp_add_jobserver but is not listed under Arguments. @automatic_post is reserved for internal use.

SQL Server Enterprise Manager provides an easy, graphical way to manage jobs, and is the recommended way to create and manage the job infrastructure.

Permissions

Execute permissions default to the public role for local jobs. Only members of the sysadmin fixed server role can execute sp_add_jobserver for multiserver jobs.

Examples

This example assigns the SEATTLE2 server to the multiserver job, Weekly Sales Data Backup job.

Note This example assumes that the Weekly Sales Data Backup job already exists.

USE msdb

EXEC sp_add_jobserver @job_name = 'Weekly Sales Data Backup',
    @server_name = 'SEATTLE2'

See Also
sp_apply_job_to_targets | System Stored Procedures
sp_delete_jobserver |


sp_add_jobstep

Adds a step (operation) to a job.

Syntax

sp_add_jobstep [@job_id =] job_id | [@job_name =] 'job_name']
[,[@step_id =] step_id]
{,[@step_name =] 'step_name'}
[,[@subsystem =] 'subsystem']
[,[@command =] 'command']
[,[@additional_parameters =] 'parameters']
[,[@cmdexec_success_code =] code]
[,[@on_success_action =] success_action]
[,[@on_success_step_id =] success_step_id]
[,[@on_fail_action =] fail_action]
[,[@on_fail_step_id =] fail_step_id]
[,[@server =] 'server']
[,[@database_name =] 'database']
[,[@database_user_name =] 'user']
[,[@retry_attempts =] retry_attempts]
[,[@retry_interval =] retry_interval]
[,[@os_run_priority =] run_priority]
[,[@output_file_name =] 'file_name']
[,[@flags =] flags]

Arguments
[@job_id =] job_id
Is the identification number of the job to which to add the step. job_id is uniqueidentifier, with a default of NULL.
[@job_name =] 'job_name'
Is the name of the job to which to add the step. job_name is sysname, with a default of NULL.

Note Either job_id or job_name must be specified, but both cannot be specified.

[@step_id =] step_id]
Is the sequence identification number for the job step. Step identification numbers start at 1 and increment without gaps. If a step is inserted in the existing sequence, the sequence numbers are adjusted automatically. A value is provided if step_id is not specified. step_id is int, with a default of NULL.
[@step_name =] 'step_name'
Is the name of the step. step_name is sysname, with no default.
[@subsystem =] 'subsystem'
Is the subsystem used by SQL Server Agent to execute command. subsystem is nvarchar(40), and can be one of these values.

Value | Description
‘ACTIVESCRIPTING’ | Active Script
‘CMDEXEC’ | Operating-system command or executable program
‘DISTRIBUTION’ | Replication Distribution Agent job
‘SNAPSHOT’ | Replication Snapshot Agent job
‘LOGREADER’ | Replication Log Reader Agent job
‘MERGE’ | Replication Merge Agent job
‘TSQL’ (default) | Transact-SQL statement

[@command =] 'command'
Is the command(s) to be executed by SQL Server Agent through subsystem. command is nvarchar(3200), with a default of NULL. command can include one or more of the following case-sensitive tokens (which are replaced at run time).

Value | Description
[A-DBN] | Database name. If the job is run by an alert, this token automatically replaces the version 6.5 [DBN] token during the conversion process.
[A-SVR] | Server name. If the job is run by an alert, this token automatically replaces the version 6.5 [SVR] token during the conversion process.
[A-ERR] | Error number. If this job is run by an alert, this token automatically replaces the version 6.5 [ERR] token during the conversion process.
[A-SEV] | Error severity. If the job is run by an alert, this token automatically replaces the version 6.5 [SEV] token during the conversion process.
[A-MSG] | Message text. If the job is run by an alert, this token automatically replaces the version 6.5 [MSG] token during the conversion process.
[DATE] | Current date (in YYYYMMDD format).
[JOBID] | Job ID.
[MACH] | Computer name.
[MSSA] | Master SQLServerAgent name.
[SQLDIR] | The directory in which SQL Server is installed. By default, this value is C:\Mssql7.
[STEPCT] | A count of the number of times this step has executed (excluding retires). Can be used by the step command to force termination of a multistep loop.
[STEPID] | Step ID.
[TIME] | Current time (in HHMMSS format).
[STRTTM] | The time (in HHMMSS format) that the job began executing.
[STRTDT] | The date (in YYYYMMDD format) that the job began executing.

[@additional_parameters =] 'parameters'
Reserved. parameters is ntext, with a default of NULL.
[@cmdexec_success_code =] code
Is the value returned by a CmdExec subsystem command to indicate that command executed successfully. code is int, with a default of 0.
[@on_success_action =] success_action
Is the action to perform if the step succeeds. success_action is tinyint, and can be one of these values.

Value | Description (action)
1 (default) | Quit with success.
2 | Quit with failure.
3 | Go to next step.
4 | Go to step on_success_step_id.

[@on_success_step_id =] success_step_id
Is the ID of the step in this job to execute if the step succeeds and success_action is 4. success_step_id is int, with a default of 0.
[@on_fail_action =] fail_action
Is the action to perform if the step fails. fail_action is tinyint, and can be one of these values.

Value | Description (action)
1 | Quit with success.
2 (default) | Quit with failure.
3 | Go to next step.
4 | Go to step on_fail_step_id.

[@on_fail_step_id =] fail_step_id
Is the ID of the step in this job to execute if the step fails and fail_action is 4. fail_step_id is int, with a default of 0.
[@server =] 'server'
Reserved. server is nvarchar(30), with a default of NULL.
[@database_name =] 'database'
Is the name of the database in which to execute a TSQL step. database is sysname, with a default of NULL, in which case the master database is used.
[@database_user_name =] 'user'
Is the name of the user account to use when executing a TSQL step. user is sysname, with a default of NULL. When user is NULL, the step runs in the job owner’s user context on database.
[@retry_attempts =] retry_attempts
Is the number of retry attempts to use if this step fails. retry_attempts is int, with a default of 0, which indicates no retry attempts.
[@retry_interval =] retry_interval
Is the amount of time in minutes between retry attempts. retry_interval is int, with a default of 0, which indicates a 0-minute interval.
[@os_run_priority =] run_priority
Reserved.
[@output_file_name =] 'file_name'
Is the name of the file in which the output of this step is saved. file_name is nvarchar(200), with a default of NULL. file_name can include one or more of the tokens listed under command. This parameter is valid only with commands running on the TSQL or CmdExec subsystems.
[@flags =] flags
Is an option that controls behavior. flags is int, and can be one of these values.

Value | Description
2 | Append to output file.
4 | Overwrite output file.
0 (default) | No options set.

Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

SQL Server Enterprise Manager provides an easy, graphical way to manage jobs, and is the recommended way to create and manage the job infrastructure.

Permissions

Execute permissions default to the public role.

Examples

This example creates a job step that changes database access to read-only for a database named sales. In addition, this example specifies five retry attempts every 5 minutes.

Note This example assumes that the Weekly Sales Data Backup job already exists.

USE msdb

EXEC sp_add_jobstep @job_name = 'Weekly Sales Data Backup',
    @step_name = 'Set database to read only',
    @subsystem = 'TSQL',
    @command = 'exec sp_dboption ''sales'', ''read only'', ''true''',
    @retry_attempts = 5,
    @retry_interval = 5

See Also
sp_add_job | sp_help_jobstep
sp_add_jobschedule | sp_update_jobstep
sp_delete_jobstep | System Stored Procedures
sp_help_job |


sp_addlinkedserver

Creates a linked server, which allows access to distributed, heterogeneous queries against OLE DB data sources. After creating a linked server with sp_addlinkedserver, this server can then execute distributed queries. If the linked server is defined as SQL Server, remote stored procedures can be executed.

Syntax

sp_addlinkedserver [@server =] 'server' [, [@srvproduct =] 'product_name']
[, [@provider =] 'provider_name'] [, [@datasrc =] 'data_source']
[, [@location =] 'location'] [, [@provstr =] 'provider_string']
[, [@catalog =] 'catalog']

Arguments
[@server =] 'server'
Is the name of the linked server to create. server is sysname, with no default.
[@srvproduct =] 'product_name'
Is the product name of the OLE DB data source to add as a linked server. product_name is nvarchar(128), with a default of NULL. If SQL Server, provider_name, data_source, location, provider_string, and catalog do not need to be specified.
[@provider =] 'provider_name'
Is the unique programmatic identifier (PROGID) of the OLE DB provider corresponding to this data source. provider_name must be unique for the specified OLE DB provider installed on the current computer. provider_name is nvarchar(128), with a default of NULL. The OLE DB provider is expected to be registered with the given PROGID in the registry.
[@datasrc =] 'data_source'
Is the name of the data source as interpreted by the OLE DB provider. data_source is nvarchar(4000), with a default of NULL. data_source is passed as the DBPROP_INIT_DATASOURCE property to initialize the OLE DB provider.
[@location =] 'location'
Is the location of the database as interpreted by the OLE DB provider. location is nvarchar(4000), with a default of NULL. location is passed as the DBPROP_INIT_LOCATION property to initialize the OLE DB provider.
[@provstr =] 'provider_string'
Is the OLE DB provider-specific connection string that identifies a unique data source. provider_string is nvarchar(4000), with a default of NULL. provstr is passed as the DBPROP_INIT_PROVIDERSTRING property to initialize the OLE DB provider.
[@catalog =] 'catalog'
Is the catalog to be used when making a connection to the OLE DB provider. catalog is sysname, with a default of NULL. catalog is passed as the DBPROP_INIT_CATALOG property to initialize the OLE DB provider.
Return Code Values

0 (success) or 1 (failure)

Result Sets

sp_addlinkedserver returns this message if no parameters are specified:

Procedure 'sp_addlinkedserver' expects parameter '@server', which was not supplied.

sp_addlinkedserver used with the appropriate OLE DB provider and parameters returns this message:

Server added.

Remarks

The table shows the ways that a linked server can be set up for data sources accessible through OLE DB. A linked server can be set up using more than one way for a given data source; therefore, there may be more than one row for a data source type. The table also shows the sp_addlinkedserver parameter values to be used for setting up the linked server.

Remote OLE DB data source | OLE DB provider | product_ name | provider_ name | data_ source | location | provider_ string | catalog
SQL Server | Microsoft OLE DB Provider for SQL Server | SQL Server (1) (default) | - | - | - | - | -
SQL Server | SQL Server | SQL Server | SQLOLEDB | Network name of SQL Server | - | - | -
Oracle | Microsoft OLE DB Provider for Oracle | Any (2) | MSDAORA | SQL*Net alias for Oracle database | - | - | -
Access/Jet | Microsoft OLE DB Provider for Jet | Any | Microsoft.Jet .OLEDB.4.0 | Full path name of Jet database file | - | - | -
ODBC data source | Microsoft OLE DB Provider for ODBC | Any | MSDASQL | System DSN of ODBC data source | - | - | -
ODBC data source | Microsoft OLE DB Provider for ODBC | Any | MSDASQL | - | - | ODBC connection string | -
File system | Microsoft OLE DB Provider for Indexing Service | Any | MSIDXS | Indexing Service catalog name | - | - | -
Microsoft Excel Spreadsheet | Microsoft OLE DB Provider for Jet | Any | Microsoft.Jet.OLEDB.4.0 | Full path name of Excel file | - | Excel 5.0 | -
(1 ) This way of setting up a linked server forces the name of the linked server to be the same as the network name of the remote SQL Server. (2 ) Any indicates that the product name can be anything.

The data_source, location, provider_string, and catalog parameters identify the database(s) the linked server points to. If any of these parameters are NULL, the corresponding OLE DB initialization property is not set.

Note To use the Microsoft OLE DB Provider for SQL Server version 7.0 in SQL Server version 6.x, run the \Mssql7\Install\Instcat.sql script against the version 6.x. This script is essential for running distributed queries against a SQL Server 6.x server.

Permissions

Execute permissions default to members of the sysadmin and setupadmin fixed server roles.

Examples
A. Use the Microsoft OLE DB Provider for SQL Server

This example creates a linked server named SEATTLESales that uses the Microsoft OLE DB Provider for SQL Server.

USE master

GO

EXEC sp_addlinkedserver

    'SEATTLESales',

    N'SQL Server'

GO

B. Use the Microsoft OLE DB Provider for Jet

This example creates a linked server named SEATTLE Mktg.

Note This example assumes that both Microsoft Access and the sample Northwind database are installed and that the Northwind database resides in C:\MSOffice\Access\Samples.

USE master

GO

-- To use named parameters:

EXEC sp_addlinkedserver

    @server = 'SEATTLE Mktg',

    @provider = 'Microsoft.Jet.OLEDB.4.0',
    @srvproduct = 'OLE DB Provider for Jet',
    @datasrc = 'C:\MSOffice\Access\Samples\Northwind.mdb'

GO

-- OR to use no named parameters:

USE master

GO

EXEC sp_addlinkedserver
    'SEATTLE Mktg',
    'OLE DB Provider for Jet',
    'Microsoft.Jet.OLEDB.4.0',
    'C:\MSOffice\Access\Samples\Northwind.mdb'

GO

C. Use the Microsoft OLE DB Provider for Oracle

This example creates a linked server named LONDON Mktg that uses the Microsoft OLE DB Provider for Oracle and assumes that the SQL*Net alias for the Oracle database is MyServer.

USE master

GO

-- To use named parameters:

EXEC sp_addlinkedserver

    @server = 'LONDON Mktg',

    @srvproduct = 'Oracle',

    @provider = 'MSDAORA',

    @datasrc = 'MyServer'

GO

-- OR to use no named parameters:

USE master

GO

EXEC sp_addlinkedserver

    'LONDON Mktg',

    'Oracle',

    'MSDAORA',

    'MyServer'

GO

D. Use the Microsoft OLE DB Provider for ODBC with the data_source parameter

This example creates a linked server named SEATTLE Payroll that uses the Microsoft OLE DB Provider for ODBC and the data_source parameter.

Note The specified ODBC data source name must be defined as System DSN in the server before executing sp_addlinkedserver.

USE master

GO

-- To use named parameters:

EXEC sp_addlinkedserver

    @server = 'SEATTLE Payroll',

    @provider = 'MSDASQL',

    @datasrc = 'LocalServer'

GO

-- OR to use no named parameters:

USE master

GO

EXEC sp_addlinkedserver

    'SEATTLE Payroll',

    '',

    'MSDASQL',

    'LocalServer'

GO

E. Use the Microsoft OLE DB Provider for ODBC with the provider_string parameter

This example creates a linked server named LONDON Payroll that uses the Microsoft OLE DB Provider for ODBC and the provider_string parameter.

USE master

GO

-- To use named parameters:

EXEC sp_addlinkedserver

    @server = 'LONDON Payroll',

    @provider = 'MSDASQL',

    @provstr = 'DRIVER={SQL Server};SERVER=MyServer;UID=sa;PWD=;'

GO

-- OR to use no named parameters:

USE master

GO

EXEC sp_addlinkedserver

    'LONDON Payroll',

    '',

    'MSDASQL',

    NULL,

    NULL,

    'DRIVER={SQL Server};SERVER=MyServer;UID=sa;PWD=;'

GO

F. Use the Microsoft OLE DB Provider for Oracle

This example creates a linked server named OrclDB that uses the Microsoft OLE DB Provider for Oracle and replaces the OracleDB string (data_source) with the name of the SQL*Net alias.

USE master

GO

sp_addlinkedserver

    'OrclDB',

    'Oracle',

    'MSDAORA',

    'OracleDB'

GO

G. Use the Microsoft OLE DB Provider for Jet on an Excel Spreadsheet

To create a linked server definition using the Microsoft OLE DB Provider for Jet to access an Excel spreadsheet, first create a named range in Excel specifying the columns and rows of the Excel worksheet to select. The name of the range can then be referenced as a table name in a distributed query.

EXEC sp_addlinkedserver 'ExcelSource',

        'Jet 4.0',

        'Microsoft.Jet.OLEDB.4.0',

        'c:\MyData\DistExcl.xls',

        NULL,

        'Excel 5.0'

GO

H. Use the Microsoft OLE DB Provider for Indexing Service

This example creates a linked server and uses OPENQUERY to retrieve information from both the linked server and the file system enabled for Indexing Service.

EXEC sp_addlinkedserver FileSystem,

    'Index Server',

    'MSIDXS',

    'Web'

GO

USE pubs

GO

IF EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES

        WHERE TABLE_NAME = 'yEmployees')

    DROP TABLE yEmployees

GO

CREATE TABLE yEmployees

 (

  id       int         NOT NULL,

  lname    varchar(30) NOT NULL,

  fname    varchar(30) NOT NULL,

  salary   money,

  hiredate datetime

 )

GO

INSERT yEmployees VALUES

 (

  10,

  'Fuller',

  'Andrew',

  $60000,

  '9/12/98'

 )

GO

IF EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.VIEWS

        WHERE TABLE_NAME = 'DistribFiles')

    DROP VIEW DistribFiles

GO

CREATE VIEW DistribFiles

 AS

 SELECT *

 FROM OPENQUERY(FileSystem,

                 'SELECT Directory,

                    FileName,

                    DocAuthor,

                    Size,

                    Create,

                    Write

                  FROM SCOPE('' "c:\My Documents" '')

                  WHERE CONTAINS(''Distributed'') > 0

                    AND FileName LIKE ''%.doc%'' ')

 WHERE DATEPART(yy, Write) = 1998

GO

SELECT *

FROM DistribFiles

GO

SELECT Directory,

  FileName,

  DocAuthor,

  hiredate

FROM DistribFiles D, yEmployees E

WHERE D.DocAuthor = E.FName + ' ' + E.LName

GO

I.Use the Microsoft OLE DB Provider for Jet to access a text file

This example creates a linked server for directly accessing text files, without linking the files as tables in an Access .mdb file. The provider is Microsoft.Jet.OLEDB.4.0 and the provider string is 'Text'.

The data source is the full pathname of the directory that contains the text files. A schema.ini file, which describes the structure of the text files, must exist in the same directory as the text files. Refer to the Jet documentation for information about creating a schema.ini file.

--Create a linked server

EXEC sp_addlinkedserver txtsrv, 'Jet 4.0',
    'Microsoft.Jet.OLEDB.4.0',
    'c:\data\distqry',
    NULL,
    'Text'

GO

--Set up login mappings

EXEC sp_addlinkedsrvlogin txtsrv, FALSE, Admin, NULL

GO

--List the tables in the linked server

EXEC sp_tables_ex txtsrv

GO

--Query one of the tables: file1#txt

--using a 4-part name

SELECT *
FROM txtsrv...[file1#txt]

See Also
sp_addlinkedsrvlogin | sp_serveroption
sp_addserver | System Tables
sp_dropserver | System Stored Procedures


sp_addlinkedsrvlogin

Creates or updates a mapping between logins on the local server running Microsoft® SQL Server™ and remote logins on the linked server.

Syntax

sp_addlinkedsrvlogin [@rmtsrvname =] 'rmtsrvname'
[,[@useself =] 'useself']
[,[@locallogin =] 'locallogin']
[,[@rmtuser =] 'rmtuser']
[,[@rmtpassword =] 'rmtpassword']

Arguments
[@rmtsrvname =] 'rmtsrvname'
Is the name of a linked server that the login mapping applies to. rmtsrvname is sysname, with no default.
[@useself =] 'useself'
Determines the name of the login used to connect to the remote server. useself is varchar(8), with a default of TRUE. A value of true specifies that SQL Server authenticated logins use their own credentials to connect to rmtsrvname, with the rmtuser and rmtpassword arguments being ignored. false specifies that the rmtuser and rmtpassword arguments are used to connect to rmtsrvname for the specified locallogin. If rmtuser and rmtpassword are also set to NULL, no login or password is used to connect to the linked server. true for useself is invalid for a Windows NT authenticated login unless the Microsoft Windows NT® environment supports security account delegation and the provider supports Windows NT Authentication (in which case creating a mapping with value of true is no longer required, but still valid).
[@locallogin =] 'locallogin'
Is a login on the local server. locallogin is sysname, with a default of NULL. NULL specifies that this entry applies to all local logins that connect to rmtsrvname. If not NULL, locallogin can be a SQL Server login or a Windows NT user. The Windows NT user must have been granted access to SQL Server either directly, or through its membership in a Windows NT group that has been granted access.
[@rmtuser =] 'rmtuser'
Is the username used to connect to rmtsrvname when useself is false. rmtuser is sysname, with a default of NULL.
[@rmtpassword =] 'rmtpassword'
Is the password associated with rmtuser. rmtpassword is sysname, with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Remarks

When a user logs in to the local server and executes a distributed query that accesses a table on the linked server, the local server must log in to the linked server on behalf of the user to access that table. Use sp_addlinkedsrvlogin to specify the login credentials that the local server uses to log in to the linked server.

A default mapping between all logins on the local server and remote logins on the linked server is automatically created by executing sp_addlinkedserver. The default mapping states that SQL Server uses the local login’s user credentials when connecting to the linked server on behalf of the login (equivalent to executing sp_addlinkedsrvlogin with @useself set to true for the linked server). Use sp_addlinkedsrvlogin only to change the default mapping or to add new mappings for specific local logins. To delete the default mapping or any other mapping, use sp_droplinkedsrvlogin.

Rather than having to use sp_addlinkedsrvlogin to create a predetermined login mapping, SQL Server can automatically use the Windows NT security credentials (Windows NT username and password) of a user issuing the query to connect to a linked server when all these conditions exist:

  • A user is connected to SQL Server using Windows NT Authentication Mode.
  • Security account delegation is available on the client and sending server.
  • The provider supports Windows NT Authentication Mode (for example, SQL Server running on Windows NT).

After the authentication has been performed by the linked server using the mappings defined by executing sp_addlinkedsrvlogin on the local SQL Server, the permissions on individual objects in the remote database are determined by the linked server, not the local server.

sp_addlinkedsrvlogin cannot be executed from within a user-defined transaction.

Permissions

Only members of the sysadmin and securityadmin fixed server roles can execute sp_addlinkedsrvlogin.

Examples

A. Connect all local logins to the linked server using their own user credentials

This example creates a mapping to ensure that all logins to the local server connect through to the linked server Accounts using their own user credentials.

EXEC sp_addlinkedsrvlogin 'Accounts'

Or

EXEC sp_addlinkedsrvlogin 'Accounts', 'true'

B. Connect all local logins to the linked server using a specified user and password

This example creates a mapping to ensure that all logins to the local server connect through to the linked server Accounts using the same login SQLUser and password Password.

EXEC sp_addlinkedsrvlogin 'Accounts', 'false', NULL, 'SQLUser', 'Password'

C. Connect all local logins to the linked server without using any user credentials

This example creates a mapping to ensure that all logins to the local server connect through to the linked server mydb without using a login or password (mydb does not require a login or password).

EXEC sp_addlinkedsrvlogin 'mydb', 'false', NULL, NULL, NULL

Or

EXEC sp_addlinkedsrvlogin 'mydb', 'false'

D. Connects a specific login to the linked server using different user credentials

    This example creates a mapping to ensure that only the Windows NT user Domain\Mary connects through to the linked server Accounts using the login MaryP and password NewPassword.

    EXEC sp_addlinkedsrvlogin 'Accounts', 'false', 'Domain\Mary', 'MaryP', 'NewPassword'

    E. Connects a specific login to an Excel spreadsheet (the linked server)

    This example first creates a linked server named ExcelSource, defined as the Microsoft Excel spreadsheet DistExcl.xls, and then creates a mapping to allow the SQL Server login sa to connect through to ExcelSource using the Excel login Admin and no password.

    EXEC sp_addlinkedserver 'ExcelSource', 'Jet 4.0',

            'Microsoft.Jet.OLEDB.4.0',

            'c:\MyData\DistExcl.xls',

            NULL,

            'Excel 5.0'

    GO

    EXEC sp_addlinkedsrvlogin 'ExcelSource', 'false', 'sa', 'Admin', NULL

    See Also
    sp_addlinkedserver | System Stored Procedures
sp_droplinkedsrvlogin |


sp_add_log_file_recover_suspect_db

Adds a log file to a file group when recovery cannot complete on a database due to an “insufficient log space” (9002) error. After the file is added, this stored procedure turns-off the suspect setting and completes the recovery of the database. The parameters are the same as those for ALTER DATABASE ADD LOG FILE.

Important This stored procedure should only be used as described in the Troubleshooting Recovery section.

Syntax

sp_add_log_file_recover_suspect_db [@dbName = ]'database',
[@name = ] 'logical_file_name',
[@filename =] 'os_file_name',
[@size =] 'size',
[@maxsize =] 'max_size',
[@filegrowth =] 'growth_increment'

Arguments
[@dbName = ]'database'
Is the name of the database. database is sysname with no default.
[@name = ] 'logical_file_name'
Is the name used in Microsoft SQL Server when referencing the file. The name must be unique in the server. logical_file_name is nvarchar(260) with no default.
[@filename =] 'os_file_name'
Is the path and file name used by the operating system for the file. The file must reside in the server in which SQL Server is installed. os_file_name is nvarchar(260) with no default.
[@size =] 'size'
Is the initial size of the file. The MB and KB suffixes can be used to specify megabytes or kilobytes. The default is MB. Specify a whole number; do not include a decimal. The minimum value for size is 512 KB, and the default if size is not specified is 1 MB. size is nvarchar(20) with a default of NULL.
[@maxsize =] 'max_size'
Is the maximum size to which the file can grow. The MB and KB suffixes can be used to specify megabytes or kilobytes. The default is MB. Specify a whole number, do not include a decimal. If max_size is not specified, the file will grow until the disk is full. The Microsoft Windows NT® application log warns an administrator when a disk is about to become full. max_size is nvarchar(20) with a default of NULL.
[@filegrowth =] 'growth_increment'
Is the amount of space added to the file each time new space is needed. A value of 0 indicates no growth. The value can be specified in MB, KB, or %. Specify a whole number; do not include a decimal. When % is specified, the growth increment is the specified percentage of the size of the file at the time the increment occurs. If a number is specified without an MB, KB, or % suffix, the default is MB. The default value if growth_increment is not specified is 10%, and the minimum value is 64 KB. The size specified is rounded to the nearest 64 KB. growth_increment is nvarchar(20) with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

This stored procedure should only be used as described in Troubleshooting Recovery.

Permissions

Execute permissions default to members of the db_owner and db_ddladmin fixed database roles, and to members of the sysadmin and dbcreator fixed server roles. These permissions are not transferable.

Example

In this example database db1 was marked suspect during recovery due to insufficient log space (error 9002).

sp_add_log_file_recover_suspect_db db1, logfile2,
    ‘c:\mssql7\data\db1_logfile2.ldf’, 1MB

See Also

sp_add_data_file_recover_suspect_db

ALTER DATABASE


sp_addlogin

Creates a new Microsoft® SQL Server™ login that allows a user to connect to a server running SQL Server using SQL Server Authentication.

Syntax

sp_addlogin [@loginame =] 'login'
[,[@passwd =] 'password']
 [,[@defdb =] 'database']
[,[@deflanguage =] 'language']
[,[@sid =] 'sid']
[,[@encryptopt =] 'encryption_option']

Arguments
[@loginame =] 'login'
Is the name of the login. login is sysname, with no default.
[@passwd =] 'password'
Is the login password. password is sysname, with a default of NULL. After sp_addlogin has been executed, the password is encrypted and stored in the system tables.
[@defdb =] 'database'
Is the default database of the login (the database the login is connected to after logging in). database is sysname, with a default of master.
[@deflanguage =] 'language'
Is the default language assigned when a user logs in to SQL Server. language is sysname, with a default of NULL. If language is not specified, the server’s default language (defined by the sp_configure configuration variable default language) is used.
[@sid =] 'sid'
Is the security identification number (SID). sid is varbinary(16), with a default of NULL. If sid is NULL, the system generates a SID for the new login Specifying a value other than NULL (the number must not already exist). SID is useful, for example, when you are scripting or moving SQL Server logins from one server to another and you want the logins to have the same SID between servers.
[@encryptopt =] 'encryption_option'
Specifies whether the password is encrypted when stored in the system tables. encryption_option is varchar(20), and can be one of these values.

Value | Description
NULL | The password is encrypted. This is the default.
skip_encryption | The password is not encrypted.
skip_encryption_old | The password is not encrypted. The supplied password was encrypted by an earlier version of SQL Server. This option is provided for upgrade purposes only.

Return Code Values

0 (success) or 1 (failure)

Remarks

SQL Server logins and passwords can contain from 1 to 128 characters, including letters, symbols, and numbers. However, logins cannot:

  • Contain a backslash character (\).
  • Be a reserved login name, for example sa or public, or already exist.
  • Be NULL or an empty string (‘‘).

If the name of a default database is supplied, you can connect to the specified database without executing the USE statement. However, you cannot use the default database until given access to that database by the database owner (using sp_adduser or sp_addrolemember) or sp_addrole.

The SID number is the unique Microsoft Windows NT® user identification number. The SID is guaranteed to be unique (it is a GUID) for each user in a Windows NT domain. SQL Server automatically uses the Windows NT SID to identify Windows NT users and groups, and generates a SID for SQL Server logins.

Using skip_encryption to suppress password encryption is useful if the password is already in encrypted form when the login is added to SQL Server. If the password was encrypted by an earlier version of SQL Server, use skip_encryption_old.

sp_addlogin cannot be executed from within a user-defined transaction.

The table shows several stored procedures that can be used in conjunction with sp_addlogin.

Stored procedure | Description
sp_grantlogin | Adds a Windows NT user or group.
sp_password | Changes a user’s password.
sp_defaultdb | Changes a user’s default database.
sp_defaultlanguage | Changes a user’s default language.

Permissions

Only members of the sysadmin and securityadmin fixed server roles can execute sp_addlogin.

Examples
A. Create a login ID with no password and master default database

This example creates a SQL Server login for the user Victoria, without specifying a password or default database.

EXEC sp_addlogin 'Victoria'

B. Create a login ID and default database

This example creates a SQL Server login for the user Albert, with a password of food and a default database of corporate.

EXEC sp_addlogin 'Albert', 'food', 'corporate'

C. Create a login ID with a different default language

This example creates a SQL Server login for the user Claire Picard, with a password of caniche, a default database of public_db, and a default language of French.

EXEC sp_addlogin 'Claire Picard', 'caniche', 'public_db', 'french'

D. Create a login ID with a specific SID

This example creates a SQL Server login for the user Michael, with a password of chocolate, a default database of pubs, a default language of us_english, and a SID of 0x12345678.

EXEC sp_addlogin 'Michael', 'chocolate', 'pubs', 'us_english', '0x12345678'

E. Create a login ID and do not encrypt the password

This example creates a SQL Server login for the user Margaret with a password of Rose on Server1, extracts the encrypted password, and then adds the login for the user Margaret to Server2 using the previously encrypted password, but does not further encrypt the password. User Margaret can then log in to Server2 using the password Rose.

-- Server1

EXEC sp_addlogin Margaret, Rose

--Results

New login created.

-- Extract encrypted password for Margaret

SELECT CONVERT(VARBINARY(32), password)

    FROM syslogins

    WHERE name = 'Margaret'

--Results

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

0x2131214A212B57304F5A552A3D513453

(1 row(s) affected)

-- Server2

EXEC sp_addlogin 'Margaret', 0x2131214A212B57304F5A552A3D513453, @encryptopt = 'skip_encryption'

See Also
sp_addrole | sp_grantlogin
sp_addrolemember | sp_helpuser
sp_adduser | sp_password
sp_defaultdb | sp_revokelogin
sp_defaultlanguage | xp_logininfo
sp_droplogin |


sp_addmergearticle

Adds an article to an existing merge publication.

Syntax

sp_addmergearticle [@publication =] 'publication', [@article =] 'article',
[@source_object =] 'source_object'
[,[@type =] 'type']
[,[@description =] 'description']
[,[@column_tracking =] 'column_tracking'] [,[@status =] 'status']
[,[@pre_creation_cmd =] 'pre_creation_cmd']
[,[@creation_script =] 'creation_script']
[,[@schema_option =] schema_option]
[,[@subset_filterclause =] 'subset_filterclause']
[,[@article_resolver =] 'article_resolver']
[,[@resolver_info =] 'resolver_info']
[,[@source_owner =] 'source_owner']

Arguments
[@publication =] 'publication'
Is the name of the publication that contains the article. publication is sysname, with no default.
[@article =] 'article'
Is the name of the article. article is sysname, with no default. article must be local, conform to the rules for identifiers, and be a table. article cannot be a view or another database object.
[@source_object =] 'source_object'
Is the name of the source table from which to add the article. source_object is sysname, with no default.
[@type =] 'type'
Is the type of article. type is sysname, with a default of table. All other types are reserved for future use.
[@description =] 'description'
Is a description of the article. description is nvarchar(255), with a default of NULL.
[@column_tracking =] 'column_tracking'
Is the setting for column-level tracking. column_tracking is nvarchar(10), with a default of FALSE. true implements column tracking. false turns off column tracking. If the table is already published using merge replication, you must use the same column tracking value.
[@status =] 'status'
Is the status of the article. status is nvarchar(10), with a default of unsynced. If active, the initial processing script to publish the table is run. If unsynced, the initial processing script to publish the table is run at the next time the Snapshot Agent runs.
[@pre_creation_cmd =] 'pre_creation_cmd'
Is a precreation method. pre_creation_cmd is nvarchar(10), and can be one of these values.

Value | Description
none | If the table already exists at the Subscriber, no action is taken.
delete | Issues a delete based on the WHERE clause in the subset filter.
drop (default) | Drops the table before re-creating it.
truncate | Same as delete, but deletes pages instead of rows. Does not take a WHERE clause, however.

[@creation_script =] 'creation_script'
Is the optional precreation script for the article. creation_script is nvarchar(255), with a default of NULL.
[@schema_option =] schema_option
Is a bitmap of the schema generation option for the given article. schema_option is binary(8), and can be one of these values.

Value | Description
0x00 | Disables scripting by the Snapshot Agent and uses the provided CreationScript.
0x01 | Generates the object creation (CREATE TABLE, CREATE PROCEDURE, and so on).
0x10 | Generates a corresponding clustered index.
0x20 | Converts user-defined data types to base data types.
0x40 | Generates corresponding nonclustered index(es).
0x80 | Includes declared referential integrity on the primary keys.
0xf1 (default) | Generates the CREATE TABLE, creates clustered indexes, creates nonclustered index(es), converts user-defined data types to base data types.
0x01 | Default for stored procedure articles.

[@subset_filterclause =] 'subset_filterclause'
Is a WHERE clause specifying the horizontal filtering. subset_filterclause is of nvarchar(2000), with a default of an empty string.
[@article_resolver =] 'article_resolver'
Is the custom resolver for the article. article_resolver is varchar(255), with a default of NULL. If custom resolver, SQL Server uses the specified resolver instead of the system-supplied resolver. Use sp_enumcustomresolvers to enumerate the list of available custom resolvers.
[@resolver_info =] 'resolver_info']
Is the name of the stored procedure used as a custom resolver. resolver_info is sysname, with a default of NULL.
[@source_owner =] 'source_owner']
Is the name of the owner of the source_object. source_owner is sysname, with a default of NULL. If NULL, the current user is assumed to be the owner.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_addmergearticle is used in merge replication.

By default, the priorities defined for the Subscriber are used in resolving conflicts.

Permissions

Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_addmergearticle.

See Also
sp_changemergearticle | sp_helpmergearticle
sp_dropmergearticle | System Stored Procedures


sp_addmergefilter

Adds a new merge filter for the purpose of creating a partition based on a join with another table.

Syntax

sp_ addmergefilter [@publication =] 'publication',
[@article =] 'article', [@filtername =] 'filtername',
[@join_articlename =] 'join_articlename'
[,[@join_filterclause =] join_filterclause]
[,[@join_unique_key =] join_unique_key]

Arguments
[@publication =] 'publication'
Is the name of the publication. publication is sysname, with no default.
[@article =] 'article'
Is the name of the article. article is sysname, with no default.
[@filtername =] 'filtername'
Is the name of the filter. filtername is a required parameter. filtername is sysname, with no default.
[@join_articlename =] 'join_articlename'
Is the article name of the join table. join_articlename is nvarchar(258), with no default. The article must be in the publication given by publication.
[@join_filterclause =] join_filterclause
Is the filter clause qualifying the join. join_ filterclause is nvarchar(2000), with a default of an empty string. join_filterclause defines only Boolean filters in this stored procedure.
[@join_unique_key =] join_unique_key
Is whether the join is on a unique key. join_unique_key is int, with a default of 0. 0 indicates a nonunique key. 1 indicates a unique key in @join_articlename.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_addmergefilter is used in merge replication.

This option is commonly used for an article that has a foreign key reference to a published primary key table, and the primary key table has a filter defined in its article. The subset of primary key rows is used to determine the foreign key rows that are replicated to the Subscriber.

Permissions

Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_ addmergefilter.

See Also
sp_changemergefilter | sp_helpmergefilter
sp_dropmergefilter | System Stored Procedures


sp_addmergepublication

Creates a new merge publication.

Syntax

sp_addmergepublication [@publication =] 'publication'
[,[@description =] 'description' [,[@retention =] retention]
[,[@sync_mode =] 'sync_mode', [@allow_push =] 'allow_push']
[,[@allow_pull =] 'allow_pull'] [@allow_anonymous =] 'allow_anonymous']
[,[@enabled_for_internet =] 'enabled_for_internet']
[,[@centralized_conflicts =] 'centralized_conflicts']
[,[@dynamic_filters =] 'dynamic_filters']

Arguments
[@publication =] 'publication'
Is the name of the merge publication to create. publication is sysname, with no default, and must not be the keyword ALL. The name of the publication must be unique within the database.
[@description =] 'description'
Is the publication description. description is nvarchar(255), with a default of NULL.
[@retention =] retention
Is the amount of change, in days, to save for the given publication. retention is int, with a default of 60 days. If the subscription does not merge within the retention period, the subscription expires and is removed.
[@sync_mode =] 'sync_mode'
Is the mode of the synchronization. sync_mode is nvarchar(10), with a default of native. If native, native-mode bulk copy program output of all tables is produced. If character, character-mode bulk copy program output of all tables is produced.
[@allow_push =] 'allow_push'
Is whether push subscriptions can be created for the given publication. allow_push is nvarchar(5), with a default of TRUE, which allows push subscriptions on the publication.
[@allow_pull =] 'allow_pull'
Is whether pull subscriptions can be created for the given publication. allow_pull is nvarchar(5), with a default of TRUE, which allows pull subscriptions on the publication.
[@allow_anonymous =] 'allow_anonymous'
Is whether anonymous subscriptions can be created for the given publication. allow_anonymous is nvarchar(5), with a default of FALSE, which does not allow anonymous subscriptions on the publication.
[@enabled_for_internet =] 'enabled_for_internet'
Is whether the publication is enabled for the Internet. enabled_for_internet is nvarchar(5), with a default of FALSE. If true, the synchronization files for the publication are put into the \Repldata\Ftp directory. The user must set up the Ftp directory.
[@centralized_conflicts =] 'centralized_conflicts'
Is whether conflict records are stored on the given Publisher. centralized_conflicts is nvarchar(5), with a default of TRUE. If true, conflict records are stored at the Publisher. If false, conflict records are stored at each Subscriber.
[@dynamic_filters =] 'dynamic_filters'
Is whether the publication is filtered on a dynamic clause. dynamic_filter is nvarchar(5), with a default of FALSE.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_addmergepublication is used in merge replication.

Permissions

Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_addmergepublication.

See Also
sp_changemergepublication | sp_helpmergepublication
sp_dropmergepublication | System Stored Procedures


sp_addmergepullsubscription

Adds a merge subscription of type pull.

Syntax

sp_addmergepullsubscription [@publication =] 'publication'
[,[@publisher =] 'publisher'] [,[@publisher_db =] 'publisher_db']
[,[@subscriber_type =] 'subscriber_type']
[,[@subscription_priority =] subscription_priority]
[,[@sync_type =] 'sync_type'] [,[@description =] 'description']

Arguments
[@publication =] 'publication'
Is the name of the publication. publication is sysname, with no default.
[@publisher =] 'publisher'
Is the name of the Publisher. publisher is sysname, with a default of the local server name. The Publisher must be a valid server.
[@publisher_db =] 'publisher_db
Is the name of the Publisher database. publisher_db is sysname, with no valid default.
[@subscriber_type =] 'subscriber_type'
Is the type of Subscriber. subscriber_type is nvarchar(15), and can be one of these values.

Value | Description
1 | Global
2 (default) | Local
3 | Anonymous

[@subscription_priority =] subscription_priority
Is the subscription priority. subscription_priority is real, with a default of NULL. For local and anonymous subscriptions, the priority is 0.0. The priority is used by the default resolver to pick a winner when conflicts are detected.
[@sync_type =] 'sync_type'
Is the subscription synchronization type. sync_type is nvarchar(15), with a default of automatic. Can be automatic or nosync. If automatic, the schema and initial data are transferred to the Subscriber first. If nosync, it is assumed the Subscriber already has the schema and initial data.
[@description =] 'description'
Is a brief description of this pull subscription. description is nvarchar(255), with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_addmergepullsubscription is used for merge replication.

sp_addmergepullsubscription implements similar functionality to sp_addmergesubscription regarding pull subscriptions, except that it does not create an agent for this subscription. The current server name and current database name are assumed to be subscriber and subscriber_db, and they do not appear in the parameter list.

Permissions

Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_addmergepullsubscription.

See Also
sp_changemergepullsubscription | sp_helpmergepullsubscription
sp_dropmergepullsubscription | System Stored Procedures


sp_addmergepullsubscription_agent

Adds an agent for a merge pull subscription at the Subscriber.

Syntax

sp_addmergepullsubscription_agent [[@name =] 'name']
{,[@publisher =] 'publisher', [@publisher_db =] 'publisher_db',
[@publication =] 'publication'}
[,[@publisher_security_mode =] publisher_security_mode]
[,[@publisher_login =] 'publisher_login']
[,[@publisher_password =] 'publisher_password']
[,[@publisher_encrypted_password =] publisher_encrypted_password]
[,[@subscriber =] 'subscriber']
[,[@subscriber_db =] 'subscriber_db']
[,[@subscriber_security_mode =] subscriber_security_mode]
[,[@subscriber_login =] 'subscriber_login']
[,[@subscriber_password =] 'subscriber_password']
[,[@distributor =] 'distributor']
[,[@distributor_security_mode =] distributor_security_mode]
[,[@distributor_login =] 'distributor_login']
[,[@distributor_password =] 'distributor_password']
[,[@encrypted_password =] encrypted_password]
[,[@frequency_type =] frequency_type]
[,[@frequency_interval =] frequency_interval]
[,[@frequency_relative_interval =] frequency_relative_interval]
[,[@frequency_recurrence_factor =] frequency_recurrence_factor]
[,[@frequency_subday =] frequency_subday]
[,[@frequency_subday_interval =] frequency_subday_interva]
[,[@active_start_time_of_day =] active_start_time_of_day]
[,[@active_end_time_of_day =] active_end_time_of_day]
[,[@active_start_date =] active_start_date]
[,[@active_end_date =] active_end_date]
[,[@optional_command_line =] 'optional_command_line']
[,[@merge_jobid =] merge_jobid]
[,[@enabled_for_syncmgr =] 'enabled_for_syncmgr']
[,[@ftp_address =] 'ftp_address']
[,[@ftp_port =] ftp_port]
[,[@ftp_login =] 'ftp_login']
[,[@ftp_password =] 'ftp_password']

Arguments
[@name =] 'name'
Is the name of the agent. name is sysname, with a default of NULL.
[@publisher =] 'publisher'
Is the name of the Publisher server. publisher is sysname, with no default.
[@publisher_db =] 'publisher_db'
Is the name of the Publisher database. publisher_db is sysname, with no default.
[@publication =] 'publication'
Is the name of the publication. publication is sysname, with no default.
[@publisher_security_mode =] publisher_security_mode
Is the security mode at the Publisher. publisher_security_mode is int, with a default of 1.
[@publisher_login =] 'publisher_login'
Is the login used at the Publisher. publisher_login is sysname, with a default of NULL.
[@publisher_password =] 'publisher_password'
Is the password used at the Publisher. publisher_password is sysname, with a default of NULL.
[@publisher_encrypted_password =] publisher_encrypted_password
Is whether the password is stored in encrypted format. publisher_encrypted_password is bit, with a default of 0.
[@subscriber =] 'subscriber'
Is the name of the Subscriber. subscriber is sysname, with a default of NULL.
[@subscriber_db =] 'subscriber_db'
Is the name of the subscription database. subscriber_db is sysname, with a default of NULL.
[@subscriber_security_mode =] subscriber_security_mode
Is the security mode of the Subscriber. subscriber_security_mode is int, with a default of 1. 0 specifies SQL Server Authentication. 1 specifiies Windows NT Authentication.
[@subscriber_login =] 'subscriber_login'
Is the Subscriber login. subscriber_login is required if subscriber_security_mode is set to 0. subscriber_login is sysname, with a default of NULL.
[@subscriber_password =] 'subscriber_password'
Is the Subscriber password. subscriber_password is required if subscriber_security_mode is set to 0. subscriber_password is sysname, with a default of NULL.
[@distributor =] 'distributor'
Is the name of the Distributor. distributor is sysname, with a default of publisher; that is, the Publisher is also the Distributor.
[@distributor_security_mode =] distributor_security_mode
Is the security mode of the Distributor. distributor_security_mode is int, with a default of 0. 0 specifies SQL Server Authentication. 1 specifies Windows NT Authentication.
[@distributor_login =] 'distributor_login'
Is the Distributor login. distributor_login is required if distributor_security_mode is set to 0 . distributor_login is sysname, with a default of sa.
[@distributor_password =] 'distributor_password'
Is the Distributor password. distributor_password is required if distributor_security_mode is set to 0. distributor_password is sysname, with a default of NULL.
[@encrypted_password =] encrypted_password
Is whether the password is encrypted. encrypted_password is bit, with a default of 0. This is used in generating replication scripts.
[@frequency_type =] frequency_type
Is the frequency with which to schedule the Distribution Agent. frequency_type is int, and can be one of these values.

Value | Description
1 | One time
2 | On demand
4 | Daily
8 | Weekly
16 | Monthly
32 | Monthly relative
64 | Autostart
124 | Recurring
NULL (default)

[@frequency_interval =] frequency_interval
The days that the Distribution Agent runs. frequency_interval is int, and can be one of these values.

Value | Description
1 | Sunday
2 | Monday
3 | Tuesday
4 | Wednesday
5 | Thursday
6 | Friday
7 | Saturday
8 | Day
9 | Weekdays
10 | Weekend days
NULL (default)

[@frequency_relative_interval =] frequency_relative_interval
Is the date of the Distribution Agent. This parameter is used when frequency_type is set to 32 (monthly relative). frequency_relative_interval is int, and can be one of these values.

Value | Description
1 | First
2 | Second
4 | Third
8 | Fourth
16 | Last
NULL (default)

[@frequency_recurrence_factor =] frequency_recurrence_factor
Is the recurrence factor used by frequency_type. frequency_recurrence_factor is int, with a default of NULL.
[@frequency_subday =] frequency_subday
Is how often to reschedule during the defined period. frequency_subday is int, and can be one of these values.

Value | Description
1 | Once
2 | Second
4 | Minute
8 | Hour
NULL (default)

[@frequency_subday_interval =] frequency_subday_interval
Is the interval for frequency_subday. frequency_subday_interval is int, with a default of NULL.
[@active_start_time_of_day =] active_start_time_of_day
Is the time of day when the Distribution Agent is first scheduled, formatted as HHMMSS. active_start_time_of_day is int, with a default of NULL.
[@active_end_time_of_day =] active_end_time_of_day
Is the time of day when the Distribution Agent stops being scheduled, formatted as HHMMSS. active_end_time_of_day is int, with a default of NULL.
[@active_start_date =] active_start_date
Is the date when the Distribution Agent is first scheduled, formatted as YYYYMMDD. active_start_date is int, with a default of NULL.
[@active_end_date =] active_end_date
Is the date when the Distribution Agent stops being scheduled, formatted as YYYYMMDD. active_end_date is int, with a default of NULL.
[@optional_command_line =] 'optional_command_line'
Is an optional command prompt that is supplied to the Distribution Agent. For example, -DefinitionFile C:\Distdef.txt or -CommitBatchSize 10. optional_command_line is nvarchar(255), with a default of NULL.
[@merge_jobid =] merge_jobid
Is the output parameter for the job ID. merge_jobid is binary(16), with a default of NULL.
[@enabled_for_syncmgr =] 'enabled_for_syncmgr'
Is whether the subscription can be synchronized through the Microsoft Synchronization Manager. enabled_for_syncmgr is nvarchar(5), with a default of false. If false, the subscription is not registered with Synchronization Manager. If true, the subscription is registered with Synchronization Manager and can be synchronized without launching SQL Server Enterprise Manager.
[@ftp_address =] 'ftp_address'
Is the network address of the FTP service for the Distributor. ftp_address is sysname, with a default of NULL.
[@ftp_port =] ftp_port
Is the port number of the FTP service for the Distributor. ftp_port is int, with a default of NULL.
[@ftp_login =] 'ftp_login'
Is the username used to connect to the FTP service. ftp_login is sysname, with a default of NULL.
[@ftp_password =] 'ftp_password'
Is the user password used to connect to the FTP service. ftp_password is sysname, with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_addmergepullsubscription_agent is used in merge replication.

sp_addmergepullsubscription_agent is symmetric with sp_addsubsubscriber_agent.

Permissions

Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_addmergepullsubscription_agent.

See Also
System Stored Procedures


sp_addmergesubscription

Creates a push or pull merge subscription.

Syntax

sp_addmergesubscription [@publication =] 'publication'
[,[@subscriber =] 'subscriber'] [,[@subscriber_db =] 'subscriber_db']
[,[@subscription_type =] 'subscription_type']
[,[@subscriber_type =] 'subscriber_type']
[,[@subscription_priority =] subscription_priority]
[,[@sync_type =] 'sync_type']
[,[@frequency_type =] frequency_type]
[,[@frequency_interval =] frequency_interval]
[,[@frequency_relative_interval =] frequency_relative_interval]
[,[@frequency_recurrence_factor =] frequency_recurrence_factor]
[,[@frequency_subday =] frequency_subday]
[,[@frequency_subday_interval =] frequency_subday_interval]
[,[@active_start_time_of_day =] active_start_time_of_day]
[,[@active_end_time_of_day =] active_end_time_of_day]
[,[@active_start_date =] active_start_date]
[,[@active_end_date =] active_end_date]
[,[@optional_command_line =] 'optional_command_line']
[,[@description =] 'description']
[,[@enabled_for_syncmgr =] 'enabled_for_syncmgr']

Arguments
[@publication =] 'publication'
Is the name of the publication. publication is sysname, with no default. The publication must already exist.
[@subscriber =] 'subscriber'
Is the name of the Subscriber. subscriber is sysname, with a default of NULL.
[@subscriber_db =] 'subscriber_db'
Is the name of the subscription database. subscriber_db is sysname, with a default of NULL.
[@subscription_type =] 'subscription_type'
Is the type of subscription. subscription_type is nvarchar(15), with a default of push. If push, then a push subscription is added and the Merge Agent is added at the Distributor. If pull, then a pull subscription is added without adding a Merge Agent at the Distributor.
[@subscriber_type =] 'subscriber_type'
Is the type of Subscriber. subscriber_type is nvarchar(15), and can be one of these values.

Value | Description
local (default) | Subscriber known only to the Publisher
global | Subscriber known to all servers
anonymous | Subscriber known only to itself

[@subscription_priority =] subscription_priority
Is a number indicating the priority for the subscription. subscription_priority is real, with a default of NULL. For local and anonymous subscriptions, the priority is 0.0. For global subscriptions, the priority must be less than 100.0.
[@sync_type =] 'sync_type']
Is the subscription sync type. sync_type is nvarchar(15), with a default of automatic. Can be automatic or nosync. If automatic, the schema and initial data are transferred to the Subscriber first. If nosync, it is assumed the Subscriber already has the schema and initial data.
[@frequency_type =] frequency_type
Is a value indicating when the Merge Agent will run. frequency_type is int, and can be one of these values.

Value | Description
1 | Once
4 | Daily
8 | Weekly
10 | Monthly
20 | Monthly, relative to the frequency interval
40 | When SQL Server Agent starts
NULL (default)

[@frequency_interval =] frequency_interval
The days that the Merge Agent runs. frequency_interval is int, and can be one of these values.

Value | Description
1 | Sunday
2 | Monday
3 | Tuesday
4 | Wednesday
5 | Thursday
6 | Friday
7 | Saturday
8 | Day
9 | Weekdays
10 | Weekend days
NULL (default)

[@frequency_relative_interval =] frequency_relative_interval
Is the scheduled merge occurrence of the frequency interval in each month. frequency_relative_interval is int, and can be one of these values.

Value | Description
1 | First
2 | Second
4 | Third
8 | Fourth
16 | Last
NULL (default)

[@frequency_recurrence_factor =] frequency_recurrence_factor
Is the recurrence factor used by frequency_type. frequency_recurrence_factor is int, with a default of NULL.
[@frequency_subday =] frequency_subday
Is the units for freq_subday_interval. frequency_subday is int, and can be one of these values.

Value | Description
1 | Once
2 | Second
4 (default) | Minute
8 | Hour

[@frequency_subday_interval =] frequency_subday_interval
Is the frequency for frequency_subday to occur between each merge. frequency_subday_interval is int, with a default of NULL.
[@active_start_time_of_day =] active_start_time_of_day
Is the time of day when the Merge Agent is first scheduled, formatted as HHMMSS. active_start_time_of_day is int, with a default of NULL.
[@active_end_time_of_day =] active_end_time_of_day
Is the time of day when the Merge Agent stops being scheduled, formatted as HHMMSS. active_end_time_of_day is int, with a default of NULL.
[@active_start_date =] active_start_date
Is the date when the Merge Agent is first scheduled, formatted as YYYYMMDD. active_start_date is int, with a default of NULL.
[@active_end_date =] active_end_date
Is the date when the Merge Agent stops being scheduled, formatted as YYYYMMDD. active_end_date is int, with a default of NULL.
[@optional_command_line =] 'optional_command_line'
Is the optional command prompt to execute. optional_command_line is nvarchar(4000), with a default of NULL. This parameter is used to add a command that captures the output and saves it to a file or to specify a configuration file or attribute.
[@description =] 'description'
Is a brief description of this merge subscription. description is nvarchar(255), with a default of NULL.
[@enabled_for_syncmgr =] 'enabled_for_syncmgr'
Is whether the subscription can be synchronized through the Microsoft Synchronization Manager. enabled_for_syncmgr is nvarchar(5), with a default of false. If false, the subscription is not registered with Synchronization Manager. If true, the subscription is registered with Synchronization Manager and can be synchronized without launching SQL Server Enterprise Manager.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_addmergesubscription is used in merge replication.

Permissions

Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_addmergesubscription.

See Also
sp_changemergesubscription | sp_helpmergesubscription
sp_dropmergesubscription | System Stored Procedures


sp_addmessage

Adds a new error message to the sysmessages table.

Syntax

sp_addmessage [@msgnum =] msg_id,
[@severity =] severity,
[@msgtext =] 'msg'
[, [@lang =] 'language']
[, [@with_log =] 'with_log']
[, [@replace =] 'replace']

Arguments
[@msgnum =] msg_id
Is the ID of the message. msg_id is int, with a default of NULL. Acceptable values for user-defined error messages start with 50001. The combination of msg_id and language must be unique; an error is returned if the ID already exists for the specified language.
[@severity =] severity
Is the severity level of the error. severity is smallint, with a default of NULL. Valid levels are 1 through 25. Only the system administrator can add a message with a severity level of 19 through 25.
[@msgtext =] 'msg'
Is the text of the error message. msg is nvarchar(255), with a default of NULL.
[@lang =] 'language'
Is the language for this message. language is sysname, with a default of NULL. Because multiple languages can be installed on the same server, language specifies the language in which each message is written. When language is omitted, the language is the default language for the session.
[@with_log =] 'with_log'
Is whether the message is to be written to the Microsoft® Windows NT® application log when it occurs. with_log is varchar(5), with a default of FALSE. If true, the error is always written to the Windows NT application log. If false, the error is not always written to the Windows NT application log but can be written, depending on how the error was raised. Only members of the sysadmin server role can use this option.

Note If a message is written to the Windows NT application log, it is also written to the Microsoft SQL Server™ error log file.

[@replace =] 'replace'
If specified as the string REPLACE, an existing error message is overwritten with new message text and severity level. replace is varchar(7), with a default of NULL. This option must be specified if msg_id already exists. If you replace a U.S. English message, the severity level is replaced for all messages in all other languages that have the same msg_id.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

For localization, the U.S. English version of a message must already exist before the message in another language can be added. The severity of the messages must match.

When localizing messages that contain parameters, use parameter numbers that correspond to the parameters in the original message. Insert an exclamation mark after each parameter number.

Original message | Localized message
‘Original message param 1: %s, param 2: %d’ | ‘Localized message param 1: %1!, param 2: %2!’

Because of language syntax differences, the parameter numbers in the localized message may not occur in the same sequence as in the original message.

Permissions

Execute permission defaults to the public role; however, only members of the sysadmin fixed server role can add messages with a severity level higher than 18 or with with_log set to true.

Examples
A. Define a custom message

This example adds a custom message to sysmessages.

USE master

EXEC sp_addmessage 50001, 16,
    N'Percentage expects a value between 20 and 100.
    Please reexecute with a more appropriate value.'

B. Add a message in two languages

This example first adds a message in U.S. English and then adds the same message in French.

USE master

EXEC sp_addmessage @msgnum = 60000, @severity = 16,
    @msgtext = N'The item named %s already exists in %s.',
    @lang = 'us_english'

EXEC sp_addmessage @msgnum = 60000, @severity = 16,
    @msgtext = N'L''élément nommé %1! existe déjà dans %2!',
    @lang = 'French'

See Also
RAISERROR | sp_dropmessage
sp_altermessage | System Stored Procedures


sp_add_notification

Sets up a notification for an alert.

Syntax

sp_add_notification [@alert_name =] 'alert',
[@operator_name =] 'operator',
[@notification_method =] notification_method

Arguments
[@alert_name =] 'alert'
Is the alert for this notification. alert is sysname, with no default.
[@operator_name =] 'operator'
Is the operator to be notified when the alert occurs. operator is sysname, with no default.
[@notification_method =] notification_method
Is the method by which the operator is notified. notification_method is tinyint, with no default. notification_method can be one or more of these values, ORed together.

Value | Description
1 | E-mail
2 | Pager
4 | net send

Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

sp_add_notification must be run from the msdb database.

SQL Server Enterprise Manager provides an easy, graphical way to manage the entire alerting system. Using SQL Server Enterprise Manager is the recommended way to configure your alert infrastructure.

To send a notification in response to an alert, you must first configure Microsoft® SQL Server™ Agent to send mail.

If a failure occurs when sending an e-mail message or pager notification, the failure is reported in the SQL Server Agent error log.

Permissions

Only members of the sysadmin fixed server role can execute sp_add_notification.

Examples

This example adds an e-mail notification for the specified alert (Test Alert).

Note This example assumes that Test Alert already exists and that stevenb is a valid operator name.

USE msdb

GO

EXEC sp_add_notification 'Test Alert', 'stevenb', 1

See Also
sp_delete_notification | sp_update_notification
sp_help_notification | System Stored Procedures


sp_add_operator

Creates an operator (notification recipient) for use with alerts and jobs.

Syntax

sp_add_operator [@name =] 'name'
[, [@enabled =] enabled]
[, [@email_address =] 'email_address']
[, [@pager_address =] 'pager_address']
[, [@weekday_pager_start_time =] weekday_pager_start_time]
[, [@weekday_pager_end_time =] weekday_pager_end_time]
[, [@saturday_pager_start_time =] saturday_pager_start_time]
[, [@saturday_pager_end_time =] saturday_pager_end_time]
[, [@sunday_pager_start_time =] sunday_pager_start_time]
[, [@sunday_pager_end_time =] sunday_pager_end_time]
[, [@pager_days =] pager_days]
[, [@netsend_address =] 'netsend_address']
[, [@category_name =] category']

Arguments
[@name =] 'name'
Is the name of an operator (notification recipient). This name must be unique and cannot contain the % character. name is sysname, with no default.
[@enabled =] enabled
Indicates the current status of the operator. enabled is tinyint, with a default of 1 (enabled). If 0, the operator is not enabled and does not receive notifications.
[@email_address =] 'email_address'
Is the e-mail address of the operator. This string is passed directly to the e-mail system. email_address is nvarchar(100), with a default of NULL.

Note If email_address or pager_address is a physical address (‘SMTP:jdoe@xyz.com’) rather than an alias (‘jdoe’), the value must be enclosed in square brackets: ‘[SMTP:jdoe@xyz.com]’.

[@pager_address =] 'pager_address'
Is the pager address of the operator. This string is passed directly to the e-mail system. pager_addresss is narchar(100), with a default of NULL.
[@weekday_pager_start_time =] weekday_pager_start_time
Is the time after which Microsoft® SQL Server™ Agent sends pager notification to the specified operator on the weekdays, Monday through Friday. weekday_pager_start_time is int, with a default of 090000, which indicates 9:00 A.M. on a 24-hour clock, and must be entered using the form HHMMSS.
[@weekday_pager_end_time =] weekday_pager_end_time
Is the time after which SQL Server Agent no longer sends pager notification to the specified operator on the weekdays, Monday through Friday. weekday_pager_end_time is int, with a default of 180000, which indicates 6:00 P.M. on a 24-hour clock, and must be entered using the form HHMMSS.
[@saturday_pager_start_time =] saturday_pager_start_time
Is the time after which SQL Server Agent sends pager notification to the specified operator on Saturdays. saturday_pager_start_time is int, with a default of 090000, which indicates 9:00 A.M. on a 24-hour clock, and must be entered using the form HHMMSS.
[@saturday_pager_end_time =] saturday_pager_end_time
Is the time after which SQL Server Agent no longer sends pager notification to the specified operator on Saturdays. saturday_pager_end_time is int, with a default of 180000, which indicates 6:00 P.M. on a 24-hour clock, and must be entered using the form HHMMSS.
[@sunday_pager_start_time =] sunday_pager_start_time
Is the time after which SQL Server Agent sends pager notification to the specified operator on Sundays. sunday_pager_start_time is int, with a default of 090000, which indicates 9:00 A.M. on a 24-hour clock, and must be entered using the form HHMMSS.
[@sunday_pager_end_time =] sunday_pager_end_time
Is the time after which SQL Server Agent no longer sends pager notification to the specified operator on Sundays. sunday_pager_end_time is int, with a default of 180000, which indicates 6:00 P.M. on a 24-hour clock, and must be entered using the form HHMMSS.
[@pager_days =] pager_days
Is a number that indicates the days that the operator is available for pages (subject to the specified start/end times). pager_days is tinyint, with a default of 0 indicating the operator is never available to receive a page. Valid values are from 0 through 127. pager_days is calculated by adding the individual values for the required days. For example, Monday through Friday is 2+4+8+16+32 = 62.

Value | Description
1 | Sunday
2 | Monday
4 | Tuesday
8 | Wednesday
16 | Thursday
32 | Friday
64 | Saturday

[@netsend_address =] 'netsend_address'
Is the network address of the operator to whom the network message is sent. netsend_address is nvarchar(100), with a default of NULL.
[@category_name =] category'
Is the name of the category for this alert. category is sysname, with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

sp_add_operator must be run from the msdb database.

Paging is supported by the e-mail system, which must have an e-mail-to-pager capability if you want to use paging.

SQL Server Enterprise Manager provides an easy, graphical way to manage jobs, and is the recommended way to create and manage the job infrastructure.

Permissions

Only members of the sysadmin fixed server role can execute sp_add_operator.

Examples

This example sets up the operator information for janetl. The operator information is enabled, and she is to be notified by pager Monday through Friday from 8 A.M. to 5 P.M.

use msdb

exec sp_add_operator @name = 'Janet Leverling',
    @enabled = 1,
    @email_address ='janetl',
    @pager_address = '5673219@mypagerco.com',
    @weekday_pager_start_time = 080000,
    @weekday_pager_end_time = 170000,
    @pager_days = 62

See Also
sp_delete_operator | sp_update_operator
sp_help_operator | System Stored Procedures


sp_addpublication

Creates a snapshot or transactional or publication.

Syntax

sp_addpublication [@publication =] 'publication' [,[@taskid =] taskid]
[,[@restricted =] 'restricted'] [,[@sync_method =] 'sync_method']
[,[@repl_freq =] 'repl_freq'] [,[@description =] 'description']
[,[@status =] 'status'] [,[@independent_agent =] 'independent_agent']
[,[@immediate_sync =] 'immediate_sync']
[,[@enabled_for_internet =] 'enabled_for_internet']
[,[@allow_push =] 'allow_push', [,[@allow_pull =] 'allow_pull']
[,[@allow_anonymous =] 'allow_anonymous']
[,[@allow_sync_tran =] 'allow_sync_tran']
[,[@autogen_sync_procs =] 'autogen_sync_procs']
[,[@retention =] retention]

Arguments
[@publication =] 'publication'
Is the name of the publication to create. publication is sysname, with no default. The name must be unique within the database.
[@taskid =] taskid
Is a unique scheduler task ID (must be created before the publication). task_id is int, with a default of 0. Do not use; this parameter is provided for backward compatibility only. Use sp_addpublication_snapshot.
[@restricted =] 'restricted'
Supported for backward compatibility only; use default_access instead.
[@sync_method =] 'sync_method'
Is the synchronization mode. sync_method is nvarchar(13), and can be one of these values.

Value | Description
native (default) | Produces native-mode bulk copy program output of all tables.
character | Produces character-mode bulk copy program output of all tables.

[@repl_freq =] 'repl_freq'
Is the type of replication frequency. replication_frequency is nvarchar(10), with a default of continuous. If continuous, the Publisher provides output of all log-based transactions. If Snapshot, the Publisher produces only scheduled synchronization events.
[@description =] 'description'
Is an optional description for the publication. description is nvarchar(255), with a default of NULL.
[@status =] 'status'
Is when publication data is available. status is nvarchar(8), and can be one of these values.

Value | Description
active | Publication data is immediately available for Subscribers.
inactive (default) | Publication data is not available for Subscribers when the publication is first created (they can subscribe, but the subscriptions are not processed).

[@independent_agent =] 'independent_agent'
Is whether there is a stand-alone Distribution Agent for this publication. independent_agent is nvarchar(5), with a default of FALSE. If true, there is a stand-alone Distribution Agent for this publication. If false, the publication uses a shared Distribution Agent, and each Publisher database/Subscriber database pair has a shared Agent.
[@immediate_sync =] 'immediate_sync'
Is whether the synchronization files for the publication are created each time the Snapshot Agent runs. immediate_sync is nvarchar(5), with a default of FALSE. If true, the synchronization files are created or re-created each time the Snapshot Agent runs. Subscribers are able to get the synchronization files immediately after the subscription if the Snapshot Agent has been completed once before the subscription. New subscriptions get the newest synchronization files generated by the most recent execution of the Snapshot Agent. independent_agent must be true for immediate_sync to be true. If false, the synchronization files are created only if there are new subscriptions. Subscribers cannot receive the synchronization files after the subscription until the Snapshot Agents are started and completed.
[@enabled_for_internet =] 'enabled_for_internet'
Is whether the publication is enabled for the Internet. enabled_for_internet is nvarchar(5), with a default of FALSE. If true, the synchronization files for the publication are put into the \Repldata\Ftp directory. The user must set up the Ftp directory.
[@allow_push =] 'allow_push'
Is whether push subscriptions can be created for the given publication. allow_push is nvarchar(5), with a default of TRUE, which allows push subscriptions on the publication.
[@allow_pull =] 'allow_pull'
Is whether pull subscriptions can be created for the given publication. allow_pull is nvarchar(5), with a default of FALSE. If false, pull subscriptions are not allowed on the publication.
[@allow_anonymous =] 'allow_anonymous'
Is whether anonymous subscriptions can be created for the given publication. allow_anonymous is nvarchar(5), with a default of FALSE. If true, immediate_sync must also be set to true. If false, anonymous subscriptions are not allowed on the publication.
[@allow_sync_tran =] 'allow_sync_tran'
Is whether immediate-updating subscriptions are allowed on the publication. allow_sync_tran is nvarchar(5), with a default of FALSE.
[@autogen_sync_procs =] 'autogen_sync_procs'
Is whether the synchronizing stored procedure for immediate-updating subscriptions is generated at the Publisher. autogen_sync_procs is nvarchar(5), with a default of TRUE.
[@retention =] retention]
Is the retention period in hours for subscription activity. retention is int, with a default of 72 hours. If a subscription is not active within the retention period, it expires and is removed. The value must be less than or equal to the maximum retention period of the distribution database used by the Publisher. If 0, the default value is used.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_addpublication is used in snapshot, transactional, and merge replication.

Permissions

Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_addpublication.

See Also
sp_addarticle | sp_enumfullsubscribers
sp_articlecolumn | sp_helparticle
sp_changearticle | sp_helparticlecolumns
sp_changepublication | sp_helppublication
sp_droparticle | System Stored Procedures
sp_droppublication |


sp_addpublication_snapshot

Creates a Snapshot Agent.

Syntax

sp_addpublication_snapshot [@publication =] 'publication'
[,[@frequency_type =] frequency_type]
[,[@frequency_interval =] frequency_interval]
[,[@frequency_subday =] frequency_subday]
[,[@frequency_subday_interval =] frequency_subday_interval]
[,[@frequency_relative_interval =] frequency_relative_interval]
[,[@frequency_recurrence_factor =] frequency_recurrence_factor]
[,[@active_start_date =] active_start_date]
[,[@active_end_date =] active_end_date]
[,[@active_start_time_of_day =] active_start_time_of_day]
[,[@active_end_time_of_day =] active_end_time_of_day]

Arguments
[@publication =] 'publication'
Is the name of the publication. publication is sysname, with no default.
[@frequency_type =] frequency_type
Is frequency with which the Snapshot Agent is applied. frequency_type is int, and can be one of these values.

Value | Description
1 | Once
4 (default) | Daily
8 | Weekly
10 | Monthly
20 | Monthly, relative to the frequency interval
40 | When SQL Server Agent starts

[@frequency_interval =] frequency_interval
Is the value to apply to the frequency set by frequency_type. frequency_interval is int, with a default of 1, which means daily.
[@frequency_subday =] frequency_subday
Is the units for freq_subday_interval. frequency_subday is int, and can be one of these values.

Value | Description
1 | Once
2 | Second
4 (default) | Minute
8 | Hour

[@frequency_subday_interval =] frequency_subday_interval
Is the interval for frequency_subday. frequency_subday_interval is int, with a default of 5, which means every 5 minutes.
[@frequency_relative_interval =] frequency_relative_interval
Is the date the Snapshot Agent runs. frequency_relative_interval is int, with a default of 1.
[@frequency_recurrence_factor =] frequency_recurrence_factor
Is the recurrence factor used by frequency_type. frequency_recurrence_factor is int, with a default of 0.
[@active_start_date =] active_start_date
Is the date when the Snapshot Agent is first scheduled, formatted as YYYYMMDD. active_start_date is int, with a default of 0.
[@active_end_date =] active_end_date
Is the date when the Snapshot Agent stops being scheduled, formatted as YYYYMMDD. active_end_date is int, with a default of 99991231, which means December 31, 9999.
[@active_start_time_of_day =] active_start_time_of_day
Is the time of day when the Snapshot Agent is first scheduled, formatted as HHMMSS. active_start_time_of_day is int, with a default of 0.
[@active_end_time_of_day =] active_end_time_of_day
Is the time of day when the Snapshot Agent stops being scheduled, formatted as HHMMSS. active_end_time_of_day is int, with a default of 235959, which means 11:59:59 P.M. as measured on a 24-hour clock.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_addpublication_snapshot is used in snapshot, transactional, and merge replication.

Permissions

Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_addpublication_snapshot.

See Also

System Stored Procedures


sp_addpublisher70

Adds a Microsoft® SQL Server™ version 7.0 Publisher at a SQL Server version 6.5 Subscriber. Use this stored procedure instead of sp_addpublisher.

Syntax

sp_addpublisher70 [@publisher =] 'publisher',
[@dist_account =] 'dist_account'

Arguments
[@publisher =] 'publisher'
Is the name of the Publisher. publisher is varchar(30), with no default.
[@dist_account =] 'dist_account'
Is the Microsoft Windows NT® account used by the Distribution Agent at the Distributor. In most cases, it is the Windows NT account of the SQL Server Agent at the Distributor. dist_account is varchar(255), with no default.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_addpublisher70 is used in snapshot and transactional replication.

Because there is no remote procedure call (RPC) link between the Subscriber and the Publisher in SQL Server 7.0, calling sp_addpublisher at the Subscriber for a SQL Server 7.0 Publisher fails. To add a SQL Server 7.0 Publisher at a SQL Server 6.5 Subscriber, you must apply a script to the version 6.5 server that creates the sp_addpublisher70 stored procedure. The script is in the file Replp70.sql located in the \Mssql7\Install directory.

Permissions

On servers running SQL Server 6.5, execute permission defaults to the system administrator.

See Also
System Stored Procedures


sp_addpullsubscription

Adds a pull or an anonymous subscription at the current database of the Subscriber.

Syntax

sp_addpullsubscription [@publisher =] 'publisher',
[@publisher_db =] 'publisher_db', [@publication =] 'publication'
[,[@independent_agent =] 'independent_agent']
[,[@subscription_type =] 'subscription_type']
[,[@description =] 'description'] [,[@update_mode =] 'update_mode']
[,[@immediate_sync =] immediate_sync]

Arguments
[@publisher =] 'publisher'
Is the name of the Publisher. publisher is sysname, with no default.
[@publisher_db =] 'publisher_db'
Is the name of the Publisher database. publisher_db is sysname, with no default.
[@publication =] 'publication'
Is the name of the publication. publication is sysname, with no default.
[@independent_agent =] 'independent_agent'
Is whether there is a stand-alone Distribution Agent for this publication. independent_agent is nvarchar(5), with a default of true. If true, there is a stand-alone Distribution Agent for this publication. If false, there is one Distribution Agent for each Publisher database/Subscriber database pair. independent_agent is a property of the publication and must have the same value here as it has at the Publisher.
[@subscription_type =] 'subscription_type'
Is the subscription type of the publication. subscription_type is nvarchar(9), and can be one of these values.

Value | Description
pull | Pull subscription
anonymous (default) | Anonymous subscription

[@description =] 'description'
Is the description of the publication. description is nvarchar(100), with a default of NULL.
[@update_mode =] 'update_mode'
Is the type of update. update_mode is nvarchar(15), and can be one of these values.

Value | Description
read-only (default) | Disables support for immediate-updating Subscribers.
synctran | Enables support for immediate-updating Subscribers.

[@immediate_sync =] immediate_sync
Is whether the synchronization files are created or re-created each time the Snapshot Agent runs. immediate_sync is bit with a default of 1, and must be set to the same value as immediate_sync in sp_addpublication. immediate_sync is a property of the publication and must have the same value here as it has at the Publisher.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_addpullsubscription is used in snapshot and transactional replication.

If the MSreplication_subscriptions table does not exist at the Subscriber, sp_addspullsubscription creates it. It also adds a row to the MSreplication_subscriptions table. For pull subscriptions, sp_addsubscription should be called at the Publisher first.

Permissions

Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_addpullsubscription.

See Also
sp_droppullsubscription | System Stored Procedures
sp_helppullsubscription |


sp_addpullsubscription_agent

Adds a new agent to the Subscriber’s database.

Syntax

sp_addpullsubscription_agent [@publisher =] 'publisher',
[@publisher_db =] 'publisher_db', [@publication =] 'publication'
[,[@subscriber =] 'subscriber']
[,[@subscriber_db =] 'subscriber_db']
[,[@subscriber_security_mode =] subscriber_security_mode]
[,[@subscriber_login =] 'subscriber_login']
[,[@subscriber_password =] 'subscriber_password']
[,[@distributor =] 'distributor', [,[@distribution_db =] 'distribution_db']
[,[@distributor_security_mode =] distributor_security_mode]
[,[@distributor_login =] 'distributor_login']
[,[@distributor_password =] 'distributor_password']
[,[@optional_command_line =] 'optional_command_line']
[,[@frequency_type =] frequency_type]
[,[@frequency_interval =] frequency_interval]
[,[@frequency_relative_interval =] frequency_relative_interval]
[,[@frequency_recurrence_factor =] frequency_recurrence_factor]
[,[@frequency_subday =] frequency_subday]
[,[@frequency_subday_interval =] frequency_subday_interval]
[,[@active_start_time_of_day =] active_start_time_of_day]
[,[@active_end_time_of_day =] active_end_time_of_day]
[,[@active_start_date =] active_start_date]
[,[@active_end_date =] active_end_date]
[,[@distribution_jobid =] distribution_jobid OUTPUT]
[,[@encrypted_distributor_password =] encrypted_distributor_password]
[,[@enabled_for_syncmgr =] 'enabled_for_syncmgr']
[,[@ftp_address =] 'ftp_address']
[,[@ftp_port =] ftp_port]
[,[@ftp_login =] 'ftp_login']
[,[@ftp_password =] 'ftp_password']

Arguments
[@publisher =] 'publisher'
Is the name of the Publisher. publisher is sysname, with no default.
[@publisher_db =] 'publisher_db'
Is the name of the Publisher database. publisher_db is sysname, with no default.
[@publication =] 'publication'
Is the name of the publication. publication is sysname, with no default.
[@subscriber =] 'subscriber'
Is the name of the Subscriber. subscriber is sysname, with a default of NULL.
[@subscriber_db =] 'subscriber_db'
Is the name of the subscription database. subscriber_db is sysname, with a default of NULL.
[@subscriber_security_mode =] subscriber_security_mode
subscriber_security_mode is int, with a default of NULL. 0 specifies Microsoft SQL Server Authentication. 1 specifies Microsoft SQL Server Authentication.
[@subscriber_login =] 'subscriber_login'
subscriber_login is sysname, with a default of NULL.
[@subscriber_password =] 'subscriber_password'
subscriber_password is sysname, with a default of NULL.
[@distributor =] 'distributor'
Is the name of the Distributor. distributor is sysname, with a default of the value specified by publisher.
[@distribution_db =] 'distribution_db'
Is the name of the Distributor. distribution_db is sysname, with no default.
[@distributor_security_mode =] distributor_security_mode
Is the security mode implemented. distributor_security_mode is int, with a default of 0. 0 specifies Microsoft SQL Server Authentication. 1 specifies Microsoft SQL Server Authentication.
[@distributor_login =] 'distributor_login'
Is the Distributor login. distributor_login is required if distributor_security_mode is set to 0. distributor_login is sysname, with a default of sa.
[@distributor_password =] 'distributor_password'
Is the Distributor password. distributor_password is required if distributor_security_mode is set to 0. distributor_password is sysname, with a default of NULL.
[@optional_command_line =] 'optional_command_line'
Is an optional command prompt supplied to the Distribution Agent. For example, -DefinitionFile C:\Distdef.txt or -CommitBatchSize 10. optional_command_line is nvarchar(4000), with a default of NULL.
[@frequency_type =] frequency_type
Is the frequency with which to schedule the Distribution Agent. frequency_type is int, and can be one of these values.

Value | Description
1 | One time
2 (default) | On demand
4 | Daily
8 | Weekly
16 | Monthly
32 | Monthly relative
64 | Autostart
124 | Recurring

[@frequency_interval =] frequency_interval
Is the value to apply to the frequency set by frequency_type. frequency_interval is int, with a default of 1.
[@frequency_relative_interval =] frequency_relative_interval
Is the date of the Distribution Agent. This parameter is used when frequency_type is set to 32 (monthly relative). frequency_relative_interval is int, and can be one of these values.

Value | Description
1 (default) | First
2 | Second
4 | Third
8 | Fourth
16 | Last

[@frequency_recurrence_factor =] frequency_recurrence_factor
Is the recurrence factor used by frequency_type. frequency_recurrence_factor is int, with a default of 1.
[@frequency_subday =] frequency_subday
Is how often to reschedule during the defined period. frequency_subday is int, and can be one of these values.

Value | Description
1 (default) | Once
2 | Second
4 | Minute
8 | Hour

[@frequency_subday_interval =] frequency_subday_interval
Is the interval for frequency_subday. frequency_subday_interval is int, with a default of 1.
[@active_start_time_of_day =] active_start_time_of_day
Is the time of day when the Distribution Agent is first scheduled, formatted as HHMMSS. active_start_time_of_day is int, with a default of 0.
[@active_end_time_of_day =] active_end_time_of_day
Is the time of day when the Distribution Agent stops being scheduled, formatted as HHMMSS. active_end_time_of_day is int, with a default of 0.
[@active_start_date =] active_start_date
Is the date when the Distribution Agent is first scheduled, formatted as YYYYMMDD. active_start_date is int, with a default of 0.
[@active_end_date =] active_end_date
Is the date when the Distribution Agent stops being scheduled, formatted as YYYYMMDD. active_end_date is int, with a default of 0.
[@distribution_jobid =] distribution_jobid OUTPUT
Is the ID of the Distribution Agent for this job. distribution_jobid is binary(16), with a default of NULL, and it is an OUTPUT parameter.
[@encrypted_distributor_password =] encrypted_distributor_password
For internal use only.
[@enabled_for_syncmgr =] 'enabled_for_syncmgr'
Is whether the subscription can be synchronized through the Microsoft Synchronization Manager. enabled_for_syncmgr is nvarchar(5), with a default of false. If false, the subscription is not registered with Synchronization Manager. If true, the subscription is registered with Synchronization Manager and can be synchronized without launching SQL Server Enterprise Manager.
[@ftp_address =] 'ftp_address'
Is the network address of the FTP service for the Distributor. ftp_address is sysname, with a default of NULL.
[@ftp_port =] ftp_port
Is the port number of the FTP service for the Distributor. ftp_port is int, with a default of NULL.
[@ftp_login =] 'ftp_login'
Is the username used to connect to the FTP service. ftp_login is sysname, with a default of NULL.
[@ftp_password =] 'ftp_password'
Is the user password used to connect to the FTP service. ftp_password is sysname, with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_addpullsubscription_agent is used in snapshot, transactional, and merge replication.

Permissions

Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_addpullsubscription_agent.

See Also
System Stored Procedures


sp_addremotelogin

Adds a new remote login ID on the local server, allowing remote servers to connect and execute remote procedure calls.

Syntax

sp_addremotelogin [@remoteserver =] 'remoteserver'
[,[@loginame =] 'login']
[,[@remotename =] 'remote_name']

Arguments
[@remoteserver =] 'remoteserver'
Is the name of the remote server that the remote login applies to. remoteserver is sysname, with no default. If only remoteserver is given, all users on remoteserver are mapped to existing logins of the same name on the local server. The server must be known to the local server (added using sp_addserver). When users on remoteserver connect to the local server running Microsoft® SQL Server™ to execute a remote stored procedure, they connect as the local login that matches their own login on remoteserver. remoteserver is the server that initiates the remote procedure call.
[@loginame =] 'login'
Is the login ID of the user on the local SQL Server. login is sysname, with a default of NULL. login must already exist on the local SQL Server. If login is specified, all users on remoteserver are mapped to that specific local login. When users on remoteserver connect to the local SQL Server to execute a remote stored procedure, they connect as login.
[@remotename =] 'remote_name'
Is the login ID of the user on the remote server. remote_name is sysname, with a default of NULL. remote_name must exist on remoteserver. If remote_name is specified, the specific user remote_name is mapped to login on the local server. When remote_name on remoteserver connects to the local SQL Server to execute a remote stored procedure, it connects as login. The login ID of remote_name can be different from the login ID on the remote server, login.
Return Code Values

0 (success) or 1 (failure)

Remarks

To execute distributed queries, use sp_addlinkedsrvlogin.

Every remote login entry has a status. The default status is not trusted. When a remote login with not trusted status is received, SQL Server checks the password. To not have the password checked, use sp_remoteoption to change the status to trusted.

sp_addremotelogin cannot be used inside a user-defined transaction.

Permissions

Only members of the sysadmin and securityadmin fixed server roles can execute sp_addremotelogin.

Examples
A. Map one to one

This example maps remote names to local names when the remote server Accounts and local server have the same user logins.

EXEC sp_addremotelogin 'ACCOUNTS'

B. Map many to one

This example creates an entry that maps all users from the remote server Accounts to the local login ID Albert.

EXEC sp_addremotelogin 'ACCOUNTS', 'Albert'

C. Use explicit one-to-one mapping

This example maps a remote login from the remote user Chris on the remote server Accounts to the local user salesmgr.

EXEC sp_addremotelogin 'ACCOUNTS', 'salesmgr', 'Chris'

See Also
sp_addlogin | sp_helpremotelogin
sp_addlinkedsrvlogin | sp_helpserver
sp_addserver | sp_remoteoption
sp_dropremotelogin | sp_revokelogin
sp_grantlogin | System Stored Procedures


sp_addrole

Creates a new Microsoft® SQL Server™ role in the current database.

Syntax

sp_addrole [@rolename =] 'role' [,[@ownername =] 'owner']

Arguments
[@rolename =] 'role'
Is the name of the new role. role is sysname, with no default. role must be a valid identifier and must not already exist in the current database.
[@ownername =] 'owner'
Is the owner of the new role. owner is sysname, with a default of dbo. owner must be a user or role in the current database. When specifying Windows NT users, specify the name the Windows NT user is known by in the database (added using sp_grantdbaccess).
Return Code Values

0 (success) or 1 (failure)

Remarks

SQL Server roles can contain from 1 to 128 characters, including letters, symbols, and numbers. However, roles cannot:

  • Contain a backslash character (\).
  • Be NULL, or an empty string (‘‘).

After adding a role, use sp_addrolemember to add security accounts as members of the role. When using the GRANT, DENY, or REVOKE statements to apply permissions to the role, members of the role inherit the permissions as if the permissions were applied directly to their accounts.

Note It is not possible to create new fixed server roles. Roles can only be created at the database level.

sp_addrole cannot be used inside a user-defined transaction.

Permissions

Only members of the sysadmin fixed server role or db_securityadmin and db_owner fixed database roles can execute sp_addrole.

Examples

This example adds the new role called Managers to the current database.

EXEC sp_addrole 'Managers'

See Also
sp_addrolemember | sp_helprole
sp_droprole | System Stored Procedures


sp_addrolemember

Adds a security account as a member of an existing Microsoft® SQL Server™ database role in the current database.

Syntax

sp_addrolemember [@rolename =] 'role',
[@membername =] 'security_account'

Arguments
[@rolename =] 'role'
Is the name of the SQL Server role in the current database. role is sysname, with no default.
[@membername =] 'security_account'
Is the security account being added to the role. security_account is sysname, with no default. security_account can be any valid SQL Server user, SQL Server role, or any Microsoft Windows NT® user or group granted access to the current database. When adding Windows NT users or groups, specify the name the Windows NT user or group is known by in the database (added using sp_grantdbaccess).
Return Code Values

0 (success) or 1 (failure)

Remarks

When using sp_addrolemember to add a security account to a role, any permissions applied to the role are inherited by the new member.

When adding a SQL Server role as a member of another SQL Server role, you cannot create circular roles. For example, MyRole cannot be added as a member of YourRole if YourRole is already a member of MyRole. Additionally, you cannot add a fixed database or fixed server role, or dbo to other roles. For example, the db_owner fixed database role cannot be added as a member of the user-defined role YourRole.

Only use sp_addrolemember to add a member to a SQL Server role. Use sp_addsrvrolemember to add a member to a fixed server role. Adding a member to a Windows NT group in SQL Server is not possible.

sp_addrolemember cannot be used inside a user-defined transaction.

Permissions

Only members of the db_securityadmin or db_owner fixed database role can execute sp_addrolemember to add a member to fixed database roles. Role owners can execute sp_addrolemember to add a member to any SQL Server role they own.

Examples

A. Add a Windows NT user

This example adds the Windows NT user Corporate\JeffL to the Sales database as user Jeff. Jeff is then added to the Sales_Managers role in the Sales database.

Note Because Corporate\JeffL is known as the user Jeff in the Sales database, the user name Jeff must be specified using sp_addrolemember.

USE Sales

GO

EXEC sp_grantdbaccess 'Corporate\JeffL', 'Jeff'

GO

EXEC sp_addrolemember 'Sales_Managers', 'Jeff'

B. Add a SQL Server user

This example adds the SQL Server user Michael to the Engineering role in the current database.

EXEC sp_addrolemember 'Engineering', 'Michael'

See Also
sp_addsrvrolemember | sp_grantdbaccess
sp_droprolemember | System Stored Procedures


sp_addserver

Defines a remote server or the name of the local Microsoft® SQL Server™. sp_addserver is provided for backward compatibility. Use sp_addlinkedserver.

Syntax

sp_addserver [@server =] 'server'
[,[@local =] 'local']
[,[@duplicate_ok =] 'duplicate_OK']

Arguments
[@server =] 'server'
Is the name of the server. Server names must be unique and follow the rules for Windows NT computer names, although spaces are not allowed. server is sysname, with no default.
[@local =] 'LOCAL'
Specifies whether the server that is being added is a local or remote server. @local is varchar(10), with a default of NULL. Specifying @local as LOCAL defines @server as the name of the local server and causes the @@SERVERNAME function to return server. (The Setup program sets this variable to the computer name during installation. It is recommended that the name not be changed. By default, the computer name is the way users connect to SQL Server without requiring additional configuration.) The local definition takes effect only after the server is shut down and restarted. Only one local server can be defined in each server.
[@duplicate_ok =] 'duplicate_OK'
Specifies whether or not a duplicate server name is allowed. @duplicate_OK is varchar(13), with a default of NULL. @duplicate_OK can only have the value duplicate_OK or NULL. If duplicate_OK is specified and the server name that is being added already exists, then no error is raised. @local must be specified if named parameters are not used.
Return Code Values

0 (success) or 1 (failure)

Remarks

To execute a stored procedure on a remote server (remote procedure calls) running an earlier version of SQL Server, add the remote server using sp_addserver. To execute a stored procedure (or any distributed query) on a remote server running SQL Server version 7.0, use sp_addlinkedserver to add the server.

To set or clear server options, use sp_serveroption.

sp_addserver cannot be used inside a user-defined transaction.

Permissions

Only members of the setupadmin and sysadmin fixed server roles can execute sp_addserver.

Examples

This example creates an entry for the remote the server ACCOUNTS on the local server.

sp_addserver 'ACCOUNTS'

See Also
sp_addlinkedserver | sp_helpremotelogin
sp_addremotelogin | sp_helpserver
sp_dropremotelogin | sp_serveroption
sp_dropserver | System Stored Procedures


sp_addsrvrolemember

Adds a login as a member of a fixed server role.

Syntax

sp_addsrvrolemember [@loginame =] 'login', [@rolename =] 'role'

Arguments
[@loginame =] 'login'
Is the name of the login being added to the fixed server role. login is sysname, with no default. login can be a Microsoft® SQL Server™ login or a Microsoft Windows NT® user account. If the Windows NT login has not already been granted access to SQL Server, access is granted automatically.
[@rolename =] 'role'
Is the name of the fixed server role in which the login is being added. role is sysname, with a default of NULL, and must be one of these values:
  • sysadmin
  • securityadmin
  • serveradmin
  • setupadmin
  • processadmin
  • diskadmin
  • dbcreator
Return Code Values

0 (success) or 1 (failure)

Remarks

When a login is added to a fixed server role, the login gains the permissions associated with that fixed server role.

The role membership of the sa login cannot be changed.

Use sp_addrolemember to add a member to a fixed database or user-defined role.

sp_addsrvrolemember stored procedure cannot be executed within a user-defined transaction.

Permissions

Members of a fixed server roles can execute sp_addsrvrolemember to add members only to the same fixed server role.

Examples

This example adds the Windows NT user Corporate\HelenS to the sysadmin fixed server role.

EXEC sp_addsrvrolemember 'Corporate\HelenS', 'sysadmin'

See Also
sp_addrolemember | System Stored Procedures
sp_dropsrvrolemember |


sp_addsubscriber

Adds a new Subscriber.

Syntax

sp_addsubscriber [@subscriber =] 'subscriber' [,[@type =] type]
[,[@login =] 'login'] [,[@password =] 'password']
[,[@commit_batch_size =] commit_batch_size]
[,[@status_batch_size =] status_batch_size]
[,[@flush_frequency =] flush_frequency]
[,[@frequency_type =] frequency_type]
[,[@frequency_interval =] frequency_interval]
[,[@frequency_relative_interval =] frequency_relative_interval]
[,[@frequency_recurrence_factor =] frequency_recurrence_factor]
[,[@frequency_subday =] frequency_subday]
[,[@frequency_subday_interval =] frequency_subday_interval]
[,[@active_start_time_of_day =] active_start_time_of_day]
[,[@active_end_time_of_day =] active_end_time_of_day]
[,[@active_start_date =] active_start_date]
[,[@active_end_date =] active_end_date]
[,[@description =] 'description'] [,[@security_mode =] security_mode]
[,[@encrypted_password =] encrypted_password]

Arguments
[@subscriber =] 'subscriber'
Is the name of the server to be added as a valid Subscriber to this server’s publications. subscriber is sysname, with no default.
[@type =] type
Is the type of Subscriber. type is tinyint, and can be one of these values.

Value | Description
0 (default) | Microsoft® SQL Server™ Subscriber
1 | ODBC data source server
2 | Microsoft Jet database
3 | OLE DB provider

[@login =] 'login'
Is the login ID for SQL Server Authentication. login is sysname, with a default of sa.
[@password =] 'password
Is the password for SQL Server Authentication. password is sysname, with a default of NULL.
[@commit_batch_size =] commit_batch_size
Is not used in SQL Server 7.0. Supported for backward compatibility only.
[@status_batch_size =] status_batch_size
Is not used in SQL Server 7.0. Supported for backward compatibility only.
[@flush_frequency =] flush_frequency
Is not used in SQL Server 7.0. Supported for backward compatibility only.
[@frequency_type =] frequency_type
Is the frequency with which to schedule the Distribution Agent. frequency_type is int, and can be one of these values.

Value | Description
1 | One time
2 | On demand
4 | Daily
8 | Weekly
16 | Monthly
32 | Monthly relative
64 (default) | Autostart
124 | Recurring

[@frequency_interval =] frequency_interval
Is the value to apply to the frequency set by frequency_type. frequency_interval is int, with a default of 1.
[@frequency_relative_interval =] frequency_relative_interval
Is the date of the Distribution Agent. This parameter is used when frequency_type is set to 32 (monthly relative). frequency_relative_interval is int, and can be one of these values.

Value | Description
1 (default) | First
2 | Second
4 | Third
8 | Fourth
16 | Last

[@frequency_recurrence_factor =] frequency_recurrence_factor
Is the recurrence factor used by frequency_type. frequency_recurrence_factor is int, with a default of 0.
[@frequency_subday =] frequency_subday
Is how often to reschedule during the defined period. frequency_subday is int, and can be one of these values.

Value | Description
1 | Once
2 | Second
4 (default) | Minute
8 | Hour

[@frequency_subday_interval =] frequency_subday_interval
Is the interval for frequency_subday. frequency_subday_interval is int, with a default of 5.
[@active_start_time_of_day =] active_start_time_of_day
Is the time of day when the Distribution Agent is first scheduled, formatted as HHMMSS. active_start_time_of_day is int, with a default of 0.
[@active_end_time_of_day =] active_end_time_of_day
Is the time of day when the Distribution Agent stops being scheduled, formatted as HHMMSS. active_end_time_of_day is int, with a default of 235959, which means 11:59:59 P.M. as measured on a 24-hour clock.
[@active_start_date =] active_start_date
Is the date when the Distribution Agent is first scheduled, formatted as YYYYMMDD. active_start_date is int, with a default of 0.
[@active_end_date =] active_end_date
Is the date when the Distribution Agent stops being scheduled, formatted as YYYYMMDD. active_end_date is int, with a default of 99991231, which means December 31, 9999.
[@description =] 'description'
Is a text description of the Subscriber. description is nvarchar(255), with a default of NULL. When upgrading, existing MSsubscriber_info tables are modified to include a description column, which is initialized to SQL Server version 7.0.
[@security_mode =] security_mode
Is the implemented security mode. security_mode is int, with a default of 1. 0 specifies SQL Server Authentication. 1 specifies Windows NT Authentication.
[@encrypted_password =] encrypted_password
For internal use only.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_addsubscriber is used in snapshot, transactional, and merge replication.

sp_addsubscriber writes to the MSsubscriber_info table in the distribution database.

Permissions

Only members of the sysadmin fixed server role can execute sp_addsubscriber.

See Also
sp_addremotelogin | sp_helpserver
sp_addserver | sp_helpsubscriberinfo
sp_changesubscriber | sp_remoteoption
sp_dboption | sp_serveroption
sp_dropsubscriber | System Stored Procedures
sp_helpdistributor |


sp_addsubscriber_schedule

Adds a schedule for the Distribution Agent and Merge Agent.

Syntax

sp_addsubscriber_schedule [@subscriber =] 'subscriber'
[,[@agent_type =] agent_type] [,[@frequency_type =] frequency_type]
[,[@frequency_interval =] frequency_interval]
[,[@frequency_relative_interval =] frequency_relative_interval]
[,[@frequency_recurrence_factor =] frequency_recurrence_factor]
[,[@frequency_subday =] frequency_subday]
[,[@frequency_subday_interval =] frequency_subday_interval]
[,[@active_start_time_of_day =] active_start_time_of_day]
[,[@active_end_time_of_day =] active_end_time_of_day]
[,[@active_start_date =] active_start_date]
[,[@active_end_date =] active_end_date]

Arguments
[@subscriber =] 'subscriber'
Is the name of the Subscriber. subscriber is sysname. The name of the Subscriber must be unique in the database, must not already exist, and cannot be NULL.
[@agent_type =] agent_type
Is the type of agent. agent_type is smallint, and can be one of these values.

Value | Description
0 (default) | Distribution Agent
1 | Merge Agent

[@frequency_type =] frequency_type
Is the frequency with which to schedule the Distribution Agent. frequency_type is int, and can be one of these values.

Value | Description
1 | One time
2 | On demand
4 | Daily
8 | Weekly
16 | Monthly
32 | Monthly relative
64 (default) | Autostart
124 | Recurring

[@frequency_interval =] frequency_interval
Is the value to apply to the frequency set by frequency_type. frequency_interval is int, with a default of 1.
[@frequency_relative_interval =] frequency_relative_interval
Is the date of the Distribution Agent. This parameter is used when frequency_type is set to 32 (monthly relative). frequency_relative_interval is int, and can be one of these values.

Value | Description
1 (default) | First
2 | Second
4 | Third
8 | Fourth
16 | Last

[@frequency_recurrence_factor =] frequency_recurrence_factor
Is the recurrence factor used by frequency_type. frequency_recurrence_factor is int, with a default of 0.
[@frequency_subday =] frequency_subday
Is how often to reschedule during the defined period. frequency_subday is int, and can be one of these values.

Value | Description
1 | Once
2 | Second
4 (default) | Minute
8 | Hour

[@frequency_subday_interval =] frequency_subday_interval
Is the interval for frequency_subday. frequency_subday_interval is int, with a default of 5.
[@active_start_time_of_day =] active_start_time_of_day
Is the time of day when the Distribution Agent is first scheduled, formatted as HHMMSS. active_start_time_of_day is int, with a default of 0.
[@active_end_time_of_day =] active_end_time_of_day
Is the time of day when the Distribution Agent stops being scheduled, formatted as HHMMSS. active_end_time_of_day is int, with a default of 235959, which means 11:59:59 P.M. as measured on a 24-hour clock.
[@active_start_date =] active_start_date
Is the date when the Distribution Agent is first scheduled, formatted as YYYYMMDD. active_start_date is int, with a default of 0.
[@active_end_date =] active_end_date
Is the date when the Distribution Agent stops being scheduled, formatted as YYYYMMDD. active_end_date is int, with a default of 99991231, which means December 31, 9999.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_addsubscriber_schedule is used in snapshot, transactional, and merge replication.

You can add a schedule for Distribution Agent and assign a default schedule for Merge Agent by calling sp_addsubscriber.

Permissions

Only members of the sysadmin fixed server role can execute sp_addsubscriber_schedule.

See Also
sp_changesubscriber_schedule System Stored Procedures


sp_addsubscription

Adds a subscription to an article and sets the Subscriber’s status.

Syntax

sp_addsubscription [@publication =] 'publication'
[,[@article =] 'article'] [,[@subscriber =] 'subscriber']
[,[@destination_db =] 'destination_db', [@sync_type =] 'sync_type']
[,[@status =] 'status' [@subscription_type =] 'subscription_type']
[,[@update_mode =] 'update_mode']
[,[@loopback_detection =] 'loopback_detection']
[,[@frequency_type =] frequency_type]
[,[@frequency_interval =] frequency_interval]
[,[@frequency_relative_interval =] frequency_relative_interval]
[,[@frequency_recurrence_factor =] frequency_recurrence_factor]
[,[@frequency_subday =] frequency_subday]
[,[@frequency_subday_interval =] frequency_subday_interval]
[,[@active_start_time_of_day =] active_start_time_of_day]
[,[@active_end_time_of_day =] active_end_time_of_day]
[,[@active_start_date =] active_start_date]
[,[@active_end_date =] active_end_date]
[,[@optional_command_line =] 'optional_command_line']
[,[@reserved =] 'reserved']
[,[@enabled_for_syncmgr =] 'enabled_for_syncmgr']

Arguments
[@publication =] 'publication'
Is the name of the publication. publication is sysname, with no default.
[@article =] 'article'
Is the article that is subscribed to. article is sysname, with a default of all. The article name must be unique within the publication. If all or not supplied, a subscription is added to all articles in that publication.
[@subscriber =] 'subscriber'
Is the name of the Subscriber. subscriber is sysname, with a default of NULL.
[@destination_db =] 'destination_db'
Is the name of the destination database in which to place replicated data. destination_db is sysname, with a default of NULL, and uses the same name as the publication database.
[@sync_type =] 'sync_type'
Is the subscription synchronization type. sync_type is nvarchar(15), and can be one of these values.

Value | Description
automatic (default) | Synchronization is applied to the Subscriber through the distribution process.
manual | A synchronization file is automatically produced, but it must be manually applied to the Subscriber.
none | No initial synchronization.

[@status =] 'status'
Is the subscription status. status is sysname, and can be one of these values.

Value | Description
active | If sync_type is none, the default for status is active. To enable a Subscriber to see articles in a restricted publication article, a placeholder subscription must be created with inactive status. If sync_type is automatic, status cannot be set to active.
subscribed | If sync_type is other than none, the default for status is subscribed.

[@subscription_type =] 'subscription_type'
Is the type of subscription. subscription_type is nvarchar(4), with a default of push. Can be push or pull.

Note Anonymous subscriptions do not need to use this stored procedure. The Distribution Agents of push subscriptions reside at the Distributor, and the Distribution Agents of pull subscriptions reside at the Subscriber.

[@update_mode =] 'update_mode'
Is the type of update. update_mode is nvarchar(15), and can be one of these values.

Value | Description
read-only (default) | Disables support for immediate-updating Subscribers.
synctran | Enables support for immediate-updating Subscribers.

[@loopback_detection =] 'loopback_detection'
Is whether the Distribution Agent sends transactions originated at the Subscriber back to the Subscriber. loopback_detection is nvarchar(5), and can be one of these values.

Value | Description
true | Distribution Agent does not send transactions originated at the Subscriber back to the Subscriber. The value can be set to true if and only if the subscription update_mode is synctran and the article table has a published timestamp column.
false | Distribution Agent sends transactions originated at the Subscriber back to the Subscriber.
NULL (default)

[@frequency_type =] frequency_type
Is the frequency with which to schedule the Distribution Agent. frequency_type is int, with a default of NULL. If no value is specified, sp_addsubscription uses the value specified in sp_addsubscriber.
[@frequency_interval =] frequency_interval
Is the value to apply to the frequency set by frequency_type. frequency_interval is int, with a default of NULL.
[@frequency_relative_interval =] frequency_relative_interval
Is the date of the Distribution Agent. This parameter is used when frequency_type is set to 32 (monthly relative). frequency_relative_interval is int, and can be one of these values.

Value | Description
1 | First
2 | Second
4 | Third
8 | Fourth
16 | Last
NULL (default)

[@frequency_recurrence_factor =] frequency_recurrence_factor
Is the recurrence factor used by frequency_type. frequency_recurrence_factor is int, with a default of NULL.
[@frequency_subday =] frequency_subday
Is how often, in minutes, to reschedule during the defined period. frequency_subday is int, and can be one of these values.

Value | Description
1 | Once
2 | Second
4 | Minute
8 | Hour
NULL

[@frequency_subday_interval =] frequency_subday_interval
Is the interval for frequency_subday. frequency_subday_interval is int, with a default of NULL.
[@active_start_time_of_day =] active_start_time_of_day
Is the time of day when the Distribution Agent is first scheduled, formatted as HHMMSS. active_start_time_of_day is int, with a default of NULL.
[@active_end_time_of_day =] active_end_time_of_day
Is the time of day when the Distribution Agent stops being scheduled, formatted as HHMMSS. active_end_time_of_day is int, with a default of NULL.
[@active_start_date =] active_start_date
Is the date when the Distribution Agent is first scheduled, formatted as YYYYMMDD. active_start_date is int, with a default of NULL.
[@active_end_date =] active_end_date
Is the date when the Distribution Agent stops being scheduled, formatted as YYYYMMDD. active_end_date is int, with a default of NULL.
[@optional_command_line =] 'optional_command_line'
Is the optional command prompt to execute. optional_command_line is nvarchar(4000), with a default of NULL.
[@reserved =] 'reserved'
Is reserved. reserved is nvarchar(10), with a default of NULL.
[@enabled_for_syncmgr =] 'enabled_for_syncmgr'
Is whether the subscription can be synchronized through the Microsoft Synchronization Manager. enabled_for_syncmgr is nvarchar(5), with a default of false. If false, the subscription is not registered with Synchronization Manager. If true, the subscription is registered with Synchronization Manager and can be synchronized without launching SQL Server Enterprise Manager.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_addsubscription is used in snapshot and transactional replication.

sp_addsubscription prevents ODBC/OLE DB Subscribers access to publications that:

  • Were created with the native @sync_method in the call to sp_addpublication.
  • Contain articles that were added to the publication with an sp_addarticle stored procedure that had a pre_creation_cmd parameter value of 3 (truncate).
  • Attempt to set @update_mode to synchtran.
  • Have an article configured to use parameterized statements.
Permissions

Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_addsubscription. For pull subscriptions, users with logins in the publication access list can execute sp_addsubscription.

See Also
sp_changesubstatus | sp_helpsubscription
sp_dropsubscription | System Stored Procedures


sp_addsynctriggers

Creates immediate-updating triggers at the Subscriber.

Syntax

sp_addsynctriggers {[@sub_table =] 'sub_table',
[@sub_table_owner =] 'sub_table_owner', [@publisher =] 'publisher',
[@publisher_db =] 'publisher_db', [@ins_proc =] 'ins_proc',
[@upd_proc =] 'upd_proc' [,[@del_proc =] 'del_proc'}
[,[@identity_col =] 'identity_col'] [,[@ts_col =] 'ts_col']
[,[@filter_clause =] 'filter_clause'],
{[@primary_key_bitmap =] 'primary_key_bitmap'}

Arguments
[@sub_table =] 'sub_table'
Is the name of the Subscriber table. sub_table is sysname, with no default.
[@sub_table_owner =] 'sub_table_owner'
Is the name of the owner of the Subscriber table. sub_table_owner is sysname, with no default.
[@publisher =] 'publisher'
Is the name of the Publisher server. publisher is sysname, with no default.
[@publisher_db =] 'publisher_db'
Is the name of the Publisher database. publisher_db is sysname, with no default. If NULL, the current database is used.
[@ins_proc =] 'ins_proc'
Is the name of the stored procedure that supports synchronous transaction inserts at the Publisher. ins_proc is sysname, with no default.
[@upd_proc =] 'upd_proc'
Is the name of the stored procedure that supports synchronous transaction updates at the Publisher. ins_proc is sysname, with no default.
[@del_proc =] 'del_proc'
Is the name of the stored procedure that supports synchronous transaction deletes at the Publisher. ins_proc is sysname, with no default.
[@identity_col =] 'identity_col'
Is the name of the identity column at the Publisher. identity_col is sysname, with a default of NULL.
[@ts_col =] 'ts_col'
Is the name of the timestamp column at the Publisher. ts_col is sysname, with a default of NULL.
[@filter_clause =] 'filter_clause'
Is the name of the filter clause used to create the article. filter_clause is nvarchar(4000), with a default of NULL.
[@primary_key_bitmap =] 'primary_key_bitmap'
Is a bit map of the primary key columns in the table. primary_key_bitmap is varbinary(4000), with no default.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_addsynctriggers is used by the Distribution Agent in snapshot and transactional replication to enable subscription for immediate-updating Subscribers.

Permissions

Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_addsynctriggers.

See Also
sp_articlesynctranprocs System Stored Procedures


sp_addtabletocontents

Inserts references into the merge tracking tables for any rows in a source table that are not currently included in the tracking tables.

Syntax

sp_addtabletocontents [@table_name =] 'table_name'
[,[@owner_name =] 'owner_name']

Arguments
[@table_name =] 'table_name'
Is the name of the table. table_name is sysname, with no default.
[@owner_name =] 'owner_name'
Is the name of the owner of the table. owner_name is sysname, with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_addtabletocontents is used only in merge replication.

The rows in the table_name are referred to by their rowguidcol and the references are added to the merge tracking tables. sp_addtabletocontents should be used after bulk copying data into a table that is published using merge replication. The stored procedure initiates tracking of the rows that were copied and ensures that the new rows will be included in the next synchronization.

Permissions

Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_addtabletocontents.


sp_addtask

sp_addtask is provided for backward compatibility only.

Creates a scheduled task.

Important For information about syntax used in earlier versions of SQL Server, see the Microsoft SQL Server Transact-SQL Reference for version 6.x.

Remarks

If you create a task by using sp_addtask, the task can be deleted only by sp_droptask. For task management, use SQL Server Enterprise Manager.

Permissions

Execute permissions default to the public role.

See Also
sp_droptask | sp_purgehistory
sp_helphistory | sp_updatetask
sp_helptask | System Stored Procedures


sp_addtype

Creates a user-defined data type.

Syntax

sp_addtype [@typename =] type,
[@phystype =] system_data_type
[, [@nulltype =] 'null_type']

Arguments
[@typename =] type
Is the name of the user-defined data type. Data type names must follow the rules for identifiers and must be unique in each database. type is sysname, with no default.
[@phystype =] system_data_type
Is the physical, or Microsoft® SQL Server™-supplied, data type (decimal, int, and so on) on which the user-defined data type is based. system_data_type is sysname, with no default, and can be one of these values:

‘binary(n)’ | image | smalldatetime
bit | int | smallint
‘char(n)’ | ‘nchar(n)’ | text
datetime | ntext | tinyint
decimal | numeric | uniqueidentifier
‘decimal[(p[, s])]’ | ‘numeric[(p[, s])]’ | ‘varbinary(n)’
float | ‘nvarchar(n)’ | ‘varchar(n)’
‘float(n)’ | real

Quotation marks are required around all parameters that have embedded blank spaces or punctuation marks. For more information about available data types, see Data Types.

n
Is a nonnegative integer indicating the length for the chosen data type
p
Is a nonnegative integer indicating the maximum total number of decimal digits that can be stored, both to the left and to the right of the decimal point. For more information, see decimal and numeric.
s
Is a nonnegative integer indicating the maximum number of decimal digits that can be stored to the right of the decimal point, and it must be less than or equal to the precision. For more information, see decimal and numeric.
[@nulltype =] ‘null_type’
Indicates the way the user-defined data type handles null values. null_type is varchar(8), with a default of NULL, and must be enclosed in single quotation marks (‘NULL’, ‘NOT NULL’, or ‘NONULL’). If null_type is not explicitly defined by sp_addtype, it is set to the current default nullability. Use the GETANSINULL system function to determine the current default nullability, which can be adjusted by using the SET statement or sp_dboption. Nullability should be explicitly defined.

Note The null_type parameter only defines the default nullability for this data type. If nullability is explicitly defined when the user-defined data type is used during table creation, it takes precedence over the defined nullability. For more information, see ALTER TABLE and CREATE TABLE.

Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

A user-defined data type name must be unique in the database, but user-defined data types with different names can have the same definition.

Executing sp_addtype creates a user-defined data type and adds it to the systypes system table for a specific database, unless sp_addtype is executed with master as the current database. If the user-defined data type must be available in all new user-defined databases, add it to model. After a user data type is created, you can use it in CREATE TABLE or ALTER TABLE, as well as bind defaults and rules to the user-defined data type.

User-defined data types cannot be defined using the SQL Server timestamp data type.

Permissions

Execute permissions default to the public role.

Examples
A. Create a user-defined data type that does not allow null values

This example creates a user-defined data type named ssn (social security number) that is based on the SQL Server-supplied varchar data type. The ssn data type is used for columns holding 11-digit social security numbers (999-99-9999). The column cannot be NULL.

Notice that varchar(11) is enclosed in single quotation marks because it contains punctuation (parentheses).

USE master

EXEC sp_addtype ssn, 'VARCHAR(11)', 'NOT NULL'

B. Create a user-defined data type that allows null values

This example creates a user-defined data type (based on datetime) named birthday that allows null values.

USE master

EXEC sp_addtype birthday, datetime, 'NULL'

C. Create additional user-defined data types

This example creates two additional user-defined data types, telephone and fax, for both domestic and international telephone and fax numbers.

USE master

EXEC sp_addtype telephone, 'varchar(24)', 'NOT NULL'

EXEC sp_addtype fax, 'varchar(24)', 'NULL'

See Also
CREATE DEFAULT | sp_rename
CREATE RULE | sp_unbindefault
sp_bindefault | sp_unbindrule
sp_bindrule | System Stored Procedures
sp_droptype |


sp_add_targetservergroup

Adds the specified server group.

Syntax

sp_add_targetservergroup [@name =] 'name'

Arguments
[@name =] 'name'
Is the name of the server group to create. name is sysname, with no default. name cannot contain commas.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

Target server groups provide an easy way to target a job at a collection of target servers. For more information, see sp_apply_job_to_targets.

Permissions

Only members of the sysadmin fixed server role can execute this procedure.

Examples

This example creates the target server group named Servers Processing Customer Orders.

USE msdb

EXEC sp_add_targetservergroup 'Servers Processing Customer Orders'

See Also
sp_delete_targetservergroup | sp_update_targetservergroup
sp_help_targetservergroup | System Stored Procedures


sp_addumpdevice

Adds a backup device to Microsoft® SQL Server™.

Syntax

sp_addumpdevice [@devtype =] 'device_type',
[@logicalname =] 'logical_name',
[@physicalname =] 'physical_name'
[, {
[@cntrltype =] controller_type
|
[@devstatus =] 'device_status'
}
]

Arguments
[@devtype =] 'device_type',
Is the type of backup device. device_type is varchar(20), with no default, and can be one of these values.

Value | Description
disk | Hard disk file as a backup device.
pipe | Named pipe.
tape | Any tape devices supported by Microsoft Windows NT®. If device is tape, noskip is the default.

[@logicalname =] 'logical_name'
Is the logical name of the backup device used in the BACKUP and RESTORE statements. logical_name is sysname, with no default, and cannot be NULL.
[@physicalname =] 'physical_name'
Is the physical name of the backup device. Physical names must follow the rules for operating-system file names or universal naming conventions for network devices, and must include a full path. physical_name is nvarchar(260), with no default value, and cannot be NULL.

When creating a backup device on a remote network location, be sure that the name under which SQL Server was started has appropriate write capabilities on the remote computer.

If you are adding a tape device, this parameter must be the physical name assigned to the local tape device by Windows NT, for example, \\.\TAPE0 for the first tape device on the computer. The tape device must be attached to the server computer; it cannot be used remotely. Enclose names containing nonalphanumeric characters in quotation marks.

[@cntrltype =] controller_type
Is not required when creating backup devices. It is acceptable to supply this parameter for scripts, but SQL Server ignores it. controller_type is smallint, with a default of NULL, and can be one of these values.

Value | Description
2 | Use when device_type is disk.
5 | Use when device_type is tape.
6 | Use when device_type is pipe.

[@devstatus =] 'device_status'
Is whether ANSI tape labels are read (noskip) or ignored (skip). device_status is varchar(40), with a default value of noskip.

Note Either specify controller_type or device_status, but not both.

Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

sp_addumpdevice adds a backup device to the master.dbo.sysdevices table. It can then be referred to logically in BACKUP and RESTORE statements.

Ownership and permissions problems can interfere with the use of disk or file backup devices. Make sure that appropriate file permissions are given to the account under which SQL Server was started.

SQL Server supports tape backups to tape devices that are supported by Windows NT. For information about Windows NT - supported tape devices, see the hardware compatibility list for Windows NT. To view the tape devices available on the computer, use SQL Server Enterprise Manager.

Use only the recommended tapes for the specific tape drive (as suggested by the drive manufacturer). If you are using DAT drives, use computer-grade DAT tapes (Digital Data Storage-DDS).

sp_addumpdevice cannot be executed inside a transaction.

Permissions

Execute permissions default to members of the diskadmin fixed server role.

Examples
A. Add a disk dump device

This example adds a disk backup device named MYDISKDUMP, with the physical name C:\Dump\Dump1.bak.

USE master

EXEC sp_addumpdevice 'disk', 'mydiskdump', 'c:\dump\dump1.bak'

B. Add a network disk backup device\

This example shows a remote disk backup device. The name under which SQL Server was started must have permissions to that remote file.

USE master

EXEC sp_addumpdevice 'disk', 'networkdevice',
    '\\servername\sharename\path\filename.ext'

C. Add a tape backup device

This example adds the TAPEDUMP1 device with the physical name \\.\Tape0.

USE master

EXEC sp_addumpdevice 'tape', 'tapedump1',
    '\\.\tape0'

See Also
BACKUP | sp_helpdevice
RESTORE | System Stored Procedures
sp_dropdevice |


sp_add_targetsvrgrp_member

Adds the specified target server to the specified target server group.

Syntax

sp_add_targetsvrgrp_member [@group_name =] 'group_name',
[@server_name =] 'server_name'

Arguments
[@group_name =] 'group_name'
Is the name of the group. group_name is sysname, with no default.
[@server_name =] 'server_name'
Is the name of the server that should be added to the specified group. server_name is nvarchar(30), with no default.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

A target server can be a member of more than one target server group.

Permissions

Only members of the sysadmin fixed server role can execute this procedure.

Examples

This example adds the group Servers Maintaining Customer Information and adds the LONDON1 server to that group.

USE msdb

EXEC sp_add_targetsvrgrp_member 'Servers Maintaining Customer Information', 'LONDON1'

See Also
sp_delete_targetsvrgrp_member System Stored Procedures


sp_adduser

Adds a security account for a new user in the current database. This procedure is included for backward compatibility. Use sp_grantdbaccess.

Syntax

sp_adduser [@loginame =] 'login'
[,[@name_in_db =] 'user']
[,[@grpname =] 'group']

Arguments
[@loginame =] 'login'
Is the name of the user’s login. login is sysname, with no default. login must be an existing Microsoft® SQL Server™ login or Microsoft Windows NT® user.
[@name_in_db =] 'user'
Is the name for the new user. user is sysname, with a default of NULL. If user is not specified, the name of the user defaults to the login name. Specifying user gives the new user a name in the database different from the login ID on SQL Server.
[@grpname =] 'group'
Is the group or role that the new user automatically becomes a member of. group is sysname, with a default of NULL. group must be a valid group or role in the current database. Microsoft SQL Server version 7.0 uses roles instead of groups.
Return Code Values

0 (success) or 1 (failure)

Remarks

SQL Server usernames can contain from 1 to 128 characters, including letters, symbols, and numbers. However, usernames cannot:

  • Contain a backslash character (\).
  • Be NULL, or an empty string (‘‘).

After a user has been added, use the GRANT, DENY, and REVOKE statements to define the permissions controlling the activities performed by the user.

Use sp_helplogin to display a list of valid login names.

Use sp_helprole to display a list of the valid role names. When specifying a role, the user automatically gains the permissions that are defined for the role. If a role is not specified, the user gains the permissions granted to the default public role. To add a user to a role, a value for username must be supplied. (username can be the same as login_id.)

To access a database, a login must be granted access by using sp_adduser or sp_grantdbaccess, or the guest security account must exist in the database.

sp_adduser cannot be executed inside a user-defined transaction.

Permissions

Only members of the db_accessadmin or db_owner fixed database roles can execute sp_adduser.

Examples
A. Add a user

This example adds the user Victoria to the existing fort_mudge role in the current database, using the existing login Victoria.

EXEC sp_adduser 'Victoria', 'Victoria', 'fort_mudge'

B. Add a username with the same login ID

This example adds the default username Margaret to the current database for the login Margaret, which belongs to the default public role.

EXEC sp_adduser 'Margaret'

C. Add a user who uses a different username

This example adds the Haroldq login to the current database with a username of Harold, which belongs to the fort_mudge role.

EXEC sp_adduser 'Haroldq', 'Harold', 'fort_mudge'

See Also
sp_addrole | sp_grantlogin
sp_dropuser | sp_helpuser
sp_grantdbaccess | System Stored Procedures


sp_altermessage

Alters the state of a sysmessages error.

Syntax

sp_altermessage [@message_id =] message_number,
[@parameter =] 'write_to_log',
[@parameter_value =] 'value'

Arguments
[@message_id =] message_number
Is the sysmessages error or message number to alter. message_number is int, with no default.
[@parameter =] 'write_to_log'
Indicates that the message is written to the Microsoft® Windows NT® application log. write_to_log is sysname, with no default value. If write_to_log is WITH_LOG, the message is written to the Microsoft Windows NT log when it occurs.

Note If a message is written to the Windows NT application log, it is also written to the Microsoft SQL Server™ error log file.

[@parameter_value =] 'value'
Is whether the error is written to the Windows NT application log. value is varchar(5), with no default. If true, the error is always written to the Windows NT application log. If false, the error is not always written to the Windows NT application log but can be written, depending on how the error was raised.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

The effect of sp_altermessage with the WITH_LOG option is similar to that of the RAISERROR WITH LOG parameter, except that sp_altermessage changes the logging behavior of an existing message. If a message has been altered to be WITH_LOG, it is always written to the Windows NT application log, regardless of how a user invokes the error. Even if RAISERROR is executed without the WITH LOG option, the error is written to the Windows NT application log.

System messages (such as 605), as well as user messages added by sp_addmessage, can be modified by using sp_altermessage.

Permissions

Only members of the sysadmin fixed server role can execute sp_altermessage.

Examples

This example causes existing message 55001 to be logged to the Windows NT application log.

sp_altermessage 55001, 'WITH_LOG', 'true'

See Also
sp_addmessage | System Stored Procedures
sp_dropmessage |


sp_apply_job_to_targets

Applies a job to one or more target servers or to the target servers belonging to one or more target server groups.

Syntax

sp_apply_job_to_targets [@job_id =] job_id | [@job_name =] 'job_name'
[, [@target_server_groups =] 'target_server_groups']
[, [@target_servers =] 'target_servers']
[, [@operation =] 'operation']

Arguments
[@job_id =] job_id
Is the job identification number of the job to apply to the specified target servers or target server groups. job_id is uniqueidentifier, with a default of NULL.
[@job_name =] 'job_name'
Is the name of the job to apply to the specified the associated target servers or target server groups. job_name is sysname, with a default of NULL.

Note Either job_id or job_name must be specified, but both cannot be specified.

[@target_server_groups =] 'target_server_groups'
Is a comma-separated list of target server groups to which the specified job is to be applied. target_server_groups is nvarchar(1024), with a default of NULL.
[@target_servers =] 'target_servers'
Is a comma-separated list of target servers to which the specified job is to be applied. target_servers is nvarchar(1024), with a default of NULL.
[@operation =] 'operation'
Is whether the specified job should be applied to or removed from the specified target servers or target server groups. operation is varchar(7), with a default of APPLY. Valid operations are APPLY and REMOVE.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

sp_apply_job_to_targets provides an easy way to apply (or remove) a job from multiple target servers, and is an alternative to calling sp_add_jobserver (or sp_delete_jobserver) once for each target server required.

Permissions

Only members of the sysadmin fixed server role can execute sp_apply_job_to_targets.

Examples

This example applies the previously created Backup Customer Information job to all the target servers in the Servers Maintaining Customer Information group.

USE msdb

EXEC sp_apply_job_to_targets @job_name = 'Backup Customer Information',     @target_server_groups = 'Servers Maintaining Customer Information',
    @operation = 'APPLY'

See Also
sp_add_jobserver | sp_remove_job_from_targets
sp_delete_jobserver | System Stored Procedures


sp_approlepassword

Changes the password of an application role in the current database.

Syntax

sp_approlepassword [@rolename =] 'role', [@newpwd =] 'password'

Arguments
[@rolename =] 'role'
Is the name of the application role. role is sysname, with no default. role must exist in the current database.
[@newpwd =] 'password'
Is the new password for the application role. password is sysname, with no default. The new password is encrypted when stored in the Microsoft® SQL Server™ system tables. password cannot be NULL.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_approlepassword cannot be executed within a user-defined transaction.

Permissions

Only members of the db_securityadmin and db_owner fixed database roles can execute sp_approlepassword.

Examples

This example sets the password for the PayrollAppRole application role to Valentine.

EXEC sp_approlepassword 'PayrollAppRole', 'Valentine'

See Also
sp_addapprole | System Stored Procedures
sp_setapprole |


sp_article_validation

Initiates a data validation request for the specified article.

Syntax

sp_article_validation [@publication =] 'publication' [,[@article =] 'article']
[,[@rowcount_only =] rowcount_only]
[,[@full_or_fast =] full_or_fast]
[,[@shutdown_agent =] shutdown_agent]

Arguments
[@publication =] 'publication'
Is the name of the publication in which the article exists. publication is sysname, with no default.
[@article =]'article'
Is the name of the article to change. article is sysname, with no default.
[@rowcount_only =] rowcount_only
Is whether to return only the rowcount for the table. rowcount_only is bit,with a default of 1, which specifies rowcount only. 0 specifies rowcount and checksum.
[@full_or_fast =] full_or_fast
Is the method used to calculate the rowcount. full_or_fast is tinyint, and can be one of these values.

Value | Description
0 | Does full count using COUNT(*).
1 | Does fast count from sysindexes.rows. Counting rows in sysindexes is much faster than counting rows in the actual table. However, because sysindexes is lazily updated, the rowcount may not be accurate.
2 (default) | Does conditional fast counting by first trying the fast method. If fast method shows differences, reverts to full method. If expected_rowcount is NULL and the stored procedure is being used to get the value, a full COUNT(*) is always used.

[@shutdown_agent =] shutdown_agent
Is whether the Distribution agent should shut down immediately upon completion of the validation. shutdown_agent is bit, with a default of 0. If 0, the Distribution Agent does not shut down. If 1, the Distribution Agent shuts down after the article is validated.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_article_validation is used in snapshot and transactional replication.

sp_article_validation causes validation information to be gathered on the specified article and posts a validation request to the transaction log. When the Distribution Agent receives this request, the Distribution Agent compares the validation information in the request to the Subscriber table. The results of the validation are displayed in the Replication Monitor and SQL Server Agent alerts.

Permissions

Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_article_validation.

See Also
sp_publication_validation | System Stored Procedures
sp_table_validation |


sp_articlecolumn

Specifies columns used in an article. Use sp_articlecolumn to vertically filter the data in a table.

Syntax

sp_articlecolumn [@publication =] 'publication', [@article =] 'article'
[,[@column =] 'column'] [,[@operation =] 'operation']
[,[@refresh_synctran_procs =] refresh_synctran_procs]
[,[@ignore_distributor =] ignore_distirbutor]

Arguments
[@publication =] 'publication'
Is the name of the publication that contains this article. publication is sysname, with no default.
[@article =] 'article'
Is the name of the article. article is sysname, with no default.
[@column =] 'column'
Is the name of the column to be added or dropped. column is sysname, with a default of NULL. If NULL, all columns are published.
[@operation =] 'operation'
Is the replication status. operation is nvarchar(4), with a default of add. add marks the column for replication. drop unmarks the column.
[@refresh_synctran_procs =] refresh_synctran_procs
Is whether to add or drop columns in an article. refresh_synctran_procs is bit, with a default of 1. If 1, the stored procedures supporting synchronous transactions are regenerated to match the number of columns replicated.
[@ignore_distributor =] ignore_distirbutor
Indicates whether this stored procedures executes without connecting to the Distributor. ignore_distributor is bit, with a default of 0. If 0, the database must be enabled for publishing, and the article cache should be refreshed to reflect the new columns replicated by the article. If 1, allows article columns to be dropped for articles that reside in an unpublished database, and should be used only in recovery situations.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_articlecolumn sets a bit in sysarticles. Only an unsubscribed article can be filtered using sp_articlecolumn.

If the publication allows immediate-updating subscriptions, the article must contain a timestamp column. If you attempt to delete the timestamp column, sp_articlecolumn returns an error.

Permissions

Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_articlecolumn.

See Also
sp_addarticle | sp_droppublication
sp_addpublication | sp_enumfullsubscribers
sp_articleview | sp_helparticle
sp_changearticle | sp_helparticlecolumns
sp_changepublication | sp_helppublication
sp_droparticle | System Stored Procedures


sp_articlefilter

Creates a filter stored procedure to horizontally filter data replicated from a published table. Only unsubscribed articles can be modified by this stored procedure.

Syntax

sp_articlefilter [@publication =] 'publication', [@article =] 'article'
[,[@filter_name =] 'filter_name'] [,[@filter_clause =] 'filter_clause']

Arguments
[@publication =] 'publication'
Is the name of the publication that contains the article. publication is sysname, with no default.
[@article =] 'article
Is the name of the article. article is sysname, with no default.
[@filter_name =] 'filter_name'
Is the name of the filter stored procedure to be created from the filter_name. filter_name is nvarchar(386), with a default of NULL.
[@filter_clause =] 'filter_clause'
Is a restriction (WHERE) clause that defines a horizontal filter. When entering the restriction clause, omit the keyword WHERE. filter_clause is ntext, with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_articlefilter creates the filter, inserts the ID of the filter stored procedure in the filter column of the sysarticles table, and inserts the text of the restriction clause in the filter_clause column.

To create an article with a horizontal filter, execute sp_addarticle with no filter parameter. Execute sp_articlefilter, providing all parameters including filter_clause. Then execute sp_articleview, providing all parameters including the identical filter_clause. If the filter already exists and if the type in sysarticles is 1 (log-based article), the previous filter is deleted and a new filter is created.

If filter_name and filter_clause are not provided, the previous filter is deleted and the filter ID is set to 0.

Permissions

Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_articlefilter.

See Also
sp_addarticle | sp_articleview
sp_articlecolumn | System Stored Procedures


sp_articlesynctranprocs

Generates procedures at the Publisher that are called by immediate updating triggers at the Subscriber.

Syntax

sp_articlesynctranprocs [@publication =] 'publication',
[@article =] 'article', [@ins_proc =] 'ins_proc',
[@upd_proc =] 'upd_proc', [@del_proc =] 'del_proc'
[,[@autogen =] 'autogen']

Arguments
[@publication =] 'publication'
Is the name of the publication. publication is sysname, with no default.
[@article =] 'article'
Is the name of the article. article is sysname, with no default.
[@ins_proc =] 'ins_proc'
Is the name of the stored procedure that supports immediate updating Subscriber inserts associated with this article. ins_proc is sysname, with no default.
[@upd_proc =] 'upd_proc'
Is the name of the stored procedure that supports immediate updating Subscriber updates associated with this article. upd_proc is sysname, with no default.
[@del_proc =] 'del_proc'
Is the name of the stored procedure that supports immediate updating Subscriber deletes associated with this article. del_proc is sysname, with no default.
[@autogen =] 'autogen'
Is whether to autogenerate stored procedures. autogen is nvarchar(5), with a default of true.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_articlesynctranprocs is used in snapshot and transactional replication.

Permissions

Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_articlesynctranprocs.

See Also
System Stored Procedures


sp_articleview

Creates the synchronization object for an article when a table is filtered vertically or horizontally. This synchronization object is a view that is used as the filtered source of the schema and data for the destination tables. Only unsubscribed articles can be modified by this stored procedure.

Syntax

sp_articleview [@publication =] 'publication', [@article =] 'article'
[,[@view_name =] 'view_name'] [,[@filter_clause =] 'filter_clause']

Arguments
[@publication =] 'publication'
Is the name of the publication that contains the article. publication is sysname, with no default.
[@article =] 'article'
Is the name of the article. article is sysname, with no default.
[@view_name =] 'view_name'
Is the name of the synchronization object. view_name is nvarchar(386), with a default of NULL.
[@filter_clause =] 'filter_clause'
Is a restriction (WHERE) clause that defines a horizontal filter. When entering the restriction clause, omit the WHERE keyword. filter_clause is ntext, with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_articleview creates the view and inserts the ID of the synchronization object (the view) in the sync_objid column of the sysarticles table, and the text of the restriction clause in the filter_clause column. If all columns are replicated and there is no filter_clause, the sync_objid in the sysarticles table is set to the ID of the base table, and the use of sp_articleview is not required.

To publish a vertically partitioned table (that is, to filter columns) first run sp_addarticle with no sync_object parameter, run sp_articlecolumn once for each column to be replicated (defining the vertical partition), and then run sp_articleview to create the synchronization object.

To publish a horizontally partitioned table (that is, to filter rows), run sp_addarticle with no filter parameter. Run sp_articlefilter, providing all parameters including filter_clause. Then run sp_articleview, providing all parameters including the identical filter_clause.

To publish a vertically and horizontally partitioned table, run sp_addarticle with no sync_object or filter parameters, run sp_articlecolumn once for each column to be replicated, and then run sp_articlefilter and sp_articleview.

If the article already has a synchronization object (a view), sp_articleview drops the existing view and creates a new one automatically. If the view was manually created (type in sysarticles is 5) the existing view is not dropped.

If you manually create a custom filter stored procedure and a synchronization object, do not run sp_articleview. Instead, provide these as the filter and sync_object parameters to sp_addarticle, along with the appropriate type value.

Permissions

Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_articleview.

See Also
sp_addarticle | sp_articlefilter
sp_articlecolumn | System Stored Procedures


sp_attach_db

Attaches a database to a server.

Syntax

sp_attach_db [@dbname =] 'dbname',
[@filename1 =] 'filename_n' [,…16]

Arguments
[@dbname =] 'dbname'
Is the name of the database to be attached to the server. The name must be unique. dbname is sysname, with a default of NULL.
[@filename1 =] 'filename_n'
Is the physical name, including path, of a database file. filename_n is nvarchar(260), with a default of NULL. There can be up to 16 file names specified. The parameter names start at @filename1 and increment to @filename16. The file name list must include at least the primary file, which contains the system tables that point to other files in the database. The list must also include any files that were moved after the database was detached.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

sp_attach_db should only be executed on databases that were previously detached from the database server using an explicit sp_detach_db operation. If more than 16 files must be specified, use CREATE DATABASE with the FOR ATTACH clause.

If you attach a database to a server other than the server from which the database was detached, and the detached database was enabled for replication, you should run sp_removedbreplication to remove replication from the database.

Permissions

Only by members of the sysadmin fixed server role can execute sp_attach_db.

Examples

This example attaches two files from pubs to the current server.

EXEC sp_attach_db @dbname = N'pubs',
    @filename1 = N'c:\mssql7\data\pubs.mdf',
    @filename2 = N'c:\mssql7\data\pubs_log.ldf'

See Also
CREATE DATABASE | sp_helpfile
sp_attach_single_file_db | System Stored Procedures
sp_detach_db | sp_removedbreplication


sp_attach_single_file_db

Attaches a database having only one data file to the current server.

Syntax

sp_attach_single_file_db [@dbname =] 'dbname',
[@physname =] 'physical_name'

Arguments
[@dbname =] 'dbname'
Is the name of the database to be attached to the server. dbname is sysname, with a default of NULL.
[@physname =] 'phsyical_name'
Is the physical name, including path, of the database file. physical_name is nvarchar(260), with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

When sp_attach_single_file_db attaches the database to the server, it builds a new log file and performs additional cleanup work to remove replication from the newly-attached database.

Used sp_attach_single_file_db only on databases that were previously detached from the server using an explicit sp_detach_db operation.

Permissions

Only members of the sysadmin fixed server role can execute sp_attach_single_file_db.

Examples

This example detaches pubs and then attaches one file from pubs to the current server.

EXEC sp_detach_db @dbname = 'pubs'

EXEC sp_attach_single_file_db @dbname = 'pubs',
    @physname = 'c:\mssql7\data\pubs.mdf'

See Also
sp_attach_db | sp_helpfile
sp_detach_db | System Stored Procedures


sp_autostats

Displays or changes the automatic UPDATE STATISTICS setting for a specific index and statistics, or for all indexes and statistics for a given table in the current database.

Note In the context of this stored procedure, the term index refers to statistics on the table.

Syntax

sp_autostats [@tblname =] 'table_name'
[, [@flagc =] 'stats_flag']
[, [@indname =] 'index_name']

Arguments
[@tblname =] 'table_name'
Is the name of the table for which to display the automatic UPDATE STATISTICS setting. table_name is nvarchar(776), with no default. If index_name is supplied, Microsoft® SQL Server™ enables the automatic UPDATE STATISTICS setting for that index.
[@flagc =] 'stats_flag'
Is whether the automatic UPDATE STATISTICS setting for the specified table or index is enabled (ON) or disabled (OFF). stats_flag is varchar(10), with a default of NULL.
[@indname =] 'index_name'
Is the name of the index for which to enable or disable the automatic UPDATE STATISTICS setting. index_name is sysname, with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Result Sets

If stats_flag is specified, this procedure reports the action that was taken but returns no result set.

If stats_flag is not specified, sp_autostats returns this is the result set.

Column name | Data type | Description
Index Name | varchar(60) | Name of the index.
AUTOSTATS | varchar(3) | Current automatic UPDATE STATISTICS setting: OFF or ON.
Last Updated | datetime | Date the statistics were last updated.

Permissions

Execute permissions default to the table owner.

Examples
A. Display the current status of all indexes for a table

This example displays the current statistics status of all indexes on the authors table.

USE pubs

EXEC sp_autostats authors

B. Enable automatic statistics for all indexes of a table

This example enables the automatic statistics setting for all indexes of the authors table.

USE pubs

EXEC sp_autostats authors, 'ON'

C. Disable automatic statistics for a specific index

This example disables the automatic statistics setting for the au_id index of the authors table.

USE pubs

EXEC sp_autostats authors, 'OFF', au_id

See Also
CREATE INDEX | sp_createstats
CREATE STATISTICS | sp_dboption
DBCC SHOW_STATISTICS | UPDATE STATISTICS
DROP STATISTICS | System Stored Procedures


sp_bindefault

Binds a default to a column or to a user-defined data type.

Syntax

sp_bindefault [@defname =] 'default',
[@objname =] 'object_name'
[, [@futureonly =] 'futureonly_flag']

Arguments
[@defname =] 'default'
Is the name of the default created by the CREATE DEFAULT statement. default is nvarchar(776), with no default.
[@objname =] 'object_name'
Is the name of table and column or the user-defined data type to which the default is to be bound. object_name is nvarchar(517), with no default. If object_name is not of the form table.column, it is assumed to be a user-defined data type. By default, existing columns of the user-defined data type inherit default unless a default has been bound directly to the column. A default cannot be bound to a column of timestamp data type, a column with the IDENTITY property, or a column that already has a DEFAULT constraint.

Note object_name can contain the [ and ] characters as delimited identifier characters.

[@futureonly =] 'futureonly_flag'
Is used only when binding a default to a user-defined data type. futureonly_flag is varchar(15), with a default of NULL. This parameter prevents existing columns of that data type from inheriting the new default. It is never used when binding a default to a column. If futureonly_flag is NULL, the new default is bound to any columns of the user-defined data type that currently have no default or that are using the existing default of the user-defined data type.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

You can bind a new default to a column (although using the DEFAULT constraint is preferred) or to a user-defined data type with sp_bindefault without unbinding an existing default. The old default is overridden. You cannot bind a default to a Microsoft® SQL Server™ data type. If the default is not compatible with the column to which you have bound it, SQL Server returns an error message when it tries to insert the default value (not when you bind it).

Existing columns of the user-defined data type inherit the new default unless they have a default bound directly to them or unless futureonly_flag is specified as futureonly. New columns of the user-defined data type always inherit the default.

When you bind a default to a column, related information is added to the syscolumns table. When you bind a default to a user-defined data type, related information is added to the systypes table.

Permissions

Execute permissions default to the object owner.

Examples
A. Bind a default to a column

Assuming that a default named today has been defined in the current database by the CREATE DEFAULT statement, this example binds the default to the hire date column of the employees table. Whenever a row is added to the employees table and data for the hire date column is not supplied, the column gets the value of the default today.

USE master

EXEC sp_bindefault 'today', 'employees.[hire date]'

B. Bind a default to a user-defined data type

Assuming that a default named def_ssn and a user-defined data type named ssn exist, this example binds the default def_ssn to the ssn user-defined data type. The default is inherited by all columns that are assigned the user-defined data type ssn when a table is created. Existing columns of type ssn also inherit the default def_ssn unless futureonly is specified for futureonly_flag value, or unless the column has a default bound directly to it. Defaults bound to columns always take precedence over those bound to data types.

USE master

EXEC sp_bindefault 'def_ssn', 'ssn'

C. Use the futureonly_flag

This example binds the default def_ssn to the user-defined data type ssn. Because futureonly is specified, no existing columns of type ssn are affected.

USE master

EXEC sp_bindefault 'def_ssn', 'ssn', 'futureonly'

D. Use delimited identifiers

This example shows the use of delimited identifiers in object_name.

USE master

CREATE TABLE [t.1] (c1 int)

-- Notice the period as part of the table name.

EXEC sp_bindefault 'default1', '[t.1].c1'

-- The object contains two periods;

-- the first is part of the table name,

-- and the second distinguishes the table name from the column name.

See Also
CREATE DEFAULT | sp_unbindefault
DROP DEFAULT | System Stored Procedures


sp_bindrule

Binds a rule to a column or to a user-defined data type.

Syntax

sp_bindrule [@rulename =] 'rule',
[@objname =] 'object_name'
[, [@futureonly =] 'futureonly_flag']

Arguments
[@rulename =] 'rule'
Is the name of a rule created by the CREATE RULE statement. rule is nvarchar(776), with no default.
[@objname =] 'object_name'
Is the table and column, or the user-defined data type to which the rule is to be bound. object_name is nvarchar(517), with no default. If object_name is not of the form table.column, it is assumed to be a user-defined data type. By default, existing columns of the user-defined data type inherit rule unless a rule has been bound directly to the column.

Note object_name can contain the [ and ] characters as delimited identifier characters.

[@futureonly =] 'futureonly_flag'
Is used only when binding a rule to a user-defined data type. future_only_flag is varchar(15), with a default of NULL. This parameter prevents existing columns of a user-defined data type from inheriting the new rule. If futureonly_flag is NULL, the new rule is bound to any columns of the user-defined data type that currently have no rule or that are using the existing rule of the user-defined data type.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

You can bind a new rule to a column (although using a CHECK constraint is preferred) or to a user-defined data type with sp_bindrule without unbinding an existing rule. The old rule is overridden. If a rule is bound to a column with an existing CHECK constraint, all restrictions are evaluated. You cannot bind a rule to a Microsoft® SQL Server™ data type.

The rule is enforced when an INSERT statement is attempted, not at binding. You can bind a character rule to a column of numeric data type, although such an INSERT is illegal.

Existing columns of the user-defined data type inherit the new rule unless future_flag is specified as futureonly. New columns defined with the user-defined data type always inherit the rule. However, if the ALTER COLUMN clause of an ALTER TABLE statement changes the data type of a column to a user-defined data type bound to a rule, the rule bound to the data type is not inherited by the column. The rule must be specifically bound to the column using sp_bindrule.

When you bind a rule to a column, related information is added to the syscolumns table. When you bind a rule to a user-defined data type, related information is added to the systypes table.

Permissions

Execute permissions default to the object owner.

Examples
A. Bind a rule to a column

Assuming that a rule named today has been created in the current database by the CREATE RULE statement, this example binds the rule to the hire date column of the employees table. When a row is added to employees, the data for the hire date column is checked against the today rule.

USE master

EXEC sp_bindrule 'today', 'employees.[hire date]'

B. Bind a rule to a user-defined data type

Assuming the existence of a rule named rule_ssn and a user-defined data type named ssn, this example binds rule_ssn to ssn. In a CREATE TABLE statement, columns of type ssn inherit the rule_ssn rule. Existing columns of type ssn also inherit the rule_ssn rule unless futureonly is specified for futureonly_flag, or ssn has a rule bound directly to it. Rules bound to columns always take precedence over those bound to data types.

USE master

EXEC sp_bindrule 'rule_ssn', 'ssn'

C. Use the futureonly_flag

This example binds the rule_ssn rule to the user-defined data type ssn. Because futureonly is specified, no existing columns of type ssn are affected.

USE master

EXEC sp_bindrule 'rule_ssn', 'ssn', 'futureonly'

D. Use delimited identifiers

This example shows the use of delimited identifiers in object_name.

USE master

CREATE TABLE [t.2] (c1 int)

-- Notice the period as part of the table name.

EXEC sp_binderule rule1, '[t.2].c1'

-- The object contains two periods;

-- the first is part of the table name

-- and the second distinguishes the table name from the column name.

See Also
CREATE RULE | sp_unbindrule
DROP RULE | System Stored Procedures


sp_bindsession

Binds or unbinds a connection to other connections. A bound connection allows two or more connections to participate in the same transaction and share the transaction space until a ROLLBACK TRANSACTION or COMMIT TRANSACTION is issued.

Syntax

sp_bindsession {'bind_token' | NULL}

Arguments
'bind_token'
Is the token that identifies the transaction space originally obtained by using sp_getbindtoken or the Open Data Services srv_getbindtoken function. bind_token is varchar(8000).
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

sp_bindsession uses a bind token to bind two or more existing client connections. A connection is a client executing a command. Bound database connections share a transaction context and lock space. If sp_bindsession is given a token that is not currently used by any other active session, that token becomes the token for the session. Another session can be bound to this session using this token.

Note If a connection involved in a local transaction executes a remote procedure call (RPC) on a remote server with SET REMOTE_PROC_TRANSACTIONS ON, the local transaction is promoted to a distributed transaction by Microsoft Distributed Transaction Coordinator (MS DTC), and an MS DTC session starts. When the transaction is promoted, the bind token changes to a distributed token identification number. Use the changed token identification number. For more information, see your Microsoft Distributed Transaction Coordinator documentation.

Unbind from a session either by omitting bind_token or by passing NULL in bind_token.

sp_bindsession can be executed through ODBC, DB-LIBRARY functions, or the isql utility.

Important Prior to executing sp_bindsession, you must obtain a bind token by running sp_getbindtoken or the Open Data Services srv_getbindtoken function.

To obtain and pass a bind token, run sp_getbindtoken prior to executing sp_bindsession for sharing the same lock space. If you obtain a bind token, sp_bindsession runs correctly.

Permissions

Execute permissions default to public role.

Examples

This example binds the specified bind token to the current session.

Note The bind token shown in the example was obtained by executing sp_getbindtoken prior to executing sp_bindsession.

USE master

EXEC sp_bindsession 'BP9---5---->KB?-V`<>1E:H-7U-]ANZ'

See Also
sp_getbindtoken System Stored Procedures


sp_browsereplcmds

Returns a result set in a readable format of the replicated commands stored in the distribution database.

Syntax

sp_browsereplcmds [[@xact_seqno_start =] 'xact_seqno_start']
[,[@xact_seqno_end =] 'xact_seqno_end']
[,[@originator_id =] 'originator_id']
[,[@publisher_database_id =] 'publisher_database_id']
[,[@article_id =] 'article_id']
[,[@command_id =] command_id]

Arguments
[@xact_seqno_start =] 'xact_seqno_start'
Specifies the lowest valued exact sequence number to return. xact_seqno_start is nchar(22), with a default of 0x00000000000000000000.
[@xact_seqno_end =] 'xact_seqno_end'
Specifies the highest exact sequence number for which to return information. xact_seqno_end is nchar(22), with a default of 0xFFFFFFFFFFFFFFFFFFFF.
[@originator_id =] 'originator_id'
Is whether commands with the specified originator_id are returned. originator_id is int, with a default of NULL.
[@publisher_database_id =] 'publisher_database_id'
Is whether commands with the specified publisher_database_id are returned. publisher_database_id is int, with a default of NULL.
[@article_id =] 'article_id'
Is whether commands with the specified article_id are returned. article_id is int, with a default of NULL.
[@command_id =] command_id
Is the location of the command in MSrepl_commands to be decoded. command_id is int, with a default of NULL. If specified, all other parameters must be specified also, and xact_seqno_start must be identical to xact_seqno_end.
Result Sets

sp_browsereplcmds is a diagnostic utility used to examine replicated commands stored in the distribution database. sp_browsereplcmds returns this result set.

Column name | Data type | Description
xact_seqno | varbinary(16) | Sequence number of the command
originator_id | int | ID of the command originator
publisher_database_id | int | ID of the Publisher database
article_id | int | ID of the article
type | int | Type of command
command | nvarchar(1024) | Transact-SQL command

Long commands can be split across several rows in the results set.

Remarks

sp_browsereplcmds is used in transactional replication.

Permissions

Only members of the sysadmin fixed server role can execute sp_browsereplcmds.

See Also
sp_dumpparamcmd | sp_replshowcmds
sp_replcmds | System Stored Procedures


sp_catalogs

Returns the list of catalogs in the specified linked server, which is equivalent to databases in Microsoft® SQL Server™.

Syntax

sp_catalogs [@server_name =] 'linked_svr'

Argument
[@server_name =] 'linked_svr'
Is the name of a linked server. linked_svr is sysname, with no default.
Return Code Values

None

Result Sets
Column name | Data type | Description
catalog_name | nvarchar(128) | Name of the catalog
Description | nvarchar(4000) | Description of the catalog

Permissions

Execute permissions default to the public role.

Examples

This example returns catalog information for the linked server named OLE DB ODBC Linked Server #3.

Note For sp_catalogs to provide useful information, the OLE DB ODBC Linked Server #3 must already exist.

USE master

EXEC sp_catalogs 'OLE DB ODBC Linked Server #3'

See Also
sp_addlinkedserver | sp_linkedservers
sp_columns_ex | sp_primarykeys
sp_column_privileges | sp_tables_ex
sp_foreignkeys | sp_table_privileges
sp_indexes | System Stored Procedures


sp_certify_removable

Verifies that a database is configured properly for distribution on removable media and reports any problems to the user.

Syntax

sp_certify_removable [@dbname =] 'dbname' [, [@autofix =] 'auto']

Arguments
[@dbname =] 'dbname'
Specifies the database to be verified. dbname is sysname.
[@autofix =] 'auto'
Gives ownership of the database and all database objects to the system administrator, and drops any user-created database users and any nondefault permissions. auto is nvarchar(4) with a default of NULL. auto has the value auto.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

If the database is configured properly, sp_certify_removable sets the database offline so the files can be copied. It updates statistics on all tables and reports any ownership or user problems. It also marks the data filegroups as read-only so these files can be copied to read-only media.

The system administrator must be the owner of the database and all database objects. The system administrator is a known user that exists on all servers running Microsoft® SQL Server™ and can be counted on to exist when the database is later distributed and installed.

If you run sp_certify_removable without the auto value and it returns information indicating that the system administrator is not the database owner, that user-created users exist, that the system administrator does not own all objects in the database, or that nondefault permissions have been granted, you can correct those conditions in two ways:

  • Use SQL Server tools and procedures, and then run sp_certify_removable again.
  • Simply run sp_certify_removable with the auto value.

Note that this stored procedure only checks for users and user permissions. It is permissible to add groups to the database and to grant permissions to those groups. For more information, see GRANT.

This procedure writes verification information to a text file that has the following file name format:

CertifyR_[dbname].txt

Note The permissions on xp_cmdshell must permit this file write.

Permission

EXECUTE permissions are restricted to members of the sysadmin fixed server role.

Example

This example certifies that the inventory database is ready to be removed.

sp_certify_removable inventory, AUTO

See Also
sp_attach_db | sp_dbremove
sp_create_removable | System Stored Procedures
sp_dboption |


sp_change_agent_parameter

Changes a parameter of a replication agent profile stored in MSagent_parameters.

Syntax

sp_change_agent_parameter [@profile_id =] profile_id,
[@parameter_name =] 'parameter_name',
[@parameter_value =] 'parameter_value'

Arguments
[@profile_id =] profile_id,
Is the ID of the profile. profile_id is int, with no default.
[@parameter_name =] 'parameter_name'
Is the name of the parameter. parameter_name is sysname, with no default.
[@parameter_value =] 'parameter_value'
Is the new value of the parameter. parameter_value is nvarchar(255), with no default.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_change_agent_parameter is used in all types of replication.

Permissions

Only members of the sysadmin fixed server role can execute sp_change_agent_parameter.

See Also
sp_add_agent_parameter | sp_help_agent_parameter
sp_drop_agent_parameter | System Stored Procedures


sp_change_agent_profile

Changes a parameter of a replication agent profile stored in MSagent_profiles.

Syntax

sp_change_agent_profile [@profile_id =] profile_id,
[@property =] 'property', [@value =] 'value'

Arguments
[@profile_id =] profile_id,
Is the ID of the profile. profile_id is int, with no default.
[@property =] 'property'
Is the name of the property. property is sysname, with no default.
[@value =] 'value'
Is the new value of the property. value is nvarchar(3000), with no default.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_change_agent_profile is used in all types of replication.

Permissions

Only members of the sysadmin fixed server role can execute sp_change_agent_profile.

See Also
sp_add_agent_profile | sp_help_agent_profile
sp_drop_agent_profile | System Stored Procedures


sp_change_users_login

Changes the relationship between a Microsoft® SQL Server™ login and a SQL Server user in the current database.

Syntax

sp_change_users_login [@Action =] 'action' [,[@UserNamePattern =] 'user']
[,[@LoginName =] 'login']

Arguments
[@Action =] 'action'
Describes the action to be performed by the procedure. action is varchar(10), and can be one of these values.

Value | Description
Auto_Fix Links user entries in the sysusers table in the current database to logins of the same name in syslogins. It is recommended that the result from the Auto_Fix statement be checked to confirm that the links made are the intended outcome. Avoid using Auto_Fix in security-sensitive situations. Auto_Fix makes best estimates on links, possibly allowing a user more access permissions than intended.

user must be a valid user in the current database, and login must be NULL, a zero-length string (‘‘), or not specified.
Report Lists the users, and their corresponding security identifiers (SID), that are in the current database, not linked to any login.

user and login must be NULL, a zero-length string (‘‘), or not specified.
Update_One | Links the specified user in the current database to login. login must already exist. user and login must be specified.

[@UserNamePattern =] 'user'
Is the name of a SQL Server user in the current database. user is sysname, with a default of NULL. sp_change_users_login can only be used with the security accounts of SQL Server logins and users; it cannot be used with Microsoft Windows NT® users.
[@LoginName =] 'login'
Is the name of a SQL Server login. login is sysname, with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Result Sets
Column name | Data type | Description
UserName | sysname | Login name.
UserSID | varbinary(85) | Login security identifier.

Remarks

Use this procedure to link the security account for a user in the current database with a different login. If the login for a user has changed, use sp_change_users_login to link the user to the new login without losing the user’s permissions.

login cannot be sa, and user cannot be the dbo, guest, or INFORMATION_SCHEMA users.

sp_change_users_login cannot be executed within a user-defined transaction.

Permissions

Any member of the public role can execute sp_change_users_login with the Report option. Only members of the sysadmin fixed server role can specify the Auto_Fix option. Only members of the sysadmin or db_owner roles can specify the Update_One option.

Examples
A. Show a report of the current user to login mappings

This example produces a report of the users in the current database and their security identifiers.

EXEC sp_change_users_login 'Report'

B. Change the login for a user

This example changes the link between user Mary in the pubs database and the existing login, to the new login NewMary (added with sp_addlogin).

--Add the new login.

USE master

go

EXEC sp_addlogin 'NewMary'

go

--Change the user account to link with the 'NewMary' login.

USE pubs

go

EXEC sp_change_users_login 'Update_One', 'Mary', 'NewMary'

See Also
sp_addlogin | sp_helplogins
sp_adduser | System Stored Procedures


sp_changearticle

Changes the properties of an article.

Syntax

sp_changearticle [[@publication =] 'publication'] [,[@article =]'article']
[,[@property =] 'property'] [,[@value =] 'value']

Arguments
[@publication =] 'publication'
Is the name of the publication that contains the article. publication is sysname, with a default of NULL.
[@article =]'article'
Is the name of the article whose property is to be changed. article is sysname, with a default of NULL.
[@property =] 'property'
Is an article property to change. property is nvarchar(20).
[@value =] 'value'
Is the new value of the article property. value is nvarchar(255).

This table describes the valid properties of articles and the values for those properties.

Property | Values | Description
description | description | New descriptive entry for the publication job.
sync_object | sync_object | Name of the table or view used to produce a synchronization output file. The default is NULL.
type | Article type. Can have a value of:
logbased (default) | Log-based article.
logbased manualfilter | Log-based article with manual filter.
logbased manualview | Log-based article with manual view.
logbased manualboth | Log-based article with both manual filter and manual view.
ins_cmd | ins_cmd | INSERT statement to execute; otherwise, it is constructed from the log.
del_cmd | del_cmd | DELETE statement to execute; otherwise, it is constructed from the log.
upd_cmd | upd_cmd | UPDATE statement to execute; otherwise, it is constructed from the log.
filter | filter | New stored procedure to be used to filter the table (horizontal filtering). The default is NULL.
dest_table | dest_table | New destination table, if different from the source table (source_table).
dest_object | dest_object
creation_script | creation_script | Path and name of an article schema script used to create target tables. The default is NULL.
pre_creation_cmd | Pre-creation command that can drop, delete, or truncate the destination table before synchronization is applied.
none | Does not use a command.
drop | Drops the destination table.
delete | Deletes the destination table.
truncate | Truncates the destination table.
status | Specifies the new status of the property.
include column names | Allows column names in the replicated INSERT statement.
no column names | Allows no column names in the replicated INSERT statement.
owner qualified | Allows owner-qualified table names.
not owner qualified | Allows table names that are not owner-qualified.
string literals | parameters | Whether the logreader-generated commands use the standard string_literal command format or the new parameterized command format.
schema option | Specifies the bitmap of the schema generation option for the given article. schema option is binary(8).
0x00 | Disables scripting by InitialSync and uses the provided CreationScript.
0x01 | Generates the object creation (CREATE TABLE, CREATE PROCEDURE, and so on).
0x11 (default) | The combined bitmap for generating the CREATE TABLE, creating a clustered index, and converting user-defined types to base types.
0x10 | Generates a corresponding clustered index.
0x20 | Converts user-defined data types to base data types.
0x40 | Generates corresponding nonclustered index(es).
0x80 | Includes declared referential integrity on the primary keys.
destination_owner | destination_owner | Name of the owner of the destination object.
NULL | NULL | All available property values are printed.

Return Code Values

0 (success) or 1 (failure)

Remarks

sp_changearticle is used in snapshot and transactional replication.

Within an existing publication, you can change a certain article (using sp_changearticle) without having to drop and re-create the entire publication. Only unsubscribed articles can be changed.

Permissions

Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_changearticle.

See Also
sp_addarticle | sp_enumfullsubscribers
sp_addpublication | sp_helparticle
sp_articlecolumn | sp_helparticlecolumns
sp_changepublication | sp_helppublication
sp_droparticle | System Stored Procedures
sp_droppublication |


sp_changedbowner

Changes the owner of the current database.

Syntax

sp_changedbowner [@loginame =] 'login' [,[@map =] remap_alias_flag]

Arguments
[@loginame =] 'login'
Is the login ID of the new owner of the current database. login is sysname, with no default. login must be Microsoft® SQL Server™ login or a Microsoft Windows NT® user that already exists. login cannot become the owner of the current database if it already has access to the database through an existing alias or user security account within the database. To avoid this, drop the alias or user within the current database first.
[@map =] remap_alias_flag
Is the value true or false, which indicates whether existing aliases to the old database owner (dbo) are mapped to the new owner of the current database or dropped. remap_alias_flag is varchar(5), with a default of NULL, indicating any existing aliases to the old dbo are mapped to the new owner of the current database. false indicates that existing aliases to the old database owner are dropped.
Return Code Values

0 (success) or 1 (failure)

Remarks

After sp_changedbowner is executed, the new owner is known as the dbo user inside the database. The dbo has implied permissions to perform all activities in the database.

The owner of the master, model, or tempdb system databases cannot be changed.

To display a list of the valid login values, execute the sp_helplogins stored procedure.

Executing sp_changedbowner with only the login parameter changes database ownership to login and maps the aliases of users who were previously aliased to dbo to the new database owner.

Permissions

Only members of the sysadmin fixed server role or the owner of the current database can execute sp_changedbowner.

Examples

This example makes the user Albert the owner of the current database and maps existing aliases to the old database owner to Albert.

EXEC sp_changedbowner 'Albert'

See Also
CREATE DATABASE | sp_helpdb
sp_dropalias | sp_helplogins
sp_dropuser | System Stored Procedures


sp_changedistpublisher

Updates the properties of the distribution Publisher.

Syntax

sp_changedistpublisher [@publisher =] 'publisher'
[,[@property =] 'property'] [,[@value =] 'value']

Arguments
[@publisher =] 'publisher'
Is the Publisher name. publisher is sysname, with no default.
[@property =] 'property'
Is a property to change for the given Publisher. property is sysname and can be one of these values.

Value | Description
active | Active status value.
distribution_db | Distribution database status value.
login | Login status value.
password | Password status value.
security_mode | Security mode status value.
working_directory | Working directory status value.
NULL (default) | All available property options are printed.

[@value =] 'value'
Is the value for the given property. value is nvarchar(255), with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_changedistpublisher is used in all types of replication.

Permissions

Only members of the sysadmin fixed server role can execute sp_changedistpublisher.

See Also
sp_adddistpublisher | sp_helpdistpublisher
sp_dropdistpublisher | System Stored Procedures


sp_changedistributiondb

Updates the properties of the distribution database.

Syntax

sp_changedistributiondb [@database =] 'database'
[,[@property =] 'property'] [,[@value =] 'value']

Arguments
[@database =] 'database'
Is the name of the database. database is sysname, with no default.
[@property =] 'property'
Is the property to change for the given database. property is sysname, and can be one of these values.

Value | Description
history_retention | History table retention period.
max_distretention | Maximum distribution retention period. This value must be greater than or equal to the retention period of all transactional publications in the distribution database.
min_distretention | Minimum distribution retention period.
NULL (default) | All available property values are printed.

[@value =] 'value'
Is the new value for the specified property. value is nvarchar(255), with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_changedistributiondb is used in all types of replication.

Permissions

Only members of the sysadmin fixed server role can execute sp_changedistributiondb.

See Also
sp_adddistributiondb | sp_helpdistributiondb
sp_dropdistributiondb | System Stored Procedures


sp_changedistributor_property

Updates the properties of the Distributor.

Syntax

sp_changedistributor_property [[@property =] 'property']
[,[@value =] 'value']

Arguments
[@property =] 'property'
Is the property for a given Distributor. property is sysname, and can be one of these values.

Value | Description
heartbeat_interval | Maximum number of minutes that an agent can go without logging a progress message.
NULL (default) | All available property values are printed.

[@value =] 'value'
Is the value for the given Distributor property. value is varchar(255), with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_changedistributor_property is used in all types of replication.

Permissions

Only members of the sysadmin fixed server role can execute sp_changedistributor_property.

See Also
sp_adddistributor | sp_helpdistributor
sp_dropdistributor | System Stored Procedures


sp_changedistributor_password

Changes the password for a Distributor.

Syntax

sp_changedistributor_password [@password =] 'password'

Arguments
[@password =] 'password'
Is the new password. password is sysname, with no default. If the Distributor is local, the password of the distributor_admin system login is changed.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_changedistributor_password is used in all types of replication.

Permissions

Only members of the sysadmin fixed server role can execute sp_changedistributor_password.

See Also
System Stored Procedures


sp_changegroup

Changes the role membership for the security account of a user in the current database. This procedure is provided for backward compatibility. Microsoft® SQL Server™ version 7.0 uses roles instead of groups. Use sp_addrolemember instead.

Syntax

sp_changegroup [@grpname =] 'role', [@username =] 'user'

Arguments
[@grpname =] 'role'
Is the role the user is added to. role is sysname, with no default. role must exist in the current database.
[@username =] 'user'
Is the user to add to the role. user is sysname, with no default. The user must already exist in the current database. When specifying Windows NT users, specify the name the Windows NT user is known by in the database (added using sp_grantdbaccess).
Return Code Values

0 (success) or 1 (failure)

Remarks

Roles provide a mechanism for managing the permissions applied to the members of the role. When adding a user to a role, the user gains the permissions defined for the role.

When sp_changegroup is executed, the security account for user is added as a member of role, and removed from all other roles. sp_addrolemember and sp_droprolemember can be used to change role membership in a single role without affecting membership in other roles.

New database users can be added to roles at the same time they are given access to the database with sp_adduser.

Every user is a member of the default role public, if not explicitly added to some other role by sp_addrolemember.

sp_changegroup cannot be executed within a user-defined transaction.

Permissions

Members of the db_owner or db_securityadmin fixed database roles can execute sp_changegroup for any role in the database.

Role owners can execute sp_changegroup for the roles they own.

Examples

This example makes the user Albert a member of the developers role.

EXEC sp_changegroup 'developers', 'Albert'

See Also
sp_addrole | sp_dropgroup
sp_addrolemember | sp_helpgroup
sp_adduser | System Stored Procedures


sp_changemergearticle

Changes the properties of a merge article.

Syntax

sp_changemergearticle [@publication =] 'publication', [@article =]'article'
[,[@property =] 'property'] [,[@value =] 'value']

Arguments
[@publication =] 'publication'
Is the name of the publication in which the article exists. publication is sysname, with no default.
[@article =]'article'
Is the name of the article to change. article is sysname, with no default.
[@property =] 'property'
Is the property to change for the given article and publication. property is nvarchar(30), and can be one of these values.

Value | Description
description | Descriptive entry for the article.
pre_creation_command | Precreation command for the DROP TABLE, DELETE TABLE, or TRUNCATE TABLE statement.
creation_script | Path and name of an article schema script used to create target tables.
column_tracking | Setting for column level tracking. Can be changed only on inactive articles.
article_resolver | Custom resolver for the article.
resolver_info | Name of the stored procedure used as a custom resolver.
status | Status of the article.
subset_filterclause | WHERE clause specifying the horizontal filtering.
schema_option | Bitmap of the schema generation option for the given article.
NULL (default)

[@value =] 'value'
Is the new value for the specified property. value is nvarchar(1000), and can be one of these values.

Value | Description
description | Description of the article.
pre_creation_command | Can be none, drop, delete, or truncate.
creation_script | Name of the creation script.
conflict_table | NULL.
column_tracking | Can be true or false.
article_resolver | Default is NULL.
resolver_info | Name of the resolver stored procedure.
status | Status of the property. Can be active, unsynced, or inactive.
subset_filterclause | WHERE clause for horizontal filtering.
NULL (default)

Return Code Values

0 (success) or 1 (failure)

Remarks

sp_changemergearticle is used in merge replication.

Permissions

Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_changemergearticle.

See Also
sp_addmergearticle | sp_helpmergearticle
sp_dropmergearticle | System Stored Procedures


sp_changemergefilter

Changes some merge filter properties. The merge filter properties that can be changed include filtername and join_filterclause.

Syntax

sp_changemergefilter [@publication =] 'publication', [@article =]'article'
[@filtername =] 'filtername', [@property =] 'property',
[@value =] 'value'

Argument
[@publication =] 'publication'
Is the name of the publication. publication is sysname, with no default.
[@article =]'article'
Is the name of the article. article is sysname, with no default.
[@filtername =] 'filtername'
Is the name of the filter. filtername is sysname, with no default. The filter is a WHERE clause without the WHERE keyword.
[@property =] 'property'
Is the name of the property to change. property is sysname, with no default, and can be one of these values.

Value | Description
filtername | Name of the filter
join_filterclause | Filter clause
join_articlename | Name of the join article

[@value =] 'value'
Is the new value for the specified property. value is nvarchar(2000), with no default.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_changemergefilter is used in merge replication.

Add a new merge filter if you want to change the join table.

Permissions

Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_changemergefilter.

See Also
sp_ addmergefilter | sp_helpmergefilter
sp_dropmergefilter | System Stored Procedures


sp_changemergepublication

Changes the properties of a merge publication.

Syntax

sp_changemergepublication [@publication =] 'publication'
[,[@property =] 'property'] [,[@value =] 'value']

Arguments
[@publication =] 'publication'
Is the name of the publication. publication is sysname, with no default.
[@property =] 'property'
Is the property to change for the given publication. property is sysname, and can be one of these values.

Value | Description
description | Description of the publication.
status | Status of the publication.
retention | Amount of change, in days, to save for the given publication.
sync_mode | Mode of the synchronization.
allow_push | Push subscriptions are created for the given publication.
allow_pull | Pull subscriptions are created for the given publication.
allow_anonymous | Anonymous subscriptions are created for the given publication.
enabled_for_internet | The publication is enabled for the Internet.
centalized_conflicts | Conflict records are stored on the given Publisher.
snapshot_ready | The snapshot for the publication is available.
NULL (default)

[@value =] 'value'
Is the new value for the specified property. value is nvarchar(255), and can be one of these values.

Value | Description
description | Description of the publication.
status | Status of the property. Can be active, unsynced, or inactive.
retention | New replication period.
sync_mode | Can be native, character, bcp native, or bcp character.
allow_push | Can be true or false.
allow_pull | Can be true or false.
allow_anonymous | Can be true or false.
enabled_for_internet | Can be true or false.
centalized_conflicts | Can be true or false.
snapshot_ready | Can be true or false.
NULL (default)

Return Code Values

0 (success) or 1 (failure)

Remarks

sp_changemergepublication is used in merge replication.

Permissions

Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_changemergepublication.

See Also
sp_addmergepublication | sp_helpmergepublication
sp_dropmergepublication | System Stored Procedures


sp_changemergepullsubscription

Changes the properties of the merge pull subscription.

Syntax

sp_changemergepullsubscription [[@publication =] 'publication']
[,[@publisher =] 'publisher'] [,[@publisher_db =] 'publisher_db']
[,[@property =] 'property'] [,[@value =] 'value']

Argument
[@publication =] 'publication'
Is the name of the publication. publication is sysname, with a default of %.
[@publisher =] 'publisher'
Is the name of the Publisher. publisher is sysname, with a default of %.
[@publisher_db =] 'publisher_db'
Is the name of the Publisher database. publisher_db is sysname, with a default of %.
[@property =] 'property'
Is the name of the property to change. property is sysname, and can be one of these values.

Value | Description
sync_type | Subscription synchronization type.
priority | Can change only at the Publisher or Republisher.
description | Description of this merge pull subscription.
NULL (default)

[@value =] 'value'
Is the new value for the specified property. value is nvarchar(255), and can be one of these values.

Value | Description
sync_type | Can be automatic or none.
priority | Priority assigned.
description | Description of the subscription.
NULL (default)

Return Code Values

0 (success) or 1 (failure)

Remarks

sp_changemergepullsubscription is used in merge replication.

The current server and current database are assumed to be the Subscriber and Subscriber database.

Permissions

Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_changemergepullsubscription.

See Also
sp_addmergepullsubscription | sp_helpmergepullsubscription
sp_dropmergepullsubscription | System Stored Procedures


sp_changemergesubscription

Changes a merge push or pull subscription.

Syntax

sp_changemergesubscription [[@publication =] 'publication']
[,[@subscriber =] 'subscriber' [,[@subscriber_db =] 'subscriber_db']
[,[@property =] 'property'] [,[@value =] 'value']

Arguments
[@publication =] 'publication'
Is the name of the publication to change. publication is sysname, with a default of NULL The publication must already exist and must conform to the rules for identifiers.
[@subscriber =] 'subscriber'
Is the name of the Subscriber. subscriber is sysname with a default of NULL.
[@subscriber_db =] 'subscriber_db'
Is the name of the subscription database. subscriber_db is sysname, with a default of NULL
[@property =] 'property'
Is the property to change for the given publication. property is sysname, and can be one of these values.

Value | Description
sync_type | Subscription synchronization type.
priority | Can change only at the Publisher or Republisher.
description | Description of this merge subscription.
NULL (default)

[@value =] 'value'
Is the new value for the specified property. value is nvarchar(255), and can be one of these values.

Value | Description
sync_type | Can be automatic or none.
priority | Priority assigned.
description | Description of the subscription.
NULL (default)

Return Code Values

0 (success) or 1 (failure)

Remarks

sp_changemergesubscription is used in merge replication.

Permissions

Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_changemergesubscription.

See Also
sp_addmergesubscription | sp_helpmergesubscription
sp_dropmergesubscription | System Stored Procedures


sp_changeobjectowner

Changes the owner of an object in the current database.

Syntax

sp_changeobjectowner [@objname =] 'object', [@newowner =] 'owner'

Arguments
[@objname =] 'object'
Is the name of an existing table, view, or stored procedure in the current database. object is nvarchar(517), with no default. object can be qualified with the existing object owner, in the form existing_owner.object.
[@newowner =] 'owner'
Is the name of the security account that will be the new owner of the object. owner is sysname, with no default. owner must be a valid Microsoft® SQL Server™ user or role, or Microsoft Windows NT® user or group in the current database. When specifying Windows NT users or groups, specify the name the Windows NT user or group is known by in the database (added using sp_grantdbaccess).
Return Code Values

0 (success) or 1 (failure)

Remarks

The owner of an object (or the members of the group or role owning the object) has special permissions for the object. Object owners can execute any of the Transact-SQL statements related to the object (for example, INSERT, UPDATE, DELETE, SELECT, or EXECUTE) and can also manage the permissions for the object.

Use sp_changeobjectowner to change the owner of an object if the security account that owns the object has to be dropped but the object must be retained.

Use sp_changedbowner to change the owner of a database.

Permissions

Only members of the db_owner fixed database role, or a member of both the db_ddladmin and db_securityadmin fixed database roles can execute sp_changeobjectowner.

Examples

This example changes the owner of the authors table to Corporate\GeorgeW.

EXEC sp_changeobjectowner 'authors', 'Corporate\GeorgeW'

See Also
CREATE TABLE | System Stored Procedures
sp_changedbowner |


sp_changepublication

Changes a publication’s properties.

Syntax

sp_changepublication [[@publication =] 'publication']
[,[@property =] 'property'] [,[@value =] 'value']

Arguments
[@publication =] 'publication'
Is the name of the publication. publication is sysname, with a default of NULL.
[@property =] 'property'
Is the publication property to change. property is nvarchar(20), and can be one of these values.

Value | Description
description | Optional entry describing the publication.
taskid | Unique scheduler task ID created using sp_addtask. This is for backward compatibility only.
sync_method | Synchronization method. Can be native (produces native-mode bulk copy output of all tables) or character (produces a character-mode bulk copy output of all tables).
name | Name of the publication.
immediate_sync | Whether the synchronization files for the publication are created each time the Snapshot Agent runs. If true, the synchronization files are created or re-created each time the Snapshot Agent runs. Subscribers are able to get the synchronization files immediately after the subscription if the Snapshot Agent has been completed once before the subscription. New subscriptions get the newest synchronization files generated by the most recent execution of the Snapshot Agent. independent_agent must be true for immediate_sync to be true. If false, the synchronization files are created only if there are new subscriptions. Subscribers cannot receive the synchronization files after the subscription until the Snapshot Agents are started and completed.
independent_agent | Whether there is a stand-alone Distribution Agent for this publication. If true, there is a stand-alone Distribution Agent for this publication. If false, the the publication uses a shared Distribution Agent, and each Publisher database/Subscriber database pair has a shared Agent.
enabled_for_internet | Whether the publication is enabled for the Internet. If true, the synchronization files for the publication are put into the \Repldata\Ftp directory.
allow_push | Whether push subscriptions can be created for the given publication. If true, push subscriptions are allowed on the publication.
allow_pull | Whether pull subscriptions can be created for the given publication. If true, pull subscriptions are allowed on the publication.
allow_anonymous | Whether anonymous subscriptions can be created for the given publication. If true, immediate_sync must also be set to true. If true, anonymous subscriptions are allowed on the publication.
retention | Retention period in days for subscription activity. If a subscription is not active within the retention period, it is removed
status | Publication status. Can be inactive (publication data will not be available for Subscribers when the publication is first created) or active (publication data is available immediately for Subscribers).
repl_freq | Frequency of replication. Can be continuous (provides output of all log-based transactions) or snapshot (produces only scheduled synchronization events).
NULL (default)

[@value =] 'value'
Is the new property value. value is nvarchar(255), with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_changepublication is used in snapshot and transactional replication.

Permissions

Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_changepublication.

See Also
sp_addarticle | sp_enumfullsubscribers
sp_addpublication | sp_helparticle
sp_articlecolumn | sp_helparticlecolumns
sp_changearticle | sp_helppublication
sp_droparticle | System Stored Procedures
sp_droppublication |


sp_changesubscriber

Changes the options for a Subscriber. Any distribution task for the Publisher’s Subscribers is updated. This stored procedure writes to the MSsubscriber_info table in the distribution database.

Syntax

sp_changesubscriber [@subscriber =] 'subscriber' [,[@type =] type]
[,[@login =] 'login'] [,[@password =] 'password']
[,[@commit_batch_size =] commit_batch_size]
[,[@status_batch_size =] status_batch_size]
[,[@flush_frequency =] flush_frequency]
[,[@frequency_type =] frequency_type]
[,[@frequency_interval =] frequency_interval]
[,[@frequency_relative_interval =] frequency_relative_interval]
[,[@frequency_recurrence_factor =] frequency_recurrence_factor]
[,[@frequency_subday =] frequency_subday]
[,[@frequency_subday_interval =] frequency_subday_interval]
[,[@active_start_time_of_day =] active_start_time_of_day]
[,[@active_end_time_of_day =] active_end_time_of_day]
[,[@active_start_date =] active_start_date]
[,[@active_end_date =] active_end_date]
[,[@description =] 'description'] [,[@security_mode =] security_mode]

Arguments
[@subscriber =] 'subscriber'
Is the name of the Subscriber to change the options of. subscriber is sysname, with no default.
[@type =] type
Is the Subscriber type. type is tinyint, with a default of NULL. 0 indicates a Microsoft® SQL Server™ Subscriber. 1 indicates a non-SQL Server or other ODBC data source server Subscriber.
[@login =] 'login'
Is the standard security login ID. login is sysname, with a default of NULL.
[@password =] 'password'
Is the standard security password. password is sysname, with a default of %. % indicates there is no change to the password property.
[@commit_batch_size =] commit_batch_size
Is not used in SQL Server 7.0. Supported for backward compatibility only.
[@status_batch_size =] status_batch_size
Is not used in SQL Server 7.0. Supported for backward compatibility only.
[@flush_frequency =] flush_frequency
Is not used in SQL Server 7.0. Supported for backward compatibility only.
[@frequency_type =] frequency_type
Is the frequency with which to schedule the distribution task. frequency_type is int, and can be one of these values.

Value | Description
1 | One time
2 | On demand
4 | Daily
8 | Weekly
16 | Monthly
32 | Monthly relative
64 | Autostart
128 | Recurring
NULL (default)

[@frequency_interval =] frequency_interval
Is the interval for frequency_type. frequency_interval is int, with a default of NULL.
[@frequency_relative_interval =] frequency_relative_interval
Is the date of the distribution task. This parameter is used when frequency_type is set to 32 (monthly relative). frequency_relative_interval is int, and can be one of these values.

Value | Description
1 | First
2 | Second
4 | Third
8 | Fourth
16 | Last
NULL (default)

[@frequency_recurrence_factor =] frequency_recurrence_factor
Is how often the distribution task should recur during the defined frequency_type. frequency_recurrence_factor is int, with a default of NULL.
[@frequency_subday =] frequency_subday
Is how often to reschedule during the defined period. frequency_subday is int, and can be one of these values.

Value | Description
1 (default) | Once
2 | Second
4 | Minute
8 | Hour

[@frequency_subday_interval =] frequency_subday_interval
Is the interval for frequence_subday. frequency_subday_interval is int, with a default of NULL.
[@active_start_time_of_day =] active_start_time_of_day
Is the time of day when the distribution task is first scheduled, formatted as HHMMSS. active_start_time_of_day is int, with a default of NULL.
[@active_end_time_of_day =] active_end_time_of_day
Is the time of day when the distribution task stops being scheduled, formatted as HHMMSS. active_end_time_of_day is int, with a default of NULL.
[@active_start_date =] active_start_date
Is the date when the distribution task is first scheduled, formatted as YYYYMMDD. active_start_date is int, with a default of NULL.
[@active_end_date =] active_end_date
Is the date when the distribution task stops being scheduled, formatted as YYYYMMDD. active_end_date is int, with a default of NULL.
[@description =] 'description'
Is an optional text description. description is nvarchar(255), with a default of NULL. When upgrading to SQL Server version 7.0, existing MSsubscriber_info tables are modified to include a description column that is initialized to SQL Server 7.0.
[@security_mode =] security_mode
Is the implemented security mode. security_mode is int, and can be one of these values.

Value | Description
0 | SQL Server Authentication
1 | Windows NT Authentication
NULL (default)

Return Code Values

0 (success) or 1 (failure)

Remarks

sp_changesubscriber is used in all types of replication.

Permissions

Only members of the sysadmin fixed server role can execute sp_changesubscriber.

See Also
sp_addsubscriber | sp_helpserver
sp_dropsubscriber | sp_helpsubscriberinfo
sp_helpdistributiondb | System Stored Procedures


sp_changesubscriber_schedule

Changes a Subscriber’s schedule for the Distribution Agent and Merge Agent.

Syntax

sp_changesubscriber_schedule [@subscriber =] 'subscriber',
[@agent_type =] type [,[@frequency_type =] frequency_type]
[,[@frequency_interval =] frequency_interval]
[,[@frequency_relative_interval =] frequency_relative_interval]
[,[@frequency_recurrence_factor =] frequency_recurrence_factor]
[,[@frequency_subday =] frequency_subday]
[,[@frequency_subday_interval =] frequency_subday_interval] [,[@active_start_time_of_day =] active_start_time_of_day]
[,[@active_end_time_of_day =] active_end_time_of_day]
[,[@active_start_date =] active_start_date]
[,[@active_end_date =] active_end_date]

Arguments
[@subscriber =] 'subscriber'
Is the name of the Subscriber. subscriber is sysname. The name of the Subscriber must be unique in the database, must not already exist, and cannot be NULL.
[@agent_type =] type
Is the type of agent. agent_type is smallint, with a default of 0. 0 indicates a Distribution Agent. 1 indicates a Merge Agent.
[@frequency_type =] frequency_type
Is the frequency with which to schedule the distribution task. frequency_type is int, with a default of 64. There are 10 schedule columns.
[@frequency_interval =] frequency_interval
Is the value to apply to the frequency set by frequency_type. frequency_interval is int, with a default of 1.
[@frequency_relative_interval =] frequency_relative_interval
Is the date of the distribution task. frequency_relative_interval is int, with a default of 1.
[@frequency_recurrence_factor =] frequency_recurrence_factor
Is the recurrence factor used by frequency_type. frequency_recurrence_factor is int, with a default of 0.
[@frequency_subday =] frequency_subday
Is how often, in minutes, to reschedule during the defined period. frequency_subday is int, with a default of 4.
[@frequency_subday_interval =] frequency_subday_interval
Is the interval for frequency_subday. frequency_subday_interval is int, with a default of 5.
[@active_start_time_of_day =] active_start_time_of_day
Is the time of day when the distribution task is first scheduled. active_start_time_of_day is int, with a default of 0.
[@active_end_time_of_day =] active_end_time_of_day
Is the time of day when the distribution task stops being scheduled. active_end_time_of_day is int, with a default of 235959, which means 11:59:59 P.M. on a 24-hour clock.
[@active_start_date =] active_start_date
Is the date when the distribution task is first scheduled, formatted as YYYYMMDD. active_start_date is int, with a default of 0.
[@active_end_date =] active_end_date
Is the date when the distribution task stops being scheduled, formatted as YYYYMMDD. active_end_date is int, with a default of 99991231, which means December 31, 9999.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_changesubscriber_schedule is used in all types of replication.

You can change a schedule for Distribution Agent and assign a default schedule for Merge Agent by calling sp_changesubscriber.

Permissions

Only members of the sysadmin fixed server role can execute sp_changesubscriber_schedule.

See Also
sp_addsubscriber_schedule System Stored Procedures


sp_changesubstatus

Changes the status of an existing Subscriber.

Syntax

sp_changesubstatus [[@publication =] 'publication'] [,[@article =] 'article'] [,[@subscriber =] 'subscriber'] {,[@status =] 'status'}
[,[@previous_status =] 'previous_status']
[,[@destination_db =] 'destination_db']
[,[@frequency_type =] frequency_type]
[,[@frequency_interval =] frequency_interval]
[,[@frequency_relative_interval =] frequency_relative_interval]
[,[@frequency_recurrence_factor =] frequency_recurrence_factor]
[,[@frequency_subday =] frequency_subday]
[,[@frequency_subday_interval =] frequency_subday_interval]
[,[@active_start_time_of_day =] active_start_time_of_day]
[,[@active_end_time_of_day =] active_end_time_of_day]
[,[@active_start_date =] active_start_date]
[,[@active_end_date =] active_end_date]
[,[@optional_command_line =] 'optional_command_line']
[,[@distribution_jobid =] distribution_jobid]
[,[@from_auto_sync =] from_auto_sync]
[,[@ignore_distributor =] ignore_distributor]

Arguments
[@publication =] 'publication'
Is the name of the publication. publication is sysname, with a default of %. If publication is not specified, all publications are affected.
[@article =]'article'
Is the name of the article. It must be unique to the publication. article is sysname, with a default of %. If article is not specified, all articles are affected.
[@subscriber =] 'subscriber'
Is the name of the Subscriber to change the status of subscriber is sysname, with a default of %. If subscriber is not specified, status is changed for all Subscribers to the specified article.
[@status =] 'status'
Is the subscription status in the syssubscriptions table. status is sysname, with no default, and can be one of these values.

Value | Description
active | Subscriber synchronized and receiving data.
inactive | Subscriber entry exists without a subscription.
subscribed | Subscriber is requesting data but is not yet synchronized.

[@previous_status =] 'previous_status'
Is the previous status for the subscription. previous_status is sysname, with a default of NULL. This parameter allows you to change any subscriptions that currently have that status, thus allowing group functions on a specific set of subscriptions (for example, setting all active subscriptions back to subscribed).
[@destination_db =] 'destination_db'
Is the name of the destination database. destination_db is sysname, with a default of %.
[@frequency_type =] frequency_type
Is the frequency with which to schedule the distribution task. frequency_type is int, with a default of NULL. If no value is provided for frequency_type, sp_changesubstatus uses the frequency_type value used by sp_addsubscriber.
[@frequency_interval =] frequency_interval
Is the value to apply to the frequency set by frequency_type. frequency_interval is int, with a default of NULL.
[@frequency_relative_interval =] frequency_relative_interval
Is the date of the distribution task. This parameter is used when frequency_type is set to 32 (monthly relative). frequency_relative interval is int, and can be one of these values.

Value | Description
1 | First
2 | Second
4 | Third
8 | Fourth
16 | Last
NULL (default)

[@frequency_recurrence_factor =] frequency_recurrence_factor
Is the recurrence factor used by frequency_type. frequency_recurrence_factor is int, with a default of NULL.
[@frequency_subday =] frequency_subday
Is how often, in minutes, to reschedule during the defined period. frequency_subday is int, and can be one of these values.

Value | Description
1 | Once
2 | Second
4 | Minute
8 | Hour
NULL (default)

[@frequency_subday_interval =] frequency_subday_interval
Is the interval for frequency_subday. frequency_subday_interval is int, with a default of NULL.
[@active_start_time_of_day =] active_start_time_of_day
Is the time of day when the distribution task is first scheduled, formatted as HHMMSS. active_start_time_of_day is int, with a default of NULL.
[@active_end_time_of_day =] active_end_time_of_day
Is the time of day when the distribution task stops being scheduled, formatted as HHMMSS. active_end_time_of_day is int, with a default of NULL.
[@active_start_date =] active_start_date
Is the date when the distribution task is first scheduled, formatted as YYYYMMDD. active_start_date is int, with a default of NULL.
[@active_end_date =] active_end_date
Is the date when the distribution task stops being scheduled, formatted as YYYYMMDD. active_end_date is int, with a default of NULL.
[@optional_command_line =] 'optional_command_line'
Is an optional command prompt. optional_command_line is nvarchar(4000), with a default of NULL.
[@distribution_jobid =] distribution_jobid
Is the job ID of the Distribution Agent at the Distributor for the subscription when changing the subscription status from inactive to active. In other cases, it is not defined. If more that one Distribution Agent is involved in a single call to this stored procedure, the result is not defined. distribution_jobid is binary(16), with a default of NULL.
[@from_auto_sync =] from_auto_sync
Reserved for internal use only.
[@ignore_distributor =] ignore_distributor
Reserved for internal use only.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_changesubstatus is used in snapshot and transactional replication.

sp_changesubstatus changes the Subscriber’s status in the syssubscriptions table with the changed status. If required, it updates the article status in the sysarticles table to indicate active or inactive. If required, it sets the replication flag on or off in the sysobjects table for the replicated table.

Permissions

Only members of the sysadmin fixed server role, db_owner fixed database role, or the creator of the subscription can execute sp_changesubstatus.

See Also
sp_addsubscription | sp_helpsubscription
sp_dropsubscription | System Stored Procedures
sp_helpdistributor |


sp_change_subscription_properties

Updates the security information in the MSsubscription_properties table.

Syntax

sp_change_subscription_properties [@publisher =] 'publisher',
[@publisher_db =] 'publisher_db', [@publication =] 'publication',
[@property =] 'property', [@value =] 'value'

Arguments
[@publisher =] 'publisher'
Is the name of the Publisher. publisher is sysname, with no default.
[@publisher_db =] 'publisher_db'
Is the name of the Publisher database. publisher_db is sysname, with no default.
[@publication =] 'publication'
Is the name of the publication. publication is sysname, with no default.
[@property =] 'property'
Is the property to be changed. property is sysname, and can be one of these values.

Value | Description
publisher_login | Publisher login.
Publisher_password | Publisher password.
Publisher_security_mode Security mode implemented at the Publisher. Can be:
0 = SQL Server Authentication
1 = Windows NT Authentication
distributor_login | Distributor login.
Distributor_password | Distributor password.
Distributor_security_mode Security mode implemented at the Distributor. Can be:
0 = SQL Server Authentication
1 = Windows NT Authentication
encrypted_distributor_password | For internal use only.
Ftp_address | Network address of the FTP service for the Distributor.
Ftp_port | Port number of the FTP service for the Distributor.
Ftp_login | Username used to connect to the FTP service.
Ftp_password | User password used to connect to the FTP service.

[@value =] 'value'
Is the new value of the property. value is sysname, with no default.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_change_subscription_properties is used in all types of replication.

Permissions

Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_change_subscription_properties.

See Also
System Stored Procedures


sp_column_privileges

Returns column privilege information for a single table in the current environment.

Syntax

sp_column_privileges [@table_name =] 'table_name'
[,[@table_owner =] 'table_owner']
[,[@table_qualifier =] 'table_qualifier']
[,[@column_name =] 'column']

Arguments
[@table_name =] 'table_name'
Is the table used to return catalog information. table_name is sysname, with no default. Wildcard pattern matching is not supported.
[@table_owner =] 'table_owner'
Is the table owner of the table used to return catalog information. table_owner is sysname, with a default of NULL. Wildcard pattern matching is not supported. If table_owner is not specified, the default table visibility rules of the underlying database management system (DBMS) apply.

In Microsoft® SQL Server™, if the current user owns a table with the specified name, that table’s columns are returned. If table_owner is not specified and the current user does not own a table with the specified table_name, sp_column privileges looks for a table with the specified table_name owned by the database owner. If one exists, that table’s columns are returned.

[@table_qualifier =] 'table_qualifier'
Is the name of the table qualifier. table_qualifier is sysname, with a default of NULL. Various DBMS products support three-part naming for tables (qualifier.owner.name). In SQL Server, this column represents the database name. In some products, it represents the server name of the table’s database environment.
[@column_name =] 'column'
Is a single column used when only one column of catalog information is wanted. column is nvarchar(384), with a default of NULL. If column is not specified, all columns are returned. In SQL Server, column represents the column name as listed in the syscolumns table. column can include wildcard characters using wildcard matching patterns of the underlying DBMS. For maximum interoperability, the gateway client should assume only SQL-92 standard pattern matching (the % and _ wildcard characters).
Return Code Values

None

Result Sets

sp_column_privileges is equivalent to SQLColumnPrivileges in ODBC. The results returned are ordered by TABLE_QUALIFIER, TABLE_OWNER, TABLE_NAME, COLUMN_NAME, and PRIVILEGE.

Column name | Data type | Description
TABLE_QUALIFIER | sysname | Table qualifier name. This field can be NULL.
TABLE_OWNER | sysname | Table owner name. This field always returns a value.
TABLE_NAME | sysname | Table name. This field always returns a value.
COLUMN_NAME | sysname | Column name, for each column of the TABLE_NAME returned. This field always returns a value.
GRANTOR sysname Database username that has granted permissions on this COLUMN_NAME to the listed GRANTEE. In SQL Server, this column is always the same as the TABLE_OWNER. This field always returns a value.

The GRANTOR column can be either the database owner (TABLE_OWNER) or a user to whom the database owner granted permissions by using the WITH GRANT OPTION clause in the GRANT statement.
GRANTEE | sysname | Database username that has been granted permissions on this COLUMN_NAME by the listed GRANTOR. In SQL Server, this column always includes a database user from the sysusers table. This field always returns a value.
PRIVILEGE varchar(32) One of the available column permissions. Column permissions can be one of the following values (or other values supported by the data source when implementation is defined):

SELECT = GRANTEE can retrieve data for the columns.

INSERT = GRANTEE can provide data for this column when new rows are inserted (by the GRANTEE) into the table.

UPDATE = GRANTEE can modify existing data in the column.

REFERENCES = GRANTEE can reference a column in a foreign table in a primary key/foreign key relationship. Primary key/foreign key relationships are defined with table constraints.
IS_GRANTABLE | varchar(3) | Indicates whether the GRANTEE is permitted to grant permissions to other users (often referred to as “grant with grant” permission). Can be YES, NO, or NULL. An unknown (or NULL) value refers to a data source for which “grant with grant” is not applicable.

Remarks

With SQL Server, permissions are given with the GRANT statement and taken away by the REVOKE statement.

Permissions

Execute permission defaults to public role.

Examples

This example returns column privilege information for a table.

EXEC sp_column_privileges Employee

See Also
GRANT | System Stored Procedures
REVOKE |


sp_column_privileges_ex

Returns column privileges for the specified table on the specified linked server.

Syntax

sp_column_privileges_ex [@table_server =] 'table_server'
[,[@table_name =] 'table_name']
[,[@table_schema =] 'table_schema']
[,[@table_catalog =] 'table_catalog']
[,[@column_name =] 'column_name']

Arguments
[@table_server =] 'table_server'
Is the name of the linked server for which to return information. table_server is sysname, with no default.
[@table_name =] 'table_name'
Is the name of the table that contains the specified column. table_name is sysname, with a default of NULL.
[@table_schema =] 'table_schema'
Is the table schema. table_schema is sysname, with a default of NULL.
[@table_catalog =] 'table_catalog'
Is the name of the database in which the specified table_name resides. table_catalog is sysname, with a default of NULL.
[@column_name =] 'column_name'
Is the name of the column for which to provide privilege information. column_name is sysname, with a default of NULL (all common).
Return Code Values

None

Result Sets

This table show the result set columns. The results returned are order by TABLE_QUALIFIER, TABLE_OWNER, TABLE_NAME, COLUMN_NAME, and PRIVILEGE.

Column name | Data type | Description
TABLE_CAT | sysname | Table qualifier name. Various DBMS products support three-part naming for tables (qualifier.owner.name). In Microsoft® SQL Server™, this column represents the database name. In some products, it represents the server name of the table’s database environment. This field can be NULL.
TABLE_SCHEM | sysname | Table owner name. In SQL Server, this column represents the name of the database user who created the table. This field always returns a value.
TABLE_NAME | sysname | Table name. This field always returns a value.
COLUMN_NAME | sysname | Column name, for each column of the TABLE_NAME returned. This field always returns a value.
GRANTOR sysname Database username that has granted permissions on this COLUMN_NAME to the listed GRANTEE. In SQL Server, this column is always the same as the TABLE_OWNER. This field always returns a value.

The GRANTOR column can be either the database owner (TABLE_OWNER) or someone to whom the database owner granted permissions by using the WITH GRANT OPTION clause in the GRANT statement.
GRANTEE | sysname | Database username who has been granted permissions on this COLUMN_NAME by the listed GRANTOR. This field always returns a value.
PRIVILEGE varchar(32) One of the available column permissions. Column permissions can be one of the following values (or other values supported by the data source when implementation is defined):

SELECT = GRANTEE can retrieve data for the columns.

INSERT = GRANTEE can provide data for this column when new rows are inserted (by the GRANTEE) into the table.

UPDATE = GRANTEE can modify existing data in the column.

REFERENCES = GRANTEE can reference a column in a foreign table in a primary key/foreign key relationship. Primary key/foreign key relationships are defined with table constraints.
IS_GRANTABLE | varchar(3) | Indicates whether the GRANTEE is permitted to grant permissions to other users (often referred to as “grant with grant” permission). Can be YES, NO, or NULL. An unknown (or NULL) value refers to a data source where “grant with grant” is not applicable.

Permissions

Execute permission defaults to the public role.

Examples

This example returns column previlege information for a table on the specified linked server.

EXEC sp_column_privileges_ex @table_server = ‘Linked_Server’, @table_name = ‘Customers’, @table_catalog = ‘Norhtwind’

See Also
sp_table_privileges_ex System Stored Procedures


sp_columns

Returns column information for the specified tables or views that can be queried in the current environment.

Syntax

sp_columns [@table_name =] object
[,[@table_owner =] owner]
[,[@table_qualifier =] qualifier]
[,[@column_name =] column]
[,[@ODBCVer =] ODBCVer]

Arguments
[@table_name =] object
Is the name of the table or view used to return catalog information. object_name is nvarchar(384), with no default. Wildcard pattern matching is not supported.
[@table_owner =] owner
Is the object owner of the table or view used to return catalog information. owner is nvarchar(384), with a default of NULL. Wildcard pattern matching is not supported. If owner is not specified, the default table or view visibility rules of the underlying DBMS apply.

In Microsoft® SQL Server™, if the current user owns a table or view with the specified name, that table’s columns are returned. If owner is not specified and the current user does not own a table or view with the specified object, sp_columns looks for a table or view with the specified object owned by the database owner. If one exists, that table’s columns are returned.

[@table_qualifier =] qualifier
Is the name of the table or view qualifier. qualifier is sysname, with a default of NULL. Various DBMS products support three-part naming for tables (qualifier.owner.name). In SQL Server, this column represents the database name. In some products, it represents the server name of the table’s database environment.
[@column_name =] column
Is a single column and is used when only one column of catalog information is wanted. column is nvarchar(384), with a default of NULL. If column is not specified, all columns are returned. In SQL Server, column represents the column name as listed in the syscolumns table. column can include wildcard characters using the underlying DBMS’s wildcard matching patterns. For maximum interoperability, the gateway client should assume only SQL-92 standard pattern matching (the % and _ wildcard characters).
[@ODBCVer =] ODBCVer
Is the version of ODBC being used. ODBCVer is int, with a default of 2, indicating ODBC Version 2. Valid values are 2 or 3. Refer to the ODBC SQLColumns specification for the behavior differences between versions 2 and 3.
Return Code Values

None

Result Sets

The sp_columns catalog stored procedure is equivalent to SQLColumns in ODBC. The results returned are ordered by TABLE_QUALIFIER, TABLE_OWNER, and TABLE_NAME.

Column name | Data type | Description
TABLE_QUALIFIER | sysname | Table or view qualifier name. This field can be NULL.
TABLE_OWNER | sysname | Table or view owner name. This field always returns a value.
TABLE_NAME | sysname | Table or view name. This field always returns a value.
COLUMN_NAME | sysname | Column name, for each column of the TABLE_NAME returned. This field always returns a value.
DATA_TYPE | smallint | Integer code for ODBC data type. If this is a data type that cannot be mapped to an ODBC type, it is NULL. The native data type name is returned in the TYPE_NAME column.
TYPE_NAME | varchar(13) | String representing a data type. The underlying DBMS presents this data type name.
PRECISION | int | Number of significant digits. The return value for the PRECISION column is in base 10.
LENGTH | int | Transfer size of the data. (*)
SCALE | smallint | Number of digits to the right of the decimal point.
RADIX | smallint | Base for numeric datatypes.
NULLABLE | smallint | Specifies nullability. 1 = NULL is possible. 0 = NOT NULL.
REMARKS | varchar(254) | This field always returns NULL.
COLUMN_DEF | varchar(254) | Default value of the column.
SQL_DATA_TYPE | smallint | Value of the SQL data type as it appears in the TYPE field of the descriptor. This column is the same as the DATA_TYPE column, except for the datetime and SQL-92 interval data types. This column always returns a value.
SQL_DATETIME_SUB | smallint | Subtype code for datetime and SQL-92 interval data types. For other data types, this column returns NULL.
CHAR_OCTET_LENGTH | int | Maximum length in bytes of a character or integer data type column. For all other data types, this column returns NULL.
ORDINAL_POSITION | int | Ordinal position of the column in the table. The first column in the table is 1. This column always returns a value.
IS_NULLABLE | varchar(254) | Nullability of the column in the table. ISO rules are followed to determine nullability. An ISO SQL-compliant DBMS cannot return an empty string. YES = Column can include NULLS. NO = Column cannot include NULLS. This column returns a zero-length string if nullability is unknown. The value returned for this column is different from the value returned for the NULLABLE column.
SS_DATA_TYPE | tinyint | SQL Server data type, used by Open Data Services extended stored procedures.
* For more information about length, see the Microsoft ODBC Programmer’s Reference and SDK Guide, available separately.

Permissions

Execute permission defaults to the public role.

Examples

This example returns column information for a specified table.

EXEC sp_columns @table_name = ‘customers’

See Also
sp_tables System Stored Procedures


sp_columns_ex

Returns the column information, one row per column, for the given linked server table(s). sp_columns_ex returns column information only for the given column if column is specified.

Syntax

sp_columns_ex [@table_server =] 'table_server'
[, [@table_name =] 'table_name']
[, [@table_schema =] 'table_schema']
[, [@table_catalog =] 'table_catalog']
[, [@column_name =] 'column']
[, [@ODBCVer =] 'ODBCVer']

Arguments
[@table_server =] 'table_server'
Is the name of the linked server for which to return column information. table_server is sysname, with default.
[@table_name =] 'table_name'
Is the name of the table for which to return column information. table_name is sysname, with a default of NULL.
[@table_schema =] 'table_schema'
Is the schema name of the table for which to return column information. table_schema is sysname, with a default of NULL.
[@table_catalog =] 'table_catalog'
Is the catalog name of the table for which to return column information. table_catalog is sysname, with a default of NULL.
[@column_name =] 'column'
Is the name of the database column for which to provide information. column is sysname, with a default of NULL.
[@ODBCVer =] 'ODBCVer'
Is the version of ODBC being used. ODBCVer is int, with a default of 2, indicating ODBC Version 2. Valid values are 2 or 3. Refer to the ODBC SQLColumns specification for the behavior differences between versions 2 and 3.
Return Code Values

None

Result Sets
Column name | Data type | Description
TABLE_CAT | sysname | Table or view qualifier name. Various DBMS products support three-part naming for tables (qualifier.owner.name). In Microsoft® SQL Server™, this column represents the database name. In some products, it represents the server name of the table’s database environment. This field can be NULL.
TABLE_SCHEM | sysname | Table or view owner name. In SQL Server, this column represents the name of the database user that created the table. This field always returns a value.
TABLE_NAME | sysname | Table or view name. This field always returns a value.
COLUMN_NAME | sysname | Column name, for each column of the TABLE_NAME returned. This field always returns a value.
DATA_TYPE | smallint | Integer value corresponding to ODBC type indicators. If this is a data type that cannot be mapped to an ODBC type, it is NULL. The native data type name is returned in the TYPE_NAME column.
TYPE_NAME | varchar(13) | String representing a data type. The underlying DBMS presents this data type name.
COLUMN_SIZE | int | Number of significant digits. The return value for the PRECISION column is in base 10.
BUFFER_LENGTH | int | Transfer size of the data. (*)
DECIMAL_DIGITS | smallint | Number of digits to the right of the decimal point.
NUM_PREC_RADIX | smallint | Is the base for numeric data types.
NULLABLE | smallint | Specifies nullability. 1 = NULL is possible. 0 = NOT NULL.
REMARKS | varchar(254) | This field always returns NULL.
COLUMN_DEF | varchar(254) | Default value of the column.
SQL_DATA_TYPE | smallint | Value of the SQL data type as it appears in the TYPE field of the descriptor. This column is the same as the DATA_TYPE column, except for the datetime and SQL-92 interval data types. This column always returns a value.
SQL_DATETIME_SUB | smallint | Subtype code for datetime and SQL-92 interval data types. For other data types, this column returns NULL.
CHAR_OCTET_LENGTH | int | Maximum length in bytes of a character or integer data type column. For all other data types, this column returns NULL.
ORDINAL_POSITION | int | Ordinal position of the column in the table. The first column in the table is 1. This column always returns a value.
IS_NULLABLE | varchar(254) | Nullability of the column in the table. ISO rules are followed to determine nullability. An ISO SQL-compliant DBMS cannot return an empty string. YES = Column can include NULLS. NO = Column cannot include NULLS. This column returns a zero-length string if nullability is unknown. The value returned for this column is different from the value returned for the NULLABLE column.
SS_DATA_TYPE | tinyint | SQL Server data type, used by Open Data Services extended stored procedures.
* For more information about length, see the Microsoft ODBC Programmer’s Reference and SDK Guide, available separately.

Remarks

sp_columns_ex is executed by querying the COLUMNS rowset of the IDBSchemaRowset interface of the OLE DB provider corresponding to table_server. The table_name, table_schema, table_catalog, and column parameters are passed to this interface to restrict the rows returned.

sp_columns_ex returns an empty result set if the OLE DB provider of the specified linked server does not support the COLUMNS rowset of the IDBSchemaRowset interface.

Permissions

Execute permission defaults to the public role.

Examples

This example returns the data type of the title_id column of the titles table.

USE master

EXEC sp_columns_ex 'LONDON1', 'titles', 'dbo', 'pubs',

    'title_id'

See Also
sp_catalogs | sp_primarykeys
sp_foreignkeys | sp_tables_ex
sp_indexes | sp_table_privileges
sp_linkedservers | System Stored Procedures


sp_configure

Displays or changes global configuration settings for the current server.

Syntax

sp_configure [[@configname=]'name'] [,[@configvalue=] 'value']

Arguments
[@configname =] 'name'
Is the name of a configuration option. name is varchar(35), with a default of NULL. Microsoft® SQL Server™ understands any unique string that is part of the configuration name. If not specified, the entire list of options is returned.
[@configvalue =] value
Is the new configuration setting. value is int, with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Result Sets

When executed with no parameters, sp_configure returns a result set with five columns and orders the options in alphabetically ascending order. The config_value and the run_value do not necessarily have to be equivalent. For example, the system administrator may have changed an option with sp_configure, but has not executed the RECONFIGURE statement (for dynamic options) or restarted SQL Server (for nondynamic options).

Column name | Data type | Description
name | nvarchar(70) | Name of the configuration option
minimum | int | Minimum value of the configuration option
maximum | int | Maximum value of the configuration option
config_value | int | Value to which the configuration option was set using sp_configure (value in sysconfigures.value)
run_value | int | Value for the configuration option (value in syscurconfigs.value)

Remarks

Some options supported by sp_configure are designated as Advanced. By default, these options are not available for viewing and changing; setting the Show Advanced Options configuration option to 1 makes these options available.

When using sp_configure to change a setting, use the RECONFIGURE WITH OVERRIDE statement for the change to take immediate effect. Otherwise, the change takes effect after SQL Server is restarted.

Note Minimum and maximum memory configurations are dynamic in SQL Server. You can change them without restarting the server.

Use sp_configure to display or change server-level settings. Use sp_dboption to change database level settings, and the SET statement to change settings that affect only the current user session.

Note If the specified config_value is too high for an option, the run_value setting reflects the fact that SQL Server defaulted to dynamic memory rather than use an invalid setting.

Permissions

Execute permissions on sp_configure with no parameters or with only the first parameter default to all users. Execute permissions for sp_configure with both parameters, used to change a configuration option, default to the sysadmin fixed server role. RECONFIGURE permissions default to the sysadmin fixed server role, and are not transferable.

Examples
A. List the advanced configuration options

This example shows how to set and list all configuration options. Advanced configuration options are displayed by first setting the show advanced option to 1. After this has been changed, executing sp_configure with no parameters displays all configuration options.

USE master

EXEC sp_configure 'show advanced option', '1'

    Configuration option changed. Run the RECONFIGURE command to
install.

RECONFIGURE

EXEC sp_configure

B. Change a configuration option

This example sets the system recovery interval to 3 minutes.

USE master

EXEC sp_configure 'recovery interval', '3'

RECONFIGURE WITH OVERRIDE

See Also
RECONFIGURE | sp_dboption
SET | System Stored Procedures


sp_createstats

Creates single-column statistics for all eligible columns for all user tables in the current database. The new statistic has the same name as the column on which it is created. Computed columns and columns of the ntext, text, or image data types cannot be specified as statistics columns. Columns already having statistics are not touched (for example, the first column of an index or a column with explicitly created statistics). A CREATE STATISTICS statement is executed for each column that satisfies the above restrictions. FULLSCAN is executed if fullscan is specified.

Syntax

sp_createstats [@indexonly =] 'indexonly',
[@fullscan =] 'fullscan',
[@norecompute =] 'norecompute'

Arguments
[@indexonly =] 'indexonly'
Specifies that only the columns participating in an index should be considered for statistics creation. indexonly is char(9), with a default of NO.
[@fullscan =] 'fullscan'
Specifies that the FULLSCAN option is used with the CREATE STATISTICS statement. If fullscan is omitted, Microsoft® SQL Server™ performs a default sample scan. fullscan is char(9), with a default of NO.
[@norecompute =] 'norecompute'
Specifies that automatic recomputation of statistics is disabled for the newly created statistics. norecompute is char(12) with a default of NO.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Permissions

Permissions default to members of the sysadmin fixed server role and the db_owner fixed database role.

Examples

This example creates statistics for all eligible columns for all user tables in the current database.

EXEC sp_createstats

This example creates statistics for only the columns participating in an index.

EXEC sp_createstats ‘indexonly’

See Also
CREATE STATISTICS | UPDATE STATISTICS
DBCC SHOW_STATISTICS | System Stored Procedures
DROP STATISTICS |


sp_create_removable

Creates a removable media database. Creates three or more files (one for the system catalog tables, one the transaction log, and one or more for the data tables) and places the database on those files.

Syntax

sp_create_removable [@dbname =] 'dbname',
[@syslogical =] 'syslogical',
[@sysphysical =] 'sysphysical',
[@syssize =] syssize,
[@loglogical =] 'loglogical',
[@logphysical =] 'logphysical',
[@logsize =] logsize,
[@datalogical1 =] 'datalogical1',
[@dataphysical1 =] 'dataphysical1',
[@datasize1 =] datasize1
[…, [@datalogical16 =] 'datalogical16',
[@dataphysical16 =] 'dataphysical16',
[@datasize16 =] datasize16]

Arguments
[@dbname =] 'dbname'
Is the name of the database to create for use on removable media. dbname is sysname.
[@syslogical =] 'syslogical'
Is the logical name of the file that contains the system catalog tables. syslogical is sysname.
[@sysphysical =] 'sysphysical'
Is the physical name, including a fully qualified path, of the file that holds the system catalog tables. sysphysical is nvarchar(260).
[@syssize =] syssize
Is the size, in megabytes, of the file that holds the system catalog tables. syssize is int. The minimum syssize is 1.
[@loglogical =] 'loglogical'
Is the logical name of the file that contains the transaction log. loglogical is sysname.
[@logphysical =] 'logphysical'
Is the physical name, including a fully qualified path, of the file that contains the transaction log. logphysical is nvarchar(260).
[@logsize =] logsize
Is the size, in megabytes, of the file that contains the transaction log. logsize is int. The minimum logsize is 1.
[@datalogical1 =] 'datalogical'
Is the logical name of a file that contains the data tables. datalogical is sysname.

There must be from 1 through 16 data files. Usually, more than one data file is created when the database is expected to be large and must be distributed on multiple disks.

[@dataphysical1 =] 'dataphysical'
Is the physical name, including a fully qualified path, of a file that contains data tables. dataphysical is nvarchar(260).
[@datasize1 =] 'datasize'
Is the size, in megabytes, of a file that contains data tables. datasize is int. The minimum datasize is 1.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

If you want to make a copy of your database on a removable media (such as a compact disc) and distribute the database to other users, use this stored procedure.

Permissions

Only members of the sysadmin fixed server role can execute sp_create_removable.

Examples

This example creates the database inventory as a removable database.

sp_create_removable 'inventory',
  'invsys','c:\mssql7\data\invsys.mdf', 2,
  'invlog', 'c:\mssql7\data\invlog.ldf',4,

   'invdata','c:\mssql7\data\invdata.ndf',10

See Also
sp_attach_db | sp_detach_db
sp_attach_single_file_db | sp_helpfile
sp_certify_removable | sp_helpfilegroup
sp_dboption | System Stored Procedures
sp_dbremove |


sp_cursor_list

Reports the attributes of server cursors currently open for the connection.

Syntax

sp_cursor_list [@cursor_return =] cursor_variable_name OUTPUT,
[@cursor_scope =] cursor_scope

Arguments
[@cursor_return =] cursor_variable_name OUTPUT
Is the name of a declared cursor variable. cursor_variable_name is cursor, with no default. The cursor is a scrollable, dynamic, read-only cursor.
[@cursor_scope =] cursor_scope
Specifies the level of cursors to report. cursor_scope is int, with no default, and can be one of these values.

Value | Description
1 | Report all local cursors.
2 | Report all global cursors.
3 | Report both local and global cursors.

Return Code Values

None

Cursors Returned

sp_cursor_list returns its report as a Transact-SQL cursor output parameter, not as a result set. This allows Transact-SQL batches, stored procedures, and triggers to work with the output one row at a time. It also means the procedure cannot be called directly from database API functions. The cursor output parameter must be bound to a program variable, but the database APIs do not support binding cursor parameters or variables.

This is the format of the cursor returned by sp_cursor_list. The format of the cursor is the same as the format returned by sp_describe_cursor.

Column name | Data type | Description
reference_name | sysname | Name used to refer to the cursor. If the reference to the cursor was through the name given on a DECLARE CURSOR statement, the reference name is the same as cursor name. If the reference to the cursor was through a variable, the reference name is the name of the cursor variable.
cursor_name | sysname | Name of the cursor from a DECLARE CURSOR statement. If the cursor was created by setting a cursor variable to a cursor, the cursor name is a system-generated name.
cursor_scope | smallint | 1 = LOCAL 2 = GLOBAL
status | smallint | Same values as reported by the CURSOR_STATUS system function: 1 = The cursor referenced by the cursor name or variable is open. If the cursor is insensitive, static, or keyset, it has at least one row. If the cursor is dynamic, the result set has zero or more rows. 0 = The cursor referenced by the cursor name or variable is open but has no rows. Dynamic cursors never return this value. -1 = The cursor referenced by the cursor name or variable is closed. -2 = Applies only to cursor variables. There is no cursor assigned to the variable. Possibly, an OUTPUT parameter assigned a cursor to the variable, but the stored procedure closed the cursor before returning. -3 = A cursor or cursor variable with the specified name does not exist, or the cursor variable has not had a cursor allocated to it.
model | smallint | 1 = Insensitive (or static) 2 = Keyset 3 = Dynamic 4 = Fast Forward
concurrency | smallint | 1 = Read-only 2 = Scroll locks 3 = Optimistic
scrollable | smallint | 0 = Forward-only 1 = Scrollable
open_status | smallint | 0 = Closed 1 = Open
cursor_rows | int | Number of qualifying rows in the result set. For more information, see @@CURSOR_ROWS.
fetch_status | smallint | Status of the last fetch on this cursor. For more information, see @@FETCH_STATUS. 0 = Fetch successful. -1 = Fetch failed or is beyond the bounds of the cursor. -2 = The requested row is missing. -9 = There has been no fetch on the cursor.
column_count | smallint | Number of columns in the cursor result set.
row_count | smallint | Number of rows affected by the last operation on the cursor. For more information, see @@ROWCOUNT.
last_operation | smallint | Last operation performed on the cursor: 0 = No operations have been performed on the cursor. 1 = OPEN 2 = FETCH 3 = INSERT 4 = UPDATE 5 = DELETE 6 = CLOSE 7 = DEALLOCATE
cursor_handle | int | A unique value that identifies the cursor within the scope of the server.

Remarks

sp_cursor_list produces a list of the current server cursors opened by the connection and describes the attributes global to each cursor, such as the scrollability and updatability of the cursor. The cursors listed by sp_cursor_list include:

  • Transact-SQL server cursors.
  • API server cursors opened by an ODBC application that then called SQLSetCursorName to name the cursor.

Use sp_describe_cursor_columns for a description of the attributes of the result set returned by the cursor. Use sp_describe_cursor_tables for a report of the base tables referenced by the cursor. sp_describe_cursor reports the same information as sp_cursor_list, but only for a specified cursor.

Permissions

Execute permissions default to the public role.

Examples

This example opens a global cursor and uses sp_cursor_list to report on the attributes of the cursor.

USE Northwind

GO

-- Declare and open a keyset-driven cursor.

DECLARE abc CURSOR KEYSET FOR

SELECT LastName

FROM Employees

WHERE LastName LIKE 'S%'

OPEN abc

-- Declare a cursor variable to hold the cursor output variable

-- from sp_cursor_list.

DECLARE @Report CURSOR

-- Execute sp_cursor_list into the cursor variable.

EXEC master.dbo.sp_cursor_list @cursor_return = @Report OUTPUT,

        @cursor_scope = 2

-- Fetch all the rows from the sp_cursor_list output cursor.

FETCH NEXT from @Report

WHILE (@@FETCH_STATUS <> -1)

BEGIN

    FETCH NEXT from @Report

END

-- Close and deallocate the cursor from sp_cursor_list.

CLOSE @Report

DEALLOCATE @Report

GO

-- Close and deallocate the original cursor.

CLOSE abc

DEALLOCATE abc

GO

See Also

System Stored Procedures


sp_cycle_errorlog

Closes the current error log file and cycles the error log extension numbers just like a server restart. The new error log contains version and copyright information and a line indicating that the new log has been created.

Syntax

sp_cycle_errorlog

Return Code Values

None

Result Sets

None

Remarks

Every time SQL Server is started, the current error log is renamed to errorlog.1; errorlog.1 becomes errorlog.2, errorlog.2 becomes errorlog.3, and so on. sp_cycle_errorlog enables you to cycle the error log files without stopping and starting the server.

Permissions

Execute permissions for sp_cycle_errorlog are restricted to members of the sysadmin fixed server role.

Examples

EXEC sp_cycle_errorlog

See Also
System Stored Procedures


sp_databases

Lists databases that reside in the Microsoft® SQL Server™ installation or are accessible through a database gateway.

Syntax

sp_databases

Return Code Values

None

Result Sets
Column name | Data type | Description
DATABASE_NAME | sysname | Name of the database. In SQL Server, this column represents the database name as stored in the sysdatabases system table.
DATABASE_SIZE | int | Size of database, in kilobytes.
REMARKS | varchar(254) | For SQL Server, this field always returns NULL.

Remarks

In SQL Server, sp_databases returns the databases listed in the sysdatabases system table. Because some database management systems (DBMS) accessed by database gateways do not have the concept of a database, this stored procedure may return no rows if sent to a Microsoft Open Data Services - based gateway.

Database names that are returned can be used as parameters in the USE statement to change the current database context.

sp_databases has no equivalent in Open Database Connectivity (ODBC).

Permissions

Execute permissions default to the public role.


sp_datatype_info

Returns information about the data types supported by the current environment.

Syntax

sp_datatype_info [[@data_type =] data_type]
[, [@ODBCVer =] odbc_version]

Arguments
[@data_type =] data_type
Is the code number for the specified data type. To obtain a list of all data types, omit this parameter. data_type is int, with a default of 0.
[@ODBCVer =] odbc_version
Is the version of ODBC being used. odbc_version is tinyint, with a default of 2.
Return Code Values

None

Result Sets
Column name | Data type | Description
TYPE_NAME | sysname | DBMS-dependent data type.
DATA_TYPE | smallint | Code for the ODBC type to which all columns of this type are mapped.
PRECISION | int | Maximum precision of the data type on the data source. NULL is returned for data types for which precision is not applicable. The return value for the PRECISION column is in base 10.
LITERAL_PREFIX | varchar(32) | Character(s) used before a constant. For example, a single quotation mark (') for character types and 0x for binary in Microsoft® SQL Server™.
LITERAL_SUFFIX | varchar(32) | Character(s) used to terminate a constant. For example, a single quotation mark (') for character types and none for binary.
CREATE_PARAMS | varchar(32) | Description of the creation parameters for this data type. For example, decimal is “precision, scale”, float is NULL, and varchar is “max_length”.
NULLABLE | smallint | Specifies nullability. 1 = Allows null values. 0 = Does not allow null values.
CASE_SENSITIVE | smallint | Specifies case sensitivity. 1 = All columns of this type are case-sensitive (for collations). 0 = All columns of this type are case-insensitive.
SEARCHABLE | smallint | Column type. 1 = Columns of this type can be used in a WHERE clause. 0 = Columns of this type cannot be used in a WHERE clause.
UNSIGNED_ATTRIBUTE | smallint | Specifies the sign of the data type. 1 = Data type unsigned. 0 = Data type signed.
MONEY | smallint | Specifies the money data type. 1 = money data type. 0 = Not a money data type.
AUTO_INCREMENT | smallint | Specifies autoincrementing. 1 = Autoincrementing. 0 = Not autoincrementing. NULL = Attribute not applicable. An application can insert values into a column that has this attribute, but it cannot update the values in the column. AUTO_INCREMENT is valid only for category data types.
LOCAL_TYPE_NAME | sysname | Localized version of the data source-dependent name of the data type. For example, DECIMAL is DECIMALE in French. NULL is returned if a localized name is not supported by the data source.
MINIMUM_SCALE | smallint | Minimum scale of the data type on the data source. If a data type has a fixed scale, the MINIMUM_SCALE and MAXIMUM_SCALE columns both contain this value. NULL is returned where scale is not applicable.
MAXIMUM_SCALE | smallint | Maximum scale of the data type on the data source. If the maximum scale is not defined separately on the data source, but is instead defined to be the same as the maximum precision, this column contains the same value as the PRECISION column.
SQL_DATA_TYPE | smallint | Value of the SQL data type as it appears in the TYPE field of the descriptor. This column is the same as the DATA_TYPE column, except for the datetime and ANSI interval data types. This field always returns a value.
SQL_DATETIME_SUB | smallint | datetime or ANSI interval subcode if the value of SQL_DATA_TYPE is SQL_DATETIME or SQL_INTERVAL. For data types other than datetime and ANSI interval, this field is NULL.
NUM_PREC_RADIX | int | Number of bits or digits for calculating the maximum number that a column can hold. If the data type is an approximate numeric data type, this column contains the value 2 to indicate a number of bits. For exact numeric types, this column contains the value 10 to indicate a number of decimal digits. Otherwise, this column is NULL. By combining the precision with radix, the application can calculate the maximum number that the column can hold.
INTERVAL_PRECISION | smallint | Value of interval leading precision if data_type is interval; otherwise NULL.
USERTYPE | smallint | usertype value from the systypes table.

Remarks

sp_datatype_info is equivalent to SQLGetTypeInfo in ODBC. The results returned are ordered by DATA_TYPE and then by how closely the data type maps to the corresponding ODBC SQL data type.

Permissions

Execute permissions default to the public role.

Examples

This example retrieves information for the sysname and nvarchar data types by specifying the DATA_TYPE value of -9.

USE master

EXEC sp_datatype_info -9

See Also
Data Types System Stored Procedures


sp_dbcmptlevel

Sets certain database behaviors to be compatible with the specified earlier version of Microsoft® SQL Server™.

Syntax

sp_dbcmptlevel [[@dbname =] name] [, [@new_cmptlevel =] version]

Arguments
[@dbname =] name
Is the name of the database whose compatibility level is to be changed. Database names must conform to the rules for identifiers. name is sysname, with a default of NULL.
[@new_cmptlevel =] version
Is the version of SQL Server with which the database is to be made compatible. version is tinyint, with a default of NULL. The value must be 70, 65, or 60.
Return Code Values

0 (success) or 1 (failure)

Result Sets

sp_dbcmptlevel returns this message if no parameters are specified or if the name parameter is not specified:

Valid values of database compatibility level are 60, 65, or 70.

If name is specified with no version, SQL Server displays a message with the compatibility setting for the named database.

Executing sp_dbcmptlevel with the value 70 restores the level of functionality associated with SQL Server 7.0.

Remarks

Use sp_dbcmptlevel as an interim migration aid. If existing SQL Server version 6.x applications are affected by the differences in SQL Server version 7.0 behaviors controlled by the compatibility level setting of sp_dbcmptlevel, use this procedure to set the earlier version behaviors until the application can be converted to work properly with the SQL Server 7.0 compatibility level. sp_dbcmptlevel does not restore full backward compatibility.

sp_dbcmptlevel affects the behaviors in the specified database, not the entire server. The compatibility setting for a database takes effect when the database is made the current database with the USE statement, or if the database is the default database for the login. When a stored procedure is executed, the current compatibility level of the database in which the procedure is defined is used. All stored procedures in the database are recompiled when the compatibility setting is changed in that database.

Setting the compatibility level to 65 or 60 affects these behaviors.

Compatibility level setting of either
60 or 65 		Compatibility level setting of 70 (default)
The result sets of SELECT statements with a GROUP BY clause and no ORDER BY clause are sorted by the GROUP BY columns. | A GROUP BY clause does no sorting on its own. An ORDER BY clause must be explicitly specified for SQL Server to sort any result set. For more information, see SELECT.
Columns prefixed with table aliases are accepted in the SET clause of an UPDATE statement. | Table aliases are not accepted in the SET clause of an UPDATE statement. The table or view specified in the SET clause must match that specified immediately following the UPDATE keyword. For more information, see UPDATE.
bit columns created without an explicit NULL or NOT NULL option in CREATE TABLE or ALTER TABLE are created as NOT NULL. | The nullability of bit columns without explicit nullability is determined by either the session setting of SET ANSI_NULL_DFLT_ON or SET ANSI_NULL_DFLT_OFF; or the database setting of SET ANSI NULL DEFAULT. For more information, see SET.
The ALTER COLUMN clause cannot be used on ALTER TABLE. | The ALTER COLUMN clause can be used on ALTER TABLE. For more information, see ALTER TABLE.
A trigger created for a table replaces any existing triggers of the same type (INSERT, UPDATE, DELETE). The WITH APPEND option of CREATE TRIGGER can be used to create multiple triggers of the same type. | Triggers of the same type are appended. Trigger names must be unique. The WITH APPEND option is assumed. For more information, see CREATE TRIGGER.
When a batch or procedure contains invalid object names, a warning is returned when the batch is parsed or compiled, and an error message is returned when the batch is executed. | No warning is returned when the batch is parsed or compiled, and an error message is returned when the batch is executed.
Queries of the following form are properly executed by ignoring table Y and inserting the SELECT statement results into table X.

INSERT X

SELECT select_list INTO Y

 SQL Server returns a syntax error when this same query is executed.
The empty string literal (‘ ‘) is interpreted as a single blank. | The empty string literal (‘ ‘) is interpreted as an empty string.
DATALENGTH(‘‘) returns 1 (‘‘ parsed as a single space).
DATALENGTH(N’’) returns 2 (N’’ parsed as a single Unicode space).
LEFT(‘123’, m) returns NULL when m = 0.
LEFT(N’123’, m) returns NULL when
m = 0.
LTRIM(‘ ‘) returns NULL.
LTRIM(N’ ‘) returns NULL.
REPLICATE(‘123’, m) returns NULL when m = 0.
REPLICATE(N’123’, m) returns NULL when m = 0.
RIGHT(N’123’, m) returns NULL when
m = 0.
RIGHT(‘123’, m) returns NULL when
m = 0.
RIGHT(‘123’, m) returns NULL when m is negative.
RIGHT(N’123’, m) returns NULL when m is negative.
RTRIM(‘ ‘) returns NULL.
RTRIM(N’ ‘) returns NULL.
SPACE(0) returns NULL.
SUBSTRING(‘123’, m, n) returns NULL when m < length of the string or when
n = 0.
SUBSTRING(N’123’, m, n) returns NULL when m > length of the string or when
n = 0.
UPDATETEXT table.textcolumn textpointer > 0 NULL NULL results in a NULL value. 		DATALENGTH(‘‘) returns 0.
DATALENGTH(N’’) returns 0.
LEFT(‘123’, m) returns an empty string when m = 0.
LEFT(N’123’, m) returns an empty string when m = 0.
LTRIM(‘ ‘) returns an empty string.
LTRIM(N’ ‘) returns an empty string.
REPLICATE(‘123’, m) returns an empty string when m = 0.
REPLICATE(N’123’, m) returns an empty string when m = 0.
RIGHT(‘123’, m) returns an empty string when m = 0.
RIGHT(N’123’, m) returns an empty string when m = 0.
RIGHT(‘123’, m) returns error when m is negative.
RIGHT(N’123’, m) returns error when m is negative.
RTRIM(‘ ‘) returns an empty string.
RTRIM(N’ ‘) returns an empty string.
SPACE(0) returns an empty string.
SUBSTRING(‘123’, m, n) returns an empty string when m < length of the string or when n = 0.
SUBSTRING(N’123’, m, n) returns an empty string when m > length of the string or when n = 0.
UPDATETEXT table.textcolumn textpointer > 0 NULL NULL results in empty text.
The CHARINDEX and PATINDEX functions return null only if both the pattern and the expression are null. | The CHARINDEX and PATINDEX functions return NULL when any input parameters are NULL.
References to text or image columns in the inserted and deleted tables appear as NULL. | References to text or image columns in the inserted and deleted tables are not allowed.
Allows UPDATETEXT to initialize text columns to NULL. | UPDATETEXT initializes text columns to an empty string. WRITETEXT initializes text columns to NULL.
The concatenation of null yields null setting of sp_dboption is off (disabled); which returns an empty string if any operands in a concatenation operation is null. | The concatenation of null yields null setting of sp_dboption is on (enabled), which returns a NULL if any operands in a concatenation operation is null.
In an INSERT statement, a SELECT returning a scalar value is allowed in the VALUES clause. | The INSERT statement cannot have a SELECT statement in the VALUES clause as one of the values to be inserted.
A ROLLBACK statement in a stored procedure referenced in an INSERT table EXEC procedure statement causes the INSERT to be rolled back, but the batch continues. | A ROLLBACK statement in a stored procedure referenced by an INSERT…EXEC statement causes the entire transaction to be rolled back and the batch stops executing.
Retrieving text or image columns from the inserted or deleted tables inside a trigger returns NULL values for text or image columns. | Retrieving text or image columns from the inserted or deleted tables inside a trigger is not allowed and causes an error.

The compatibility setting also has an effect on reserved keywords. This table shows the words that are reserved at the specified level, but are valid for use in object names at lower levels. At lower compatibility levels, the language features corresponding to the reserved keywords in upper levels are not available.

Compatibility level setting | Reserved keywords
70 | BACKUP, DENY, PERCENT, RESTORE, TOP
65 | AUTHORIZATION, CASCADE, CROSS, DISTRIBUTED, ESCAPE, FULL, INNER, JOIN, LEFT, OUTER, PRIVILEGES, RESTRICT, RIGHT, SCHEMA, WORK

The compatibility level setting cannot be changed in the master database, but it can be changed in the model database to take effect in all new databases. The compatibility level cannot be changed inside a stored procedure or in Transact-SQL strings executed with the EXEC(‘string’) syntax. The compatibility level should not be changed inside a batch of Transact-SQL statements.

Permissions

sp_dbcmptlevel permissions default to members of the db_owner and sysadmin fixed database roles.

Examples

This example creates a procedure named distributed, which is a SQL Server reserved keyword, by setting the compatibility level setting for the pubs database to 60.

CREATE PROCEDURE distributed

AS

PRINT 'This won''t happen'

EXEC sp_dbcmptlevel 'pubs', 60

CREATE PROCEDURE distributed

AS

PRINT 'You are in a procedure that could not be defined'

PRINT 'in a version of SQL Server 6.5 or greater'

PRINT 'without the compatibility setting.'

EXEC distributed

Here is the result set:

Msg 156, Level 15, State 1

Incorrect syntax near the keyword 'distributed'.

DBCC execution completed. If DBCC printed error messages, see your System Administrator.

You are in a procedure that could not be defined

in a version of SQL Server 6.5 or greater

without the compatibility setting.

See Also
EXECUTE | sp_dboption
Reserved Keywords | System Stored Procedures


sp_dbfixedrolepermission

Displays the permissions for each fixed database role.

Syntax

sp_dbfixedrolepermission [[@rolename =] 'role']

Arguments
[@rolename =] 'role'
Is the name of a valid Microsoft® SQL Server™ fixed database role. role is sysname, with a default of NULL. If role is not specified, the permissions for all fixed database roles are displayed.
Return Code Values

0 (success) or 1 (failure)

Result Sets
Column name | Data type | Description
DbFixedRole | sysname | Name of the fixed database role
Permission | nvarchar(70) | Permissions associated with DbFixedRole

Remarks

To display a list of the fixed database roles, execute sp_helpdbfixedrole. These are the fixed database roles.

Fixed database role | Description
db_owner | Database owners
db_accessadmin | Database access administrators
db_securityadmin | Database security administrators
db_ddladmin | Database DDL administrators
db_backupoperator | Database backup operators
db_datareader | Database data readers
db_datawriter | Database data writers
db_denydatareader | Database deny data readers
db_denydatawriter | Database deny data writers

The permissions of the db_owner fixed database role span all of the other fixed database roles. To display the permissions for fixed server roles, execute sp_srvrolepermission.

The permissions listed in the result set include the Transact-SQL statements that can be executed, as well as other special activities that can be performed by members of the database role.

Permissions

All users have permissions to execute sp_dbfixedrolepermission.

Examples

This example displays the permissions for all fixed database roles.

EXEC sp_dbfixedrolepermission

See Also
sp_addrolemember | sp_srvrolepermission
sp_droprolemember | System Stored Procedures
sp_helpdbfixedrole |


sp_dboption

Displays or changes database options. sp_dboption should not be used on either the master or tempdb databases.

Syntax

sp_dboption [[@dbname =] 'database']
[, [@optname =] 'option_name']
[, [@optvalue =] 'value']

Arguments
[@dbname =] 'database'
Is the name of the database in which to set the specified option. database is sysname, with a default of NULL.
[@optname =] 'option_name'
Is the name of the option to set. It is not necessary to enter the complete option name. Microsoft® SQL Server™ recognizes any part of the name that is unique. Enclose the option name with quotation marks if it includes embedded blanks or is a keyword. If this parameter is omitted, sp_dboption lists the options that are on. option_name is varchar(35), with a default of NULL.
[@optvalue =] 'value'
Is the new setting for option_name. If this parameter is omitted, sp_dboption returns current setting. value can be true or false or on or off. value is varchar(10), with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Result Sets

If no parameters are supplied, this is the result set:

Column name | Data type | Description
Settable database options | nvarchar(35) | All of the settable database options

If database is the only supplied parameter, this is the result set:

Column name | Data type | Description
The following options are set: | nvarchar(35) | The options that are set for the database

If option_name is supplied, this is the result set:

Column name | Data type | Description
OptionName | nvarchar(35) | Name of the option
CurrentSetting | char(3) | Whether the option is on or off

If value is supplied, sp_dboption does not return a result set.

Remarks

These are the options set by sp_dboption.

Option | Description
auto create statistics | When true, any missing statistics needed by a query for optimization are automatically built during optimization. For more information, see CREATE STATISTICS.
auto update statistics | When true, any out of date statistics needed by a query for optimization are automatically built during optimization. For more information, see UPDATE STATISTICS.
autoclose | When true, the database is shutdown cleanly and its resources are freed after the last user exits.
autoshrink | When true, the database files are candidates for automatic periodic shrinking.
ANSI null default | When true, CREATE TABLE follows the SQL-92 rules to determine if a column allows null values.
ANSI nulls | When true, all comparisons to a null value evaluate to UNKNOWN. When false, comparisons of non-UNICODE values to a null value evaluate to TRUE if both values are NULL.
ANSI warnings | When true, errors or warnings are issued when conditions such as “divide by zero” occur.
concat null yields null | When true, if either operand in a concatenation operation is NULL, the result is NULL.
cursor close on commit | When true, any cursors that are open when a transaction is committed or rolled back are closed. When false, such cursors remain open when a transaction is committed. When false, rolling back a transaction closes any cursors except those defined as INSENSITIVE or STATIC.
dbo use only | When true, only the database owner can use the database.
default to local cursor | When true, cursor declarations default to LOCAL.
merge publish | When true, the database can be published for a merge replication.
offline | When true, the database is offline.
published | When true, the database can be published for replication.
quoted identifier | When true, double quotation marks can be used to enclose delimited identifiers.
read only | When true, users can only read data in the database, not modify it. The database cannot be in use when a new value for the read only option is specified. The master database is the exception, and only the system administrator can use master while the read only option is being set.
recursive triggers | When true, enables recursive firing of triggers.
select into/bulkcopy | When true, the SELECT INTO statement and fast bulk copies are allowed.
single user | When true, only one user at a time can access the database.
subscribed | When true, the database can be subscribed for publication.
torn page detection | When true, incomplete pages can be detected.
trunc. log on chkpt. | When true, a checkpoint truncates the inactive part of the log when the database is in log truncate mode. This is the only option you can set for the master database.

The database owner or system administrator can set or turn off particular database options for all new databases by executing sp_dboption on the model database.

After sp_dboption has been executed, a checkpoint executes in the database for which the option was changed. This causes the change to take effect immediately.

sp_dboption changes settings for a database. Use sp_configure to change server-level settings, and the SET statement to change settings that affect only the current session.

Important If the autoclose, autoshrink, dbo use only, read only, single user, select into/bulkcopy, or torn page detection settings have changed for the database since the last full database backup, these settings must be reset before restoring the database.

Permissions

Execute permissions to display only the list of options (using sp_dboption with no parameters) default to all users. Execute permissions to change an option (using sp_dboption with parameters) default to members of the sysadmin fixed server role or the db_owner fixed database role for the database for which the option is to be changed.

Examples
A. Set a database to read-only

This example makes the pubs database read-only.

USE master

EXEC sp_dboption 'pubs', 'read only', 'TRUE'

Here is the result set:

CHECKPOINTing database that was changed.

B.Turn off an option

B. Turn off an option

This example makes the pubs database writable again.

USE master

EXEC sp_dboption 'pubs', 'read only', 'FALSE'

Here is the result set:

CHECKPOINTing database that was changed.

C. Take a database offline

This example takes the sales database offline if there are no users accessing the database.

USE master

EXEC sp_dboption 'sales', 'offline', 'TRUE'

Here is the result set:

CHECKPOINTing database that was changed.

See Also
SET | System Stored Procedures
sp_configure |


sp_dbremove

Removes a database and all files associated with that database.

Important This procedure is provided for backward compatibility only. For removable media databases, use sp_detach_db to remove a database from the server.

Syntax

sp_dbremove [@dbname =] 'database'[, [@dropdev =] 'dropdev']

Arguments
[@dbname =] 'database'
Is the name of the database to be removed. database is sysname, with a default value of NULL.
[@dropdev =] 'dropdev'
Is a flag provided for backward compatibility only and is currently ignored. dropdev has the value dropdev.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Permissions

Execute permissions default to members of the sysadmin fixed server role or db_owner fixed database role for the database for which the drop will be performed.

Example

This example removes a database named sales and all files associated with it.

sp_dbremove sales

See Also
ALTER DATABASE | DBCC
CREATE DATABASE | sp_detach_db


sp_defaultdb

Changes the default database for a login.

Syntax

sp_defaultdb [@loginame =] 'login' ,[@defdb =] 'database'

Arguments
[@loginame =] 'login'
Is the login name. login is sysname, with no default. login can be an existing Microsoft® SQL Server™ login or a Microsoft Windows NT® user or group. If the Windows NT user or group does not exist in SQL Server, it is automatically added.
[@defdb =] 'database'
Is the name of the new default database. database is sysname, with no default. database must already exist.
Return Code Values

0 (success) or 1 (failure)

Remarks

When a client connects with SQL Server, the default database defined for its login becomes the current database with an explicit USE statement. The default database can be defined when the login is added with sp_addlogin. When executing sp_addlogin the master database is the default database if a database is not specified.

After sp_defaultdb is executed, the login is connected to the new database the next time the user logs in. However, sp_defaultdb does not automatically give the login access to that database. The database owner (dbo) must give database access to the login through sp_grantdbaccess, or there must be a guest user specified in the database.

It is recommended that sp_defaultdb be used to change the default database for all logins other than members of the sysadmin fixed server role. This prevents users from inadvertently trying to use or create objects in the master database.

sp_defaultdb cannot be executed within a user-defined transaction.

Permissions

Execute permissions default to the public role for users changing the default database for their own logins. Only members of the syadmin or securityadmin fixed server roles can execute sp_defaultdb for other logins.

Examples

This example sets pubs as the default database for user Victoria.

EXEC sp_defaultdb 'Victoria', 'pubs'

See Also
sp_addlogin | USE
sp_droplogin | System Stored Procedures
sp_grantdbaccess |


sp_defaultlanguage

Changes the default language of a login.

Syntax

sp_defaultlanguage [@loginame =] 'login' [,[@language =] 'language']

Arguments
[@loginame =] 'login'
Is the login name. login is sysname, with no default. login can be an existing Microsoft® SQL Server™ login or a Microsoft Windows NT® user or group. If the Windows NT user or group does not exist in SQL Server, it is automatically added.
[@language =] 'language'
Is the default language of the login. language is sysname, with a default of NULL. language must be a valid language on the server. If language is not specified, the server’s default language (defined by the sp_configure configuration variable default language) is used.
Return Code Values

0 (success) or 1 (failure)

Remarks

A default language can be set by using either sp_defaultlanguage or sp_addlogin when the login is initially added to SQL Server. Use sp_helplanguage to display a list of the valid language options.

Any user can use the SET LANGUAGE statement to change the language setting for the duration of the current session. Use the @@LANGUAGE function to show the current language setting.

If the default language of a login is dropped from the server, the default language of the server is used as the initial language setting, and a message is displayed.

sp_defaultlanguage cannot be executed within a user-defined transaction.

Permissions

Execute permissions default to the public role for users changing the default language for their login. Only members of the sysadmin or securityadmin fixed server roles can execute sp_defaultlanguage for other logins.

Examples

This example sets the default language for login Claire to french.

EXEC sp_defaultlanguage 'Claire', 'french'

See Also
@@LANGUAGE | sp_helplanguage
SET | System Stored Procedures
sp_addlogin |


sp_delete_alert

Removes an alert.

Syntax

sp_delete_alert [@name =] 'name'

Arguments
[@name =] 'name'
Is the name of the alert. name is sysname, with no default.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

Removing an alert also removes any notifications associated with the alert.

sp_delete_alert must be executed in the msdb database.

Permissions

Only members of the sysadmin fixed server role or the db_owner fixed database role can execute sp_delete_alert.

Examples

This example removes an alert named Test Alert.

sp_delete ‘Test Alert’

See Also
sp_add_alert sp_help_alert


sp_delete_backuphistory

Deletes the entries in the backup and restore history tables for backup sets that are older than oldest_date. Because additional rows are added to the backup and restore history tables whenever a backup or restore operation is performed, sp_delete_backuphistory can be used to reduce the size of the history tables in the msdb database.

Syntax

sp_delete_backuphistory [@oldest_date =] 'oldest_date'

Arguments
[@oldest_date =] 'oldest_date'
Is the oldest date retained in the backup and restore history tables. oldest_date is datetime, with no default.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

sp_delete_backuphistory must be run from the msdb database.

Permissions

Execute permissions default to members of the sysadmin fixed server role, but can be granted to other users.

Examples

This example deletes all entries older than August 20, 1998, 5:30 A.M., in the backup and restore history tables.

sp_delete_backuphistory('08/20/98 5:30AM')

See Also
BACKUP | DUMP
backupfile | LOAD
backupmediafamily | RESTORE
backupmediaset | restorefile
backupset | restorehistory


sp_delete_category

Removes the specified category of jobs, alerts, or operators from the current server.

Syntax

sp_delete_category [@class =] 'class',
[@name =] 'name'

Arguments
[@class =] 'class'
Is the class of the category. class is varchar(8), with no default, and must have one of these values.

Value | Description
JOB | Deletes a job category.
ALERT | Deletes an alert category.
OPERATOR | Deletes an operator category.

[@name =] 'name'
Is the name of the category to be removed. name is sysname, with no default.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

sp_delete_category must be executed in the msdb database.

Deleting a category recategorizes any jobs, alerts, or operators in that category to the default category for the class.

Permissions

Only members of the sysadmin fixed server role or the db_owner fixed database role can execute, or grant permissions to execute, sp_delete_category in the current database.

Examples

This example deletes the job category named AdminJobs.

USE msdb

EXEC sp_delete_category 'JOB', 'AdminJobs'

See Also
sp_add_category | sp_update_category
sp_help_category | System Stored Procedures


sp_delete_job

Deletes a job.

Syntax

sp_delete_job [@job_id =] job_id | [@job_name =] 'job_name'
[, [@originating_server =] 'server']

Arguments
[@job_id =] job_id
Is the identification number of the job to be deleted. job_id is uniqueidentifier, with a default of NULL.
[@job_name =] 'job_name'
Is the name of the job to be deleted. job_name is sysname, with a default of NULL.

Note Either job_id or job_name must be specified, but both cannot be specified.

Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

Two parameters, @delete_history and @originating_server, exist in sp_delete_job, but are reserved for internal use.

SQL Server Enterprise Manager provides an easy, graphical way to manage jobs, and is the recommended way to create and manage the job infrastructure.

Permissions

Only members of the sysadmin fixed server role or the db_owner fixed database role can execute sp_delete_job.

Examples

This example deletes the job Nightly Backups.

USE msdb

EXEC sp_delete_job @job_name ='Nightly Backups'

See Also
sp_add_job | sp_update_job
sp_help_job | System Stored Procedures


sp_delete_jobschedule

Removes a schedule from a job.

Syntax

sp_delete_jobschedule [@job_id =] job_id, | [@job_name =] 'job_name',
[@name =] 'sched_job_name'

Arguments
[@job_id =] job_id
Is the identification number of the job from which to delete the schedule. job_id is uniqueidentifier, with a default of NULL.
[@job_name =] 'job_name'
Is the name of the job from which to delete the schedule. job_name is sysname, with a default of NULL.

Note Either job_id or job_name must be specified, but both cannot be specified.

[@name =] 'sched_job_name'
Is the name of the schedule to delete. sched_job_name is sysname, with no default.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

Removing a schedule from a job prevents SQL Server Agent from executing the job according to that schedule. sp_update_jobschedule can be used to disable a scheduled job without removing it from the schedule.

SQL Server Enterprise Manager provides an easy, graphical way to manage jobs, and is the recommended way to create and manage the job infrastructure.

Permissions

Execute permissions default to the public role.

Examples

This example removes the Nightly Backup schedule from the Database Backup job.

USE msdb

EXEC sp_delete_jobschedule @job_name = N'Database Backup',

    @name = N'Nightly Backup'

See Also
sp_add_jobschedule | sp_update_jobschedule
sp_help_jobschedule | System Stored Procedures


sp_delete_jobserver

Removes the specified target server.

Syntax

sp_delete_jobserver [@job_id =] job_id,| [@job_name =] 'job_name',
[@server_name =] 'server'

Arguments
[@job_id =] job_id
Is the identification number of the job from which the specified target server will be removed. job_id is uniqueidentifier, with a default of NULL.
[@job_name =] 'job_name'
Is the name of the job from which the specified target server will be removed. job_name is sysname, with a default of NULL.

Note Either job_id or job_name must be specified, but both cannot be specified.

[@server_name =] 'server'
Is the name of the target server to remove from the specified job. server is nvarchar(30), with no default. server can be (LOCAL) or the name of a remote target server.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Permissions

Execute permissions default to the public role.

Examples

This example removes the server LONDON1 from processing the Backup Customer Information job.

Note This example assumes that the Backup Customer Information job was created earlier.

USE msdb

EXEC sp_delete_jobserver
    @job_name = 'Backup Customer Information',
    @server_name = 'LONDON1'

See Also
sp_add_jobserver | System Stored Procedures
sp_help_jobserver |


sp_delete_jobstep

Removes a job step from a job.

Syntax

sp_delete_jobstep [@job_id =] job_id, | [@job_name =] 'job_name',
[@step_id =] step_id

Arguments
[@job_id =] job_id
Is the identification number of the job from which the step will be removed. job_id is uniqueidentifier, with a default of NULL.
[@job_name =] 'job_name'
Is the name of the job from which the step will be removed. job_name is sysname, with a default of NULL.

Note Either job_id or job_name must be specified, but both cannot be specified.

[@step_id =] step_id
Is the identification number of the step being removed. step_id is int, with no default.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

Removing a job step automatically updates the other job steps that reference the deleted step.

For information about the steps associated with a particular job, run sp_help_jobstep.

SQL Server Enterprise Manager provides an easy, graphical way to manage jobs, and is the recommended way to create and manage the job infrastructure.

Permissions

Execute permissions default to the public role.

Examples

This example removes job step 1 from the job Nightly Backups.

USE msdb

EXEC sp_delete_jobstep @job_name = 'Nightly Backups',
    @step_id = 1

See Also
sp_add_jobstep | sp_update_jobstep
sp_help_jobstep | System Stored Procedures


sp_delete_notification

Removes all notifications sent to a particular operator in response to an alert.

Syntax

sp_delete_notification [@alert_name =] 'alert',
[@operator_name =] 'operator'

Arguments
[@alert_name =] 'alert'
Is the name of the alert. alert is sysname, with no default.
[@operator_name =] 'operator'
Is the name of the operator. operator is sysname, with no default.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

Removing a notification removes only the notification; the alert and the operator are left intact.

Permissions

Only members of the sysadmin fixed server role can execute sp_delete_notification.

Examples

This example removes all notifications sent to operator stevenb when alert 'Error 1101' occurs.

USE msdb

EXEC sp_delete_notification 'Error 11001', 'stevenb'

See Also
sp_add_alert | sp_help_notification
sp_add_notification | sp_help_operator
sp_add_operator | sp_update_notification
sp_delete_alert | System Stored Procedures
sp_help_alert |


sp_delete_operator

Removes an operator.

Syntax

sp_delete_operator [@name =] 'name'
[, [@reassign_to_operator =] 'reassign_operator']

Arguments
[@name =] 'name'
Is the name of the operator to delete. name is sysname, with no default.
[@reassign_to_operator =] 'reassign_operator'
Is the name of an operator to whom the specified operator's alerts can be reassigned. reassign_operator is sysname, with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

When an operator is removed, all the notifications associated with the operator are also removed.

Permissions

Only members of the sysadmin fixed server role can execute sp_delete_operator.

Examples

This example deletes operator janetl.

USE msdb

EXEC sp_delete_operator 'janetl'

See Also
sp_add_operator | sp_update_operator
sp_help_operator | System Stored Procedures


sp_delete_targetserver

Removes the specified server from the list of available target servers.

Syntax

sp_delete_targetserver [@server_name =] 'server'

Arguments
[@server_name =] 'server'
Is name of the server to remove as an available target server. server is nvarchar(30), with no default.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

The @clear_downloadlist and @post_defection parameters also exist in sp_delete_targetserver, but are reserved for internal use only.

The normal way to delete a target server is to call sp_msx_defect at the target server. Use sp_delete_targetserver only when a manual defection is necessary.

Permissions

Only members of the sysadmin fixed server role or the db_owner fixed database role can execute sp_delete_targetserver.

Examples

This example removes the server LONDON1 from the available job servers.

USE msdb

EXEC sp_delete_targetserver 'LONDON1'

See Also
sp_help_targetserver | System Stored Procedures
sp_msx_defect |


sp_delete_targetservergroup

Deletes the specified target server group.

Syntax

sp_delete_targetservergroup [@name =] 'name'

Arguments
[@name =] 'name'
Is the name of the target server group to remove. name is sysname, with no default.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Permissions

Only members of the sysadmin fixed server role or the db_owner fixed database role can execute sp_delete_targetservergroup.

Examples

This example removes the target server group Servers Maintaining Customer Information.

USE msdb

EXEC sp_delete_targetservergroup
    @name = N'Servers Maintaining Customer Information'

See Also
sp_add_targetservergroup | sp_update_targetservergroup
sp_help_targetservergroup | System Stored Procedures


sp_delete_targetsvrgrp_member

Removes a target server from a target server group.

Syntax

sp_delete_targetsvrgrp_member [@group_name =] 'group_name',
[server_name =] 'server_name'

Arguments
[@group_name =] 'group_name'
Is the name of the group. group_name is sysname, with no default.
[@server_name =] 'server_name'
Is the name of the server to remove from the specified group. server_name is nvarchar(30), with no default.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Permissions

Only members of the sysadmin fixed server role or the db_owner fixed database role can execute sp_delete_targetsvrgrp_member.

Examples

This example removes the server LONDON1 from the Servers Maintaining Customer Information group.

USE msdb

EXEC sp_delete_targetsvrgrp_member
    @group_name = N'Servers Maintaining Customer Information',
    @server_name = N'LONDON1'

See Also
sp_add_targetsvrgrp_member System Stored Procedures


sp_deletemergeconflictrow

Deletes rows from a conflict table or the msmerge_delete_conflicts table.

Syntax

sp_deletemergeconflictrow [[@conflict_table =] 'conflict_table']
[,[@source_object =] 'source_object'] {,[@rowguid =] 'rowguid',
[@origin_datasource =] 'origin_datasource']}
[,[@drop_table_if_empty =] 'drop_table_if_empty']

Arguments
[@conflict_table =] 'conflict_table'
Is the name of the conflict table. conflict_table is sysname, with a default of %. If the conflict_table is specified as NULL or %, the conflict is assumed to be a delete conflict and the row matching rowguid and origin_datasource and source_object is deleted from the msmerge_delete_conflicts table.
[@source_object =] 'source_object'
Is the name of the source table. source_object is nvarchar(386), with a default of NULL.
[@rowguid =] 'rowguid'
Is the row identifier for the delete conflict. rowguid is uniqueidentifier, with no default.
[@origin_datasource =] 'origin_datasource'
Is the origin of the conflict. origin_datasource is varchar(255), with no default.
[@drop_table_if_empty =] 'drop_table_if_empty'
Is a flag indicating whether the conflict_table is to be dropped if is empty. drop_table_if_empty is varchar(10), with a default of FALSE.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_deletemergeconflictrow is used in merge replication.

msmerge_delete_conflicts is a system table and is not deleted from the database, even if it is empty.

Permissions

Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_deletemergeconflictrow.

See Also
System Stored Procedures


sp_denylogin

Prevents a Microsoft® Windows NT® user or group from connecting to Microsoft SQL Server™.

Syntax

sp_denylogin [@loginame =] 'login'

Arguments
[@loginame =] 'login'
Is the name of the Windows NT user or group. login is sysname, with no default. If the Windows NT user or group does not exist in SQL Server, it is automatically added.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_denylogin can be used only with Windows NT accounts in the form Domain\User, for example London\Joeb. sp_denylogin cannot be used with SQL Server logins added with sp_addlogin.

Use sp_grantlogin to reverse the effects of sp_denylogin and allow the user to connect.

sp_denylogin cannot be executed within a user-defined transaction.

Permissions

Only members of the securityadmin or sysadmin fixed server roles can execute sp_denylogin.

Examples

This example prevents user Corporate\GeorgeW from logging in to SQL Server.

EXEC sp_denylogin 'Corporate\GeorgeW'

Or

EXEC sp_denylogin [Corporate\GeorgeW]

See Also
sp_grantlogin sp_revokelogin


sp_depends

Displays information about database object dependencies (for example, the views and procedures that depend on a table or view, and the tables and views that are depended on by the view or procedure). References to objects outside the current database are not reported.

Syntax

sp_depends [@objname =] 'object'

Arguments
[@objname =] 'object'
The database object to examine for dependencies. The object can be a table, view, stored procedure, or trigger. object is nvarchar(776), with no default.
Return Code Values

0 (success) or 1 (failure)

Result Sets

sp_depends displays two result sets.

This result set shows the objects on which object depends.

Column name | Data type | Description
name | nvarchar(40) | Name of the item for which a dependency exists
type | nvarchar(16) | Type of the item
updated | nvarchar(7) | Whether the item is updated
selected | nvarchar(8) | Whether the item is used in a SELECT statement
column | sysname | Column or parameter on which the dependency exists

This result set shows the objects that depend on object.

Column name | Data type | Description
name | nvarchar(40) | Name of the item for which a dependency exists
type | nvarchar(16) | Type of the item

Remarks

An object that references another object is considered dependent on that object. sp_depends determines the dependencies by looking at the sysdepends table.

Permissions

Execute permissions default to the public role.

Examples

This example lists the database objects that depend on the Customers table.

USE Northwind

EXEC sp_depends 'Customers'

See Also
CREATE PROCEDURE | EXECUTE
CREATE TABLE | sp_help
CREATE VIEW | System Stored Procedures


sp_describe_cursor

Reports the attributes of a server cursor.

Syntax

sp_describe_cursor [@cursor_return =] output_cursor_variable OUTPUT
{
[, [@cursor_source =] N'local', [@cursor_identity =] N'local_cursor_name'] |
[, [@cursor_source =] N'global',
[@cursor_identity =] N'global_cursor_name'] |
[, [@cursor_source =] N'variable', [@cursor_identity =]
N'input_cursor_variable']
}

Arguments
[@cursor_return =] output_cursor_variable OUTPUT
Is the name of a declared cursor variable to receive the cursor output. output_cursor_variable is cursor, with no default, and must not be associated with any cursors at the time sp_describe_cursor is called. The cursor returned is a scrollable, dynamic, read-only cursor.
[@cursor_source =] { N'local' | N'global' | N'variable' }
Specifies whether the cursor being reported on is specified using the name of a local cursor, a global cursor, or a cursor variable. The parameter is nvarchar(30).
[@cursor_identity =] N'local_cursor_name']
Is the name of a cursor created by a DECLARE CURSOR statement either having the LOCAL keyword, or that defaulted to LOCAL. local_cursor_name is nvarchar(128).
[@cursor_identity =] N'global_cursor_name']
Is the name of a cursor created by a DECLARE CURSOR statement either having the GLOBAL keyword, or that defaulted to GLOBAL. It can also be the name of an API server cursor opened by an ODBC application that then named the cursor by calling SQLSetCursorName. global_cursor_name is nvarchar(128).
[@cursor_identity =] N'input_cursor_variable']
Is the name of a cursor variable associated with an open cursor. input_cursor_variable is nvarchar(128).
Return Code Values

None

Cursors Returned

sp_describe_cursor encapsulates its result set in a Transact-SQL cursor output parameter. This allows Transact-SQL batches, stored procedures, and triggers to work with the output one row at a time. It also means that the procedure cannot be called directly from database API functions. The cursor output parameter must be bound to a program variable, but the database APIs do not support binding cursor parameters or variables.

This is the format of the cursor returned by sp_describe_cursor. The format of the cursor is the same as the format returned by sp_cursor_list.

Column name | Data type | Description
reference_name | sysname | Name used to refer to the cursor. If the reference to the cursor was through the name given on a DECLARE CURSOR statement, the reference name is the same as cursor name. If the reference to the cursor was through a variable, the reference name is the name of the variable.
cursor_name | sysname | Name of the cursor from a DECLARE CURSOR statement. If the cursor was created by setting a cursor variable to a cursor, the cursor name is a system-generated name.
cursor_scope | tinyint | 1 = LOCAL 2 = GLOBAL
status | int | Same values as reported by the CURSOR_STATUS system function: 1 = The cursor referenced by the cursor name or variable is open. If the cursor is insensitive, static, or keyset, it has at least one row. If the cursor is dynamic, the result set has zero or more rows. 0 = The cursor referenced by the cursor name or variable is open but has no rows. Dynamic cursors never return this value. -1 = The cursor referenced by the cursor name or variable is closed. -2 = Applies only to cursor variables. There is no cursor assigned to the variable. Possibly, an OUTPUT parameter assigned a cursor to the variable, but the stored procedure closed the cursor before returning. -3 = A cursor or cursor variable with the specified name does not exist, or the cursor variable has not had a cursor allocated to it.
model | tinyint | 1 = Insensitive (or static) 2 = Keyset 3 = Dynamic 4 = Fast Forward
concurrency | tinyint | 1 = Read-only 2 = Scroll locks 3 = Optimistic
scrollable | tinyint | 0 = Forward-only 1 = Scrollable
open_status | tinyint | 0 = Closed 1 = Open
cursor_rows | decimal(10,0) | Number of qualifying rows in the result set. For more information, see @@CURSOR_ROWS.
fetch_status | smallint | Status of the last fetch on this cursor. For more information, see @@FETCH_STATUS. 0 = Fetch successful. -1 = Fetch failed or is beyond the bounds of the cursor. -2 = The requested row is missing. -9 = There has been no fetch on the cursor.
column_count | smallint | Number of columns in the cursor result set.
row_count | decimal(10,0) | Number of rows affected by the last operation on the cursor. For more information, see @@ROWCOUNT.
last_operation | tinyint | Last operation performed on the cursor: 0 = No operations have been performed on the cursor. 1 = OPEN 2 = FETCH 3 = INSERT 4 = UPDATE 5 = DELETE 6 = CLOSE 7 = DEALLOCATE
cursor_handle | int | A unique value for the cursor within the scope of the server.

Remarks

sp_describe_cursor describes the attributes that are global to a server cursor, such as the scrollability and updatability of the cursor. Use sp_describe_cursor_columns for a description of the attributes of the result set returned by the cursor. Use sp_describe_cursor_tables for a report of the base tables referenced by the cursor. Use sp_cursor_list to get a report of the Transact-SQL server cursors visible on the connection.

A DECLARE CURSOR statement may request a cursor type that Microsoft® SQL Server™ cannot support with the SELECT statement contained in the DECLARE CURSOR. SQL Server implicitly converts the cursor to a type it can support with the SELECT statement. If TYPE_WARNING is specified in the DECLARE CURSOR statement SQL Server sends the application an informational message that a conversion has been done. sp_describe_cursor can then be called to determine the type of cursor that has been implemented.

Permissions

Execute permission defaults to the public role.

Examples

This example opens a global cursor and uses sp_describe_cursor to report on the attributes of the cursor.

USE Northwind

GO

-- Declare and open a global cursor.

DECLARE abc CURSOR STATIC FOR

SELECT LastName

FROM Employees

OPEN abc

-- Declare a cursor variable to hold the cursor output variable

-- from sp_describe_cursor.

DECLARE @Report CURSOR

-- Execute sp_describe_cursor into the cursor variable.

EXEC master.dbo.sp_describe_cursor @cursor_return = @Report OUTPUT,

        @cursor_source = N'global', @cursor_identity = N'abc'

-- Fetch all the rows from the sp_describe_cursor output cursor.

FETCH NEXT from @Report

WHILE (@@FETCH_STATUS <> -1)

BEGIN

    FETCH NEXT from @Report

END

-- Close and deallocate the cursor from sp_describe_cursor.

CLOSE @Report

DEALLOCATE @Report

GO

-- Close and deallocate the original cursor.

CLOSE abc

DEALLOCATE abc

GO

See Also
CURSOR_STATUS | sp_describe_cursor_columns
DECLARE CURSOR | sp_describe_cursor_tables
sp_cursor_list |


sp_describe_cursor_columns

Reports the attributes of the columns in the result set of a server cursor.

Syntax

sp_describe_cursor_columns
[@cursor_return =] output_cursor_variable OUTPUT
{
[, [@cursor_source =] N'local', [@cursor_identity =] N'local_cursor_name'] |
[, [@cursor_source =] N'global', [@cursor_identity =]
N'global_cursor_name'] |
[, [@cursor_source =] N'variable', [@cursor_identity =]
N'input_cursor_variable']
}

Arguments
[@cursor_return =] output_cursor_variable OUTPUT
Is the name of a declared cursor variable to receive the cursor output. output_cursor_variable is cursor, with no default, and must not be associated with any cursors at the time sp_describe_cursor_columns is called. The cursor returned is a scrollable, dynamic, read-only cursor.
[@cursor_source =] { N'local' | N'global' | N'variable' }
Specifies whether the cursor being reported on is specified using the name of a local cursor, a global cursor, or a cursor variable. The parameter is nvarchar(30).
[@cursor_identity =] N'local_cursor_name']
Is the name of a cursor created by a DECLARE CURSOR statement either having the LOCAL keyword, or that defaulted to LOCAL. local_cursor_name is nvarchar(128).
[@cursor_identity =] N'global_cursor_name']
Is the name of a cursor created by a DECLARE CURSOR statement either having the GLOBAL keyword, or that defaulted to GLOBAL. It can also be the name of an API server cursor opened by an ODBC application that then named the cursor by calling SQLSetCursorName. global_cursor_name is nvarchar(128).
[@cursor_identity =] N'input_cursor_variable']
Is the name of a cursor variable associated with an open cursor. input_cursor_variable is nvarchar(128).
Return Code Values

None

Cursors Returned

sp_describe_cursor_columns encapsulates its report as a Transact-SQL cursor output parameter. This allows Transact-SQL batches, stored procedures, and triggers to work with the output one row at a time. It also means that the procedure cannot be called directly from database API functions. The cursor output parameter must be bound to a program variable, but the database APIs do not support binding cursor parameters or variables.

This is the format of the cursor returned by sp_describe_cursor_columns.

Column name | Data type | Description
column_name | sysname nullable | Name assigned to the result set column. The column is NULL if the column was specified without an accompanying AS clause.
ordinal_position | int | Relative position of the column from the leftmost column in the result set. The first column is in position 1. The value for any hidden columns is 0.
column_ characteristics_ flags | int | A bitmask indicating the information stored in DBCOLUMNFLAGS in OLE DB. Can be one of the following: 1 = Bookmark 2 = Fixed length 4 = Nullable 8 = Row versioning 16 = Updatable column (set for projected columns of a cursor that has no FOR UPDATE clause and, if there is such a column, can be only one per cursor).
column_size | int | Maximum possible size for a value in this column.
data_type_sql | smallint | Number indicating the SQL Server data type of the column.
column_precision | tinyint | Maximum precision of the column as per the bPrecision value in OLE DB.
column_scale | tinyint | Number of digits to the right of the decimal point for the numeric or decimal data types as per the bScale value in OLE DB.
order_position | int | If the column participates in the ordering of the result set, the position of the column in the order key relative to the leftmost column.
order_direction | varchar(1), nullable | A = The column is in the order key and the ordering is ascending. D = The column is in the order key and the ordering is descending. NULL = The column does not participate in ordering.
hidden_column | smallint | If a value of 0, this column appears in the select list. The value 1 is reserved for future use.
columnid | int | Column ID of the base column. If the result set column was built from an expression, columnid is -1.
objectid | int | Object ID of the base table supplying the column. If the result set column was built from an expression, objectid is -1.
dbid | int | ID of the database containing the base table supplying the column. If the result set column was built from an expression, dbid is -1.
dbname | sysname nullable | Name of the database containing the base table supplying the column. If the result set column was built from an expression, dbname is NULL.

Remarks

sp_describe_cursor_columns describes the attributes of the columns in the result set of a server cursor, such as the name and data type of each cursor. Use sp_describe_cursor for a description of the global attributes of the server cursor. Use sp_describe_cursor_tables for a report of the base tables referenced by the cursor. Use sp_cursor_list to get a report of the Transact-SQL server cursors visible on the connection.

Permissions

Execute permissions default to the public role.

Examples

This example opens a global cursor and uses sp_describe_cursor_columns to report on the columns used in the cursor.

USE Northwind

GO

-- Declare and open a global cursor.

DECLARE abc CURSOR KEYSET FOR

SELECT LastName

FROM Employees

GO

OPEN abc

-- Declare a cursor variable to hold the cursor output variable

-- from sp_describe_cursor_columns.

DECLARE @Report CURSOR

-- Execute sp_describe_cursor_columns into the cursor variable.

EXEC master.dbo.sp_describe_cursor_columns

        @cursor_return = @Report OUTPUT,

        @cursor_source = N'global', @cursor_identity = N'abc'

-- Fetch all the rows from the sp_describe_cursor_columns output cursor.

FETCH NEXT from @Report

WHILE (@@FETCH_STATUS <> -1)

BEGIN

    FETCH NEXT from @Report

END

-- Close and deallocate the cursor from sp_describe_cursor_columns.

CLOSE @Report

DEALLOCATE @Report

GO

-- Close and deallocate the original cursor.

CLOSE abc

DEALLOCATE abc

GO

See Also
CURSOR_STATUS | sp_describe_cursor
DECLARE CURSOR | sp_describe_cursor_tables
sp_cursor_list |


sp_describe_cursor_tables

Reports the base tables referenced by a server cursor.

Syntax

sp_describe_cursor_tables
[@cursor_return =] output_cursor_variable OUTPUT
{
[, [@cursor_source =] N'local', [@cursor_identity =] N'local_cursor_name'] |
[, [@cursor_source =] N'global', [@cursor_identity =]
N'global_cursor_name'] |
[, [@cursor_source =] N'variable', [@cursor_identity =]
N'input_cursor_variable']
}

Arguments
[@cursor_return =] output_cursor_variable OUTPUT
Is the name of a declared cursor variable to receive the cursor output. output_cursor_variable is cursor, with no default, and must not be associated with any cursors at the time sp_describe_cursor_tables is called. The cursor returned is a scrollable, dynamic, read-only cursor.
[@cursor_source =] { N'local' | N'global' | N'variable' }
Specifies whether the cursor being reported on is specified using the name of a local cursor, a global cursor, or a cursor variable. The parameter is nvarchar(30).
[@cursor_identity =] N'local_cursor_name']
Is the name of a cursor created by a DECLARE CURSOR statement either having the LOCAL keyword, or that defaulted to LOCAL. local_cursor_name is nvarchar(128).
[@cursor_identity =] N'global_cursor_name']
Is the name of a cursor created by a DECLARE CURSOR statement either having the GLOBAL keyword, or that defaulted to GLOBAL. It can also be the name of an API server cursor opened by an ODBC application that then named the cursor by calling SQLSetCursorName.global_cursor_name is nvarchar(128).
[@cursor_identity =] N'input_cursor_variable']
Is the name of a cursor variable associated with an open cursor. input_cursor_variable is nvarchar(128).
Return Code Values

None

Cursors Returned

sp_describe_cursor_tables encapsulates its report as a Transact-SQL cursor output parameter. This allows Transact-SQL batches, stored procedures, and triggers to work with the output one row at a time. It also means that the procedure cannot be called directly from database API functions. The cursor output parameter must be bound to a program variable, but the database APIs do not support bind cursor parameters or variables.

This is the format of the cursor returned by sp_describe_cursor_tables.

Column name | Data type | Description
table owner | sysname | User ID of the table owner.
Table_name | sysname | Name of the base table.
Optimizer_hints | smallint | Bitmap consisting of one or more of: 1 = Row-level locking (ROWLOCK) 4 = Page-level locking (PAGELOCK) 8 = Table Lock (TABLOCK) 16 = Exclusive table lock (TABLOCKX) 32 = Update lock (UPDLOCK) 64 = No lock (NOLOCK) 128 = Fast first-row option (FASTFIRST) 4096 = Read repeatable semantic when used with declare cursor (HOLDLOCK) When multiple options are supplied, the system uses the most restrictive. However, sp_describe_cursor_tables shows the flags as specified in the query.
lock_type | smallint | Scroll-lock type requested either explicitly or implicitly for each base table that underlies this cursor. The value can be: 0 = None 1 = Shared 3 = Update
server_name | sysname, nullable | Name of the linked server the table resides on. NULL if OPENQUERY or OPENROWSET are used.
Objectid | int | Object ID of the table. 0 if OPENQUERY or OPENROWSET are used.
dbid | int | ID of the database the table resides in. 0 if OPENQUERY or OPENROWSET are used.
dbname | sysname, nullable | Name of the database the table resides in. NULL if OPENQUERY or OPENROWSET are used.

Remarks

sp_describe_cursor_tables describes the base tables referenced by a server cursor. Use sp_describe_cursor_columns for a description of the attributes of the result set returned by the cursor. Use sp_describe_cursor for a description of the global characteristics of the cursor, such as its scrollability and updatability. Use sp_cursor_list to get a report of the Transact-SQL server cursors visible on the connection.

Permissions

Execute permissions default to the public role.

Examples

This example opens a global cursor and uses sp_describe_cursor_tables to report on the tables referenced by the cursor.

USE Northwind

GO

-- Declare and open a global cursor.

DECLARE abc CURSOR KEYSET FOR

SELECT LastName

FROM Employees

WHERE LastName LIKE 'S%'

OPEN abc

GO

-- Declare a cursor variable to hold the cursor output variable

-- from sp_describe_cursor_tables.

DECLARE @Report CURSOR

-- Execute sp_describe_cursor_tables into the cursor variable.

EXEC master.dbo.sp_describe_cursor_tables
        @cursor_return = @Report OUTPUT,

        @cursor_source = N'global', @cursor_identity = N'abc'

-- Fetch all the rows from the sp_describe_cursor_tables output cursor.

FETCH NEXT from @Report

WHILE (@@FETCH_STATUS <> -1)

BEGIN

    FETCH NEXT from @Report

END

-- Close and deallocate the cursor from sp_describe_cursor_tables.

CLOSE @Report

DEALLOCATE @Report

GO

-- Close and deallocate the original cursor.

CLOSE abc

DEALLOCATE abc

GO

See Also
CURSOR_STATUS | sp_describe_cursor
DECLARE CURSOR | sp_describe_cursor_columns
sp_cursor_list |


sp_detach_db

Detaches a database from a server and, optionally, runs UPDATE STATISTICS on all tables before detaching.

Syntax

sp_detach_db [@dbname =] 'dbname'
[, [@skipchecks =] 'skipchecks']

Arguments
[@dbname =] 'dbname'
Is the name of the database to be detached. dbname is sysname, with a default value of NULL.
[@skipchecks =] 'skipchecks'
skipchecks is nvarchar(10), with a default value of NULL. If true, UPDATE STATISTICS is skipped. If false, UPDATE STATISTICS is run. This option is useful for databases that are to be moved to read-only media.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

The detached files remain and can be reattached using sp_attach_db or sp_attach_single_file_db. The files can also be moved to another server and attached.

Permissions

Only members of the sysadmin fixed server role can execute sp_detach_db.

Examples

This example detaches the pubs database with skipchecks set to true.

EXEC sp_detach_db 'pubs', 'true'

See Also
sp_attach_db sp_attach_single_file_db


sp_drop_agent_parameter

Drops one or all parameters from a profile in the MSagent_parameters table.

Syntax

sp_drop_agent_parameter [@profile_id =] profile_id
[,[@parameter_name =] 'parameter_name']

Arguments
[@profile_id =] profile_id
Is the ID of the profile for which a parameter is to be dropped. profile_id is int, with no default.
[@parameter_name =] 'parameter_name'
Is the name of the parameter to be dropped. parameter_name is sysname, with a default of %. If %, all parameters for the specified profile are dropped.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_drop_agent_parameter is used in all types of replication.

Permissions

Only members of the sysadmin fixed server role can execute sp_drop_agent_parameter.

See Also
sp_add_agent_parameter | System Stored Procedures
sp_help_agent_parameter |


sp_drop_agent_profile

Drops a profile from the MSagent_profiles table.

Syntax

sp_drop_agent_profile [@profile_id =] profile_id

Arguments
[@profile_id =] profile_id
Is the ID of the profile to be dropped. profile_id is int, with no default.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_drop_agent_profile is used in all types of replication.

The parameters of the given profile are also dropped from the MSagent_parameters table.

Permissions

Only members of the sysadmin fixed server role can execute sp_drop_agent_profile.

See Also
sp_add_agent_profile | sp_help_agent_profile
sp_change_agent_profile | System Stored Procedures


sp_dropalias

Removes an alias to a user in the current database from a login. sp_dropalias is provided for backward compatibility only. Use roles and the sp_droprolemember stored procedure instead of aliases.

Syntax

sp_dropalias [@loginame =] 'login'

Arguments
[@loginame =] 'login'
Is the name of the Microsoft® SQL Server™ login or Microsoft Windows NT® user or group from which the alias is to be removed. login is sysname, with no default. login must already exist.
Return Code Values

0 (success) or 1 (failure)

Remarks

Aliases allow logins to assume the identity of a user in a database, thereby gaining the permissions of that user while working in that database.

When the alias is removed, the login can no longer perform the activities associated with the user to whom they were aliased in the current database.

sp_dropalias cannot be executed within a user-defined transaction.

Permissions

Only members of the db_accessadmin or db_owner fixed database roles can execute sp_dropalias.

Examples

This example removes the alias to user Victoria in the current database.

EXEC sp_dropalias 'Victoria'

See Also
sp_addalias | sp_droprolemember
sp_addrolemember | System Stored Procedures


sp_dropapprole

Removes an application role from the current database.

Syntax

sp_dropapprole [@rolename =] 'role'

Arguments
[@rolename =] 'role'
Is the application role to remove. role is sysname, with no default. role must exist in the current database.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_dropapprole can only be used to remove application roles. Use sp_droprole to remove a standard Microsoft® SQL Server™ role. An application role cannot be removed if it owns any objects. Either remove the objects before removing the application role, or use sp_changeobjectowner to change the owner of any objects that must not be removed.

sp_dropapprole cannot be executed within a user-defined transaction.

Permissions

Only members of both the db_securityadmin and db_owner fixed database roles can execute sp_dropapprole.

Examples

This example removes the SalesApp application role from the current database.

EXEC sp_dropapprole 'SalesApp'

See Also
sp_addapprole | sp_changeobjectowner
sp_setapprole | System Stored Procedures


sp_droparticle

Drops an article from a publication. An article cannot be removed if one or more subscriptions to it exist.

Syntax

sp_droparticle [@publication =] 'publication', [@article =]'article'
[,[@ignore_distributor =] ignore_distributor]

Arguments
[@publication =] 'publication'
Is the name of the publication that contains the article to be dropped. publication is sysname, with no default.
[@article =]'article'
Is the name of the article to be dropped. article is sysname, with no default.
[@ignore_distributor =] ignore_distributor
For internal use only.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_droparticle is used in all types of replication.

sp_droparticle checks the article’s type column in the sysarticles table to determine whether a view or filter should also be dropped. If a view or filter was autogenerated, it is dropped with the article. If it was manually created, it is not dropped.

Permissions

Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_droparticle.

See Also
sp_addarticle | sp_enumfullsubscribers
sp_addpublication | sp_helparticle
sp_articlecolumn | sp_helparticlecolumns
sp_changearticle | sp_helppublication
sp_changepublication | System Stored Procedures
sp_droppublication |


sp_dropdevice

Drops a database device or backup device from Microsoft® SQL Server™, deleting the entry from master.dbo.sysdevices.

Syntax

sp_dropdevice [@logicalname =] 'device'
[, [@delfile =] 'delfile']

Arguments
[@logicalname =] 'device'
Is the logical name of the database device or backup device as listed in master.dbo.sysdevices.name. device is sysname, with no default.
[@delfile =] 'delfile'
Is whether or not the physical backup device file should be deleted. delfile is varchar(7). If specified as DELFILE, the physical backup device disk file is deleted.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

sp_dropdevice cannot be used inside a transaction.

Permissions

Execute permissions default to the sysadmin fixed server role, and are not transferable.

Examples

This example drops the TAPEDUMP1 tape dump device from SQL Server.

sp_dropdevice 'TAPEDUMP1'

See Also
DROP DATABASE | sp_helpdevice
sp_addumpdevice | System Stored Procedures
sp_helpdb |


sp_dropdistpublisher

Drops a distribution Publisher.

Syntax

sp_dropdistpublisher [@publisher =] 'publisher' [,[@no_checks =] no_checks]

Arguments
[@publisher =] 'publisher'
Is the Publisher to drop. publisher is sysname, with no default.
[@no_checks =] no_checks
Is whether sp_dropdistpublisher checks to be sure the Publisher has uninstalled the server as the Distributor. no_checks is bit, with a default of 0. If 0 and the distribution publisher is remote, the stored procedure checks to make sure the remote publisher has uninstalled the local server as the distributor. If 0 and the distribution Publisher is local, the stored procedure checks to make sure that there are no publishing or distribution objects for the local server left. If 1, all the replication objects associated with the distribution publisher are dropped. After doing this, the remote Publisher must uninstall replication using sp_dropdistributor with @ignore_distributor = 1.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_dropdistpublisher is used in all types of replication.

Permissions

Only members of the sysadmin fixed server role can execute sp_dropdistpublisher.

See Also
sp_adddistpublisher | sp_helpdistpublisher
sp_changedistpublisher | System Stored Procedures


sp_dropdistributiondb

Drops a distribution database. Drops the physical files used by the database if they are not used by another database.

Syntax

sp_dropdistributiondb [@database =] 'database'

Arguments
[@database =] 'database'
Is the database to drop. database is sysname, with no default.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_dropdistributiondb is used in all types of replication.

Permissions

Only members of the sysadmin fixed server role can execute sp_dropdistributiondb.

See Also
sp_adddistributiondb | sp_helpdistributiondb
sp_changedistributiondb | System Stored Procedures


sp_dropdistributor

Uninstalls the Distributor.

Syntax

sp_dropdistributor [[@no_checks =] no_checks]
[,[@ignore_distributor =] ignore_distributor

Arguments
[@no_checks =] no_checks
Indicates whether to check for dependent objects before dropping the Distributor. no_checks is bit, with a default of 0. If 0, sp_dropdistributor checks to make sure that all publishing and distribution objects in addition to the Distributor have been dropped. If 1, sp_dropdistributor drops all the publishing and distribution objects without checking.
[@ignore_distributor =] ignore_distributor
Indicates whether this stored procedure is executed without connecting to the Distributor. ignore_distributor is bit, with a default of 0. If 0, sp_dropdistributor connects to the Distributor and cleans up all replication objects. If sp_dropdistributor is unable to connect to the Distributor, the stored procedure fails. If 1, no connection is made to the Distributor and the replication objects are not cleaned up. This is used if the Distributor is being uninstalled or is permanently offline. The objects for this Publisher at the Distributor will not be cleaned up until the Distributor is reinstalled at some future time.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_dropdistributor is used in all types of replication.

If other Publisher or distribution objects exist on the server, sp_dropdistributor fails unless @no_checks is set to 1.

Permissions

Only members of the sysadmin fixed server role can execute sp_dropdistributor.

See Also
sp_adddistributor | sp_helpdistributor
sp_changedistributor_property | System Stored Procedures


sp_dropextendedproc

Drops an extended stored procedure.

Syntax

sp_dropextendedproc [@functname =] 'procedure'

Arguments
[@functname =] 'procedure'
Is the name of the extended stored procedure to drop. procedure is nvarchar(517), with no default.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

Executing sp_dropextendedproc drops the extended stored procedure name from the sysobjects table and removes the entry from the syscomments table.

sp_dropextendedproc cannot be executed inside a transaction.

Permissions

Only members of the sysadmin fixed server role can execute sp_dropextendedproc.

Examples

This example drops the xp_diskfree extended stored procedure.

Note This extended stored procedure must already exist for this example to work without returning an error message.

USE master

EXEC sp_dropextendedproc 'xp_diskfree'

See Also
sp_addextendedproc | System Stored Procedures
sp_helpextendedproc |


sp_dropgroup

Removes a role from the current database. sp_dropgroup is provided for backward compatibility. In Microsoft® SQL Server™ version 7.0, groups are implemented as roles.

Syntax

sp_dropgroup [@rolename =] 'role'

Arguments
[@rolename =] 'role'
Is the role to remove from the current database. role is sysname, with no default.
Return Code Values

0 (success) or 1 (failure)

Result Sets
Column name | Data type | Description
Name | sysname | The name of the existing member of the role.

Remarks

sp_dropgroup calls sp_droprole with the role value to remove the role. The public, fixed server, fixed database, or application roles cannot be removed. Use sp_dropapprole to remove an application role.

A role cannot be removed if it owns any objects. Either remove the objects before removing the role, or use sp_changeobjectowner to change the owner of any objects that must not be removed.

Additionally, the role cannot be removed if there are any members of the role. Use sp_droprolemember to remove the user from the role. If any users are still members of the role, sp_dropgroup displays those members.

sp_dropgroup cannot be executed within a user-defined transaction.

Permissions

Only members of both the db_securityadmin or db_owner fixed database roles, or the owner of the role, can execute sp_dropgroup.

Examples

This example removes the role my_role from the current database.

EXEC sp_dropgroup 'my_role'

See Also
sp_addrole | sp_droprole
sp_dropapprole | System Stored Procedures


sp_droplinkedsrvlogin

Removes an existing mapping between a login on the local server running Microsoft® SQL Server™ and a login on the linked server.

Syntax

sp_droplinkedsrvlogin [@rmtsrvname =] 'rmtsrvname',
[@locallogin =] 'locallogin'

Arguments
[@rmtsrvname =] 'rmtsrvname'
Is the name of a linked server that the SQL Server login mapping applies to. rmtsrvname is sysname, with no default. rmtsrvname must already exist.
[@locallogin =] 'locallogin'
Is the SQL Server login on the local server that has a mapping to the linked server rmtsrvname. locallogin is sysname, with no default. A mapping for locallogin to rmtsrvname must already exist. If NULL, the default mapping created by sp_addlinkedserver, which maps all logins on the local server to logins on the linked server, is deleted.
Return Code Values

0 (success) or 1 (failure)

Remarks

When the existing mapping for a login is deleted, the local server uses the default mapping created by sp_addlinkedserver when connecting to the linked server on behalf of that login. To change the default mapping, use sp_addlinkedsrvlogin.

If the default mapping is also deleted, only logins that have been explicitly given a login mapping to the linked server, using sp_addlinkedsrvlogin, can access the linked server.

sp_droplinkedsrvlogin cannot be executed from within a user-defined transaction.

Permissions

Only members of the sysadmin or securityadmin fixed server roles can execute sp_droplinkedsrvlogin.

Examples
A. Remove the login mapping for an existing user

This example removes the mapping for the login Mary from the local server to the linked server Accounts; as a result, login Mary uses the default login mapping.

EXEC sp_droplinkedsrvlogin 'Accounts', 'Mary'

B. Remove the default login mapping

This example removes the default login mapping originally created by executing sp_addlinkedserver on the local server Accounts.

EXEC sp_droplinkedsrvlogin 'Accounts', NULL

See Also
sp_addlinkedserver | System Stored Procedures
sp_addlinkedsrvlogin |


sp_droplogin

Removes a Microsoft® SQL Server™ login, preventing access to SQL Server using that login name.

Syntax

sp_droplogin [@loginame =] 'login'

Arguments
[@loginame =] 'login'
Is the login to be removed. login is sysname, with no default. login must already exist in SQL Server.
Return Code Values

0 (success) or 1 (failure)

Remarks

A login mapped to an existing user in any database cannot be removed. The user must be removed first by using sp_dropuser. Additionally, these logins cannot be removed:

  • The system administrator (sa) login
  • A login that owns an existing database
  • A login that owns jobs in the msdb database
  • A login that is currently in use and connected to SQL Server

Use sp_changedbowner to change the owner of a database.

Removing a login also deletes any remote and linked server logins mapped to the login.

sp_droplogin cannot be executed within a user-defined transaction.

Permissions

Only members of the sysadmin or securityadmin fixed server roles can execute sp_droplogin.

Note sp_droplogin must check all databases on the server to determine if any user accounts in those databases are associated with the login being deleted. Therefore, for each database on the server, one of these must apply:

  • The user executing sp_droplogin must have permissions to access the database.
  • The guest user account must exist in the database.

If a database cannot be accessed, the login can still be deleted. However, error message 15622 is generated and any users who were associated with the deleted login become orphaned in the databases that could not be accessed. To determine the orphaned users, execute sp_change_users_login REPORT in each database that could not be accessed by sp_droplogin.

Examples

This example removes the login Victoria from SQL Server.

EXEC sp_droplogin 'Victoria'

See Also
sp_addlogin | sp_dropuser
sp_changedbowner | sp_helpuser
sp_change_users_login | System Stored Procedures


sp_dropmergearticle

Removes an article from a merge publication.

Syntax

sp_dropmergearticle [@publication =] 'publication', [@article =] 'article'
[,[@ignore_distributor =] ignore_distributor

Arguments
[@publication =] 'publication'
Is the name of the publication from which to drop an article. publication is sysname, with no default.
[@article =] 'article'
Is the name of the article to drop from the given publication. article is sysname, with no default. If all, all existing articles in the specified merge publication are removed. Even if article is all, the publication still must be dropped separately from the article.
[@ignore_distributor =] ignore_distributor
Indicates whether this stored procedure is executed without connecting to the Distributor. ignore_distributor is bit, with a default of 0.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_dropmergearticle is used in merge replication.

Permissions

Only members of the sysadmin fixed server role or the db_owner fixed database role can execute sp_dropmergearticle.

See Also
sp_addmergearticle | sp_helpmergearticle
sp_changemergearticle | System Stored Procedures


sp_dropmergefilter

Drops a merge filter. sp_dropmergefilter drops all the merge filter columns defined on the merge filter that is to be dropped.

Syntax

sp_dropmergefilter [@publication =] 'publication', [@article =]'article',
[@filtername =] 'filtername'

Arguments
[@publication =] 'publication'
Is the name of the publication. publication is sysname, with no default.
[@article =]'article'
Is the name of the article. article is sysname, with no default.
[@filtername =] 'filtername'
Is the name of the filter to be dropped. filtername is sysname, with no default.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_dropmergefilter is used in merge replication.

Permissions

Only members of the sysadmin fixed server role or the db_owner fixed database role can execute sp_dropmergefilter.

See Also
sp_ addmergefilter | sp_helpmergefilter
sp_changemergefilter | System Stored Procedures


sp_dropmergepublication

Drops a merge publication and its associated Snapshot Agent. All subscriptions must be dropped before dropping merge publications. The articles in the publication are dropped automatically.

Syntax

sp_dropmergepublication [@publication =] 'publication'
[,[@ignore_distributor =] ignore_distributor]

Arguments
[@publication =] 'publication'
Is the name of the publication to drop. publication is sysname, with no default. If all, all existing merge publications are removed as well as the snapshot associated with them. If other values are specified, the Snapshot Agent associated with that publication is dropped.
[@ignore_distributor =] ignore_distributor
ignore_distributor is bit, with a default of 0. This parameter can be used to drop a publication without doing cleanup tasks at the Distributor. It is also useful if you had to reinstall the Distributor.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_dropmergepublication is used in merge replication.

Permissions

Only members of the sysadmin fixed server role or the db_owner fixed database role can execute sp_dropmergepublication.

See Also
sp_addmergepublication | sp_helpmergepublication
sp_changemergepublication | System Stored Procedures


sp_dropmergepullsubscription

Drops a merge pull subscription.

Syntax

sp_dropmergepullsubscription [[@publication =] 'publication']
[,[@publisher =] 'publisher'] [,[@publisher_db =] 'publisher_db']

Arguments
[@publication =] 'publication'
Is the name of the publication. publication is sysname, with a default of NULL.
[@publisher =] 'publisher'
Is the name of the Publisher. publisher is sysname, with a default of NULL.
[@publisher_db =] 'publisher_db'
Is the name of the Publisher database. publisher_db is sysname, with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_dropmergepullsubscription is used in merge replication.

sp_dropmergepullsubscription drops the agent for this merge pull subscription, although the agent is not created in sp_addmergepullsubscription. Also note that the local server and current database are assumed to be the subscriber and subscriber_db.

Permissions

Only members of the sysadmin fixed server role or the db_owner fixed database role can execute sp_dropmergepullsubscription.

See Also
sp_addmergepullsubscription | sp_helpmergepullsubscription
sp_changemergepullsubscription | System Stored Procedures


sp_dropmergesubscription

Drops a subscription to a merge publication and its associated Merge Agent.

Syntax

sp_dropmergesubscription [[@publication =] 'publication']
[,[@subscriber =] 'subscriber' [,[@subscriber_db =] 'subscriber_db']
[,[@subscription_type =] 'subscription_type']
[,[@ignore_distributor =] ignore_distributor]

Arguments
[@publication =] 'publication'
Is the publication name. publication is sysname, with a default of NULL. The publication must already exist and conform to the rules for identifiers.
[@subscriber =] 'subscriber'
Is the name of the Subscriber. subscriber is sysname, with a default of NULL.
[@subscriber_db =] 'subscriber_db'
Is the name of the subscription database. subscription_database is sysname, with a default of NULL.
[@subscription_type =] 'subscription_type'
Is the type of subscription. subscription_type is nvarchar(15), and can be one of these values.

Value | Description
push (default) | Push subscription
pull | Pull subscription
both | Both a push and pull subscription

[@ignore_distributor =] ignore_distributor
Indicates whether this stored procedure is executed without connecting to the Distributor. ignore_distributor is bit, with a default of 0. This parameter can be used to drop a subscription without doing cleanup tasks at the Distributor. It is also useful if you had to reinstall the Distributor.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_dropmergesubscription is used in merge replication.

Permissions

Only members of the sysadmin fixed server role or the db_owner fixed database role can execute sp_dropmergesubscription.

See Also
sp_addmergesubscription | sp_helpmergesubscription
sp_changemergesubscription | System Stored Procedures


sp_dropmessage

Drops a specified error message from the sysmessages system table.

Syntax

sp_dropmessage [@msgnum =] message_number
[, [@lang =] 'language']

Arguments
[@msgnum =] message_number
Is the message number to drop. message_number must be a user-defined message with a message number greater than 50000. message_number is int, with a default of NULL.
[@lang =] 'language'
Is the language of the message to drop. If all is specified, all language versions of message_number are dropped. language is sysname, with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Permissions

Execute permissions default to members of the sysadmin fixed server role.

Examples

This example drops the message (number 50001) from sysmessages.

USE master

EXEC sp_dropmessage 50001

Here is the result:

Message dropped.

See Also
CREATE TABLE | sp_altermessage
RAISERROR | System Stored Procedures
sp_addmessage |


sp_droppublication

Drops a publication and its associated articles.

Syntax

sp_droppublication [@publication =] 'publication'
[,[@ignore_distributor =] ignore_distributor]

Arguments
[@publication =] 'publication'
Is the name of the publication to be dropped. publication is sysname, with no default. If all is specified, all publications are dropped from the publication database, except for those with subscriptions.
[@ignore_distributor =] ignore_distributor
For internal use only.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_droppublication is used in snapshot and transactional replication.

sp_droppublication recursively drops all articles associated with a publication and then drops the publication itself. A publication cannot be removed if it has one or more subscriptions to it. The associated sync task is also dropped.

Permissions

Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_droppublication.

See Also
sp_addarticle | sp_enumfullsubscribers
sp_addpublication | sp_helparticle
sp_articlecolumn | sp_helparticlecolumns
sp_changearticle | sp_helppublication
sp_changepublication | System Stored Procedures
sp_droparticle |


sp_droppullsubscription

Drops a subscription at the current database of the Subscriber.

Syntax

sp_droppullsubscription [@publisher =] 'publisher',
[@publisher_db =] 'publisher_db', [@publication =] 'publication'
[,[@reserved =] 'reserved']

Arguments
[@publisher =] 'publisher'
Is the remote server name. publisher is sysname, with no default. If all, the subscription is dropped at all the Publishers.
[@publisher_db =] 'publisher_db'
Is the name of the Publisher database. publisher_db is sysname, with no default. all means all the Publisher databases.
[@publication =] 'publication'
Is the publication name. publication is sysname, with no default. If all, the subscription is dropped to all the publications.
[@reserved =] 'reserved'
For internal use only.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_droppullsubscription is used in snapshot and transactional replication.

sp_droppullsubscription deletes the corresponding row in the MSreplication_subscriptions table and the corresponding Distributor Agent at the Subscriber. If no rows are left in Msreplication_subscriptions, it drops the table.

Permissions

Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_droppullsubscription.

See Also
sp_addpullsubscription System Stored Procedures


sp_dropremotelogin

Removes a remote login mapped to a local login used to execute remote stored procedures against the local server running Microsoft® SQL Server™.

Syntax

sp_dropremotelogin [@remoteserver =] 'remoteserver'
[,[@loginame =] 'login']
[,[@remotename =] 'remote_name']

Arguments
[@remoteserver =] 'remoteserver'
Is the name of the remote server mapped to the remote login that is to be removed. remoteserver is sysname, with no default. remoteserver must already exist.
[@loginame =] 'login'
Is the optional login name on the local server that is associated with the remote server. login is sysname, with a default of NULL. login must already exist if specified.
[@remotename =] 'remote_name'
Is the optional name of the remote login that is mapped to login when logging in from the remote server. remote_name is sysname, with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Remarks

If only remoteserver is specified, all remote logins for that remote server are removed from the local server. If login is additionally specified, all remote logins from remoteserver mapped to that specific local login are removed from the local server. If remote_name is also specified, only the remote login for that remote user from remoteserver is removed from the local server.

To add local server users, use sp_addlogin. To remove local server users, use sp_droplogin.

Remote logins are only required when using earlier versions of SQL Server. SQL Server version 7.0 uses linked server logins instead. Use sp_addlinkedsrvlogin and sp_droplinkedsrvlogin to add and remove linked server logins.

sp_dropremotelogin cannot be executed within a user-defined transaction.

Permissions

Only members of the sysadmin or securityadmin fixed server roles can execute sp_dropremotelogin.

Examples
A. Drop all remote logins for a remote server

This example removes the entry for the remote server ACCOUNTS, thereby removing all mappings between logins on the local server and remote logins on the remote server.

EXEC sp_dropremotelogin 'ACCOUNTS'

B. Drop a login mapping

This example removes the entry for mapping remote logins from the remote server ACCOUNTS to the local login Albert.

EXEC sp_dropremotelogin 'ACCOUNTS', 'Albert'

C. Drop a remote user

This example removes the login for the remote login Chris on the remote server ACCOUNTS that was mapped to the local login salesmgr.

EXEC sp_dropremotelogin 'ACCOUNTS', 'salesmgr', 'Chris'

See Also
sp_addlogin | sp_droplinkedsrvlogin
sp_addlinkedsrvlogin | sp_droplogin
sp_addremotelogin | sp_helpremotelogin
sp_addserver | System Stored Procedures


sp_droprole

Removes a Microsoft® SQL Server™ role from the current database.

Syntax

sp_droprole [@rolename =] 'role'

Arguments
[@rolename =] 'role'
Is the name of the role to remove from the current database. role is sysname, with no default. role must already exist in the current database.
Return Code Values

0 (success) or 1 (failure)

Result Sets
Column name | Data type | Description
Name | sysname | The name of the existing member of the role

Remarks

Only standard user roles can be removed using sp_droprole. To remove an application role, use sp_dropapprole.

A role with existing members cannot be removed. All members of the role must first be removed from the role before the role can be removed. To remove users from a role, use sp_droprolemember. If any users are still members of the role, sp_droprole displays those members.

Fixed roles and the public role cannot be removed.

A role cannot be removed if it owns any objects. Either remove the objects before removing the role, or use sp_changeobjectowner to change the owner of any objects that must not be removed.

sp_droprole cannot be executed from within a user-defined transaction.

Permissions

Only members of the db_owner or db_securityadmin fixed database roles can execute sp_droprole.

Examples

This example removes the SQL Server role Sales.

EXEC sp_droprole 'Sales'

See Also
sp_addrole | System Stored Procedures
sp_dropapprole |


sp_droprolemember

Removes a security account from a Microsoft® SQL Server™ role in the current database.

Syntax

sp_droprolemember [@rolename =] 'role',
[@membername =] 'security_account'

Arguments
'role'
Is the name of the role that the member is being removed from. role is sysname, with no default. role must exist in the current database.
'security_account'
Is the name of the security account being removed from the role. security_account is sysname, with no default. security_account can be a SQL Server user or another SQL Server role, or a Microsoft Windows NT® user or group. security_account must exist in the current database. When specifying a Windows NT user or group, specify the name that the Windows NT user or group is known by in the database (added using sp_grantdbaccess).
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_droprolemember removes a role member by deleting a row from the sysmembers table. When removing a member from a role, the permissions applied to the role are no longer applied to the former member of the role.

sp_droprolemember cannot be used to remove a Windows NT user from a Windows NT group; this must be done in the Windows NT security system. To remove a user from a fixed server role, use sp_dropsrvrolemember. Users cannot be removed from the public role, and dbo cannot be removed from any role.

Use sp_helpuser to see the members of a SQL Server role, and use sp_addrolemember to add a member to a role.

sp_droprolemember cannot be executed from within a user-defined transaction.

Permissions

Only members of the db_owner or db_securityadmin fixed database roles can execute sp_droprolemember. Only a member of the db_owner fixed database role can remove users from a fixed database role.

Examples

This example removes the user JonB from the role Sales.

EXEC sp_droprolemember 'Sales', 'Jonb'

See Also
sp_addrolemember | sp_helpuser
sp_droprole | System Stored Procedures
sp_dropsrvrolemember |


sp_dropserver

Removes a server from the list of known remote and linked servers on the local Microsoft® SQL Server™.

Syntax

sp_dropserver [@server =] 'server' [, [@droplogins =]{'droplogins' | NULL}]

Arguments
[@server =] 'server'
Is the server to be removed. server is sysname, with no default. server must exist.
[@droplogins =] 'droplogins' | NULL
Indicates that related remote and linked server logins for server must also be removed if droplogins is specified. @droplogins is char(10), with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Remarks

Running sp_dropserver on a server that has associated remote and linked server login entries results in an error message stating that logins must be removed before removing the remote or linked server. To remove all remote and linked server logins for a server when removing the server, use the droplogins argument.

sp_dropserver cannot be executed inside a user-defined transaction.

Permissions

Only members of the sysadmin or setupadmin fixed server roles can execute sp_dropserver.

Examples

This example removes the remote server ACCOUNTS and all associated remote logins from the local SQL Server.

sp_dropserver 'ACCOUNTS', 'droplogins'

See Also
sp_addserver | sp_helpserver
sp_dropremotelogin | System Stored Procedures
sp_helpremotelogin |


sp_dropsrvrolemember

Removes a Microsoft® SQL Server™ login or a Microsoft Windows NT® user or group from a fixed server role.

Syntax

sp_dropsrvrolemember [@loginame =] 'login', [@rolename =] 'role'

Arguments
[@loginame =] 'login'
Is the name of a login to remove from the fixed server role. login is sysname, with no default. login must exist.
[@rolename =] 'role'
Is the name of a server role. role is sysname, with a default of NULL. role must be a valid fixed server role, and must be one of these values:
  • sysadmin
  • securityadmin
  • serveradmin
  • setupadmin
  • processadmin
  • diskadmin
  • dbcreator
Return Code Values

0 (success) or 1 (failure)

Remarks

Only sp_dropsrvrolemember can be used to remove a login from a server role. Use sp_droprolemember to remove a member from a standard SQL Server role.

When a login has been removed from a server role, that login can no longer perform activities based on the permissions associated with the server role.

The sa login cannot be removed from any fixed server role.

sp_dropsrvrolemember cannot be executed from within a user-defined transaction.

Permissions

Only members of the sysadmin fixed server role can execute sp_dropsrvrolemember to remove any login from a fixed server role. Members of a fixed server role can remove other members of the same fixed server role.

Examples

This example removes the login JackO from the sysadmin fixed server role.

EXEC sp_dropsrvrolemember 'JackO', 'sysadmin'

See Also
sp_addsrvrolemember | System Stored Procedures
sp_droprolemember |


sp_dropsubscriber

Removes the Subscriber designation from a registered server.

Syntax

sp_dropsubscriber [@subscriber =] 'subscriber' [,[@reserved =] 'reserved']
[,[@ignore_distributor =] ignore_distributor]

Arguments
[@subscriber =] 'subscriber'
Is the name of the Subscriber to be dropped. subscriber is sysname, with no default.
[@reserved =] 'reserved'
For internal use only.
[@ignore_distributor =] ignore_distributor
For internal use only.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_dropsubscriber is used in all types of replication.

This stored procedure removes the server sub option and removes the remote login mapping of system administrator to repl_subscriber.

Permissions

Only members of the sysadmin fixed server role can execute sp_dropsubscriber.

See Also
sp_addsubscriber | sp_helpserver
sp_changesubscriber | sp_helpsubscriberinfo
sp_dboption | System Stored Procedures
sp_helpdistributor |


sp_dropsubscription

Drops subscriptions to a particular article, publication, or set of subscriptions on the Publisher.

Syntax

sp_dropsubscription [[@publication =] 'publication'] [,[@article =]'article']
{,[@subscriber =] 'subscriber'} [,[@destination_db =] 'destination_db']
[,[@ignore_distributor =] ignore_distributor] [,[@reserved =] 'reserved']

Arguments
[@publication =] 'publication'
Is the name of the associated publication. publication is sysname, with a default of NULL. If all, all subscriptions for all publications for the specified Subscriber are canceled.
[@article =] 'article'
Is the name of the article. article is sysname, with a default of NULL. If all, subscriptions to all articles for each specified publication and Subscriber are dropped. If article is not supplied, subscriptions are dropped for all articles in the publication. Use all for immediate-sync publications.
[@subscriber =] 'subscriber'
Is the name of the Subscriber that will have its subscriptions dropped. subscriber is sysname, with no default. If all, all subscriptions for all Subscribers are dropped.
[@destination_db =] 'destination_db'
Is the name of the destination database. destination_db is sysname, with a default of NULL. If NULL, all the subscriptions from that Subscriber are dropped.
[@ignore_distributor =] ignore_distributor
For internal use only.
[@reserved =] 'reserved'
Is reserved for internal use only. reserved is nvarchar(10).
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_dropsubscription is used in snapshot and transactional replication.

If you drop the subscription on an article in an immediate_sync publication, you cannot add it back unless you drop the subscriptions on all the articles in the publication and add them all back at once.

Permissions

Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_dropsubscription. A remote connection from the Subscriber can drop a subscription to an existing publication or article.

See Also
sp_addsubscription | sp_helpsubscription
sp_changesubstatus | System Stored Procedures


sp_droptask

sp_droptask is provided for backward compatibility only.

Removes a scheduled task.

Important For information about syntax used in earlier versions of SQL Server, see the Microsoft SQL Server Transact-SQL Reference for version 6.x.

Remarks

If you create a task by using sp_addtask, that task must be deleted only by using sp_droptask. For task management, use SQL Server Enterprise Manager.

Permissions

Execute permissions default to the public role.

See Also
sp_addtask | sp_updatetask
sp_helptask | System Stored Procedures
sp_purgehistory |


sp_droptype

Deletes a user-defined data type from systypes.

Syntax

sp_droptype [@typename =] 'type'

Arguments
[@typename =] 'type'
Is the name of a user-defined data type that you own. type is sysname, with no default.
Return Code Type

0 (success) or 1 (failure)

Result Sets

None

Remarks

The type user-defined data type cannot be dropped if tables or other database objects reference it.

Note A user-defined data type cannot be dropped if the user-defined data type is used within a table definition or if a rule or default is bound to it.

Permissions

Execute permissions default to the members of the db_owner fixed database role and the data type owner.

Examples

This example drops the user-defined data type birthday.

Note This user-defined data type must already exist or this example returns an error message.

USE master

EXEC sp_droptype 'birthday'

See Also
sp_addtype | System Stored Procedures
sp_rename |


sp_dropuser

Removes a Microsoft® SQL Server™ user or Microsoft Windows NT® user from the current database. sp_dropuser is provided for backward compatibility. Use sp_revokedbaccess to remove a user.

Syntax

sp_dropuser [@name_in_db =] 'user'

Arguments
[@name_in_db =] 'user'
Is the name of the user to remove. user is sysname, with no default. user must exist in the current database. When specifying a Windows NT user, specify the name that the Windows NT user is known by in the database (added using sp_grantdbaccess).
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_dropuser executes sp_revokedbaccess to remove the user from the current database.

Use sp_helpuser to display a list of the usernames that can be removed from the current database.

When the security account for a user is removed, any aliases to that user are also removed. A user cannot be removed if the user owns any objects in the database. Ownership of the objects must be changed to another user using sp_changeobjectowner. Removing a user automatically removes the permissions associated with the user and removes them from any roles of which the user is a member.

sp_dropuser cannot be used to remove the dbo or INFORMATION_SCHEMA users, nor the guest user from the master or tempdb databases.

sp_dropuser cannot be executed from within a user-defined transaction.

Permissions

Only members of the db_owner or db_accessadmin fixed database roles can execute sp_dropuser.

Examples

This example removes the user Albert from the current database.

EXEC sp_dropuser 'Albert'

See Also
sp_grantdbaccess | System Stored Procedures
sp_revokedbaccess |


sp_dropwebtask

Deletes a previously defined Web task.

Note All Web tasks or jobs are categorized as Web Assistant in the Job Categories dialog box in SQL Server Enterprise Manager.

Syntax

sp_dropwebtask {[@procname =] 'procname' | [,@outputfile =] 'outputfile'}

Arguments
[@procname =] 'procname'
Is the name of the procedure that defines the query for the task. procname is nvarchar(128), with a default of NULL.
[@outputfile =] 'outputfile'
Is the name of the HTML output file to be deleted. putputfile is nvarchar(255), with a default of NULL.
Return Code Values

0 (success) or a nonzero (failure)

Important The return code values have changed from earlier versions of Microsoft® SQL Server™.

Result Sets

None

Remarks

sp_dropwebtask accepts either or both parameters. If outputfile is specified without procname, a placeholder value of NULL can be specified for procname, or the parameter name @procname can be used. These examples are equivalent:

sp_dropwebtask NULL,'filename.htm'

sp_dropwebtask @procname = 'filename.htm'

sp_dropwebtask must be executed in the database specified in the dbname parameter of sp_makewebtask.

Running sp_dropwebtask on a database of a version earlier than Microsoft SQL Server version 7.0 returns an error.

Permissions

Only the owner of the specified procedure can execute sp_dropwebtask to delete the Web task.

Examples

This example deletes a Web task with the output file C:\Web\Myfile.html and a procedure named MYHTML.

sp_dropwebtask 'MYHTML', 'C:\WEB\MYFILE.HTML'

See Also
sp_makewebtask | System Stored Procedures
sp_runwebtask |


sp_dsninfo

Returns ODBC or OLE DB data source information from the Distributor associated with the current server.

Syntax

sp_dsninfo [@dsn =] 'dsn'
[, [@infotype =] 'info_type']
[, [@login =] 'login']
[, [@password =] 'password']
[, [@dso_type =] dso_type]

Arguments
[@dsn =] 'dsn'
Is the name of the ODBC DSN or OLE DB linked server. dsn is varchar(128), with no default.
[@infotype =] 'info_type'
Is the type of information to return. If info_type is not specified or if NULL is specified, all information types are returned. info_type is varchar(128), with a default of NULL, and can be one of these values.

Value | Description
DBMS_NAME | Specifies the data source vendor name.
DBMS_VERSION | Specifies the data source version.
DATABASE_NAME | Specifies the database name.
SQL_SUBSCRIBER | Specifies the data source can be a Subscriber.

[@login =] 'login'
Is the login for the data source. If the data source includes a login, specify NULL or omit the parameter. login is varchar(128), with a default of NULL.
[@password =] 'password'
Is the password for the login. If the data source includes a login, specify NULL or omit the parameter. password is varchar(128), with a default of NULL.
[@dso_type =] dso_type
Is the data source type. dso_type is int, and can be one of these values.

Value | Description
1 (default) | ODBC data source
3 | OLE DB data source

Return Code Values

0 (success) or 1 (failure)

Result Set
Column name | Data type | Description
Information Type | nvarchar(64) | Information types such as DBMS_NAME, DBMS_VERSION, DATABASE_NAME, SQL_SUBSCRIBER.
Value | nvarchar(512) | Value of the associated information type.

Remarks

sp_dsninfo is used in all types of replication.

sp_dsninfo retrieves ODBC or OLE DB data source information that shows whether the database can be used for replication or querying.

Permissions

Only members of the sysadmin fixed server role can execute sp_dsninfo.

See Also
sp_enumdsn System Stored Procedures


sp_dumpparamcmd

Returns detailed information for a parameterized command that has been stored in the distribution database.

Syntax

sp_dumpparamcmd [@originator_id =] 'originator_id',
[@publisher_database_id =] 'publisher_database_id',
[@article_id =] 'article_id', [@xact_seqno =] 'xact_seqno'

Arguments
[@originator_id =] 'originator_id'
Is the originator_id for which to return parameterized commands. originator_id is int, with no default.
[@publisher_database_id =] 'publisher_database_id'
Is the publisher_database_id for which to return parameterized commands. publisher_database_id is int, with no default.
[@article_id =] 'article_id'
Is the article_id for which to return parameterized commands. article_id is int, with no default.
[@xact_seqno =] 'xact_seqno'
Is the exact sequence number for which to display parameterized commands. xact_seqno is nchar(22), with no default.
Result Sets

sp_dumpparamcmd is a diagnostic procedure used to retrieve detailed information on parameterized commands within a single transaction. sp_dumpparamcmd returns two result sets for each parameterized command within the transaction.

Column name | Data type | Description
bytes | int | Number of bytes of Transact-SQL.
params | smallint | Number of parameters in the statement.
command | nvarchar(1024) | Transact-SQL command.

Note Long commands may be split across several rows in the results set. Long values may also be split across several rows in the results set.

The second result set contains one or more rows for each parameter.

Column name | Data type | Description
paramid | smallint | ID of the parameter.
offset | int | Byte offset within the data stream.
repltype | nvarchar(20) | Type information.
storage | nvarchar(20) | Storage information.
align | int | Alignment of data.
ctype | nvarchar(20) | ODBC C type information.
sqltype | nvarchar(20) | ODBC SQL type information.
prec | int | Precision of the value.
scale | smallint | Scale of the value.
token_fragment | nvarchar(1024) | Displays the value stored in this token in a text format.

Remarks

sp_dumpparamcmd is used in transactional replication.

Permissions

Only members of the sysadmin fixed server role can execute sp_ dumpparamcmd.

See Also
sp_browsereplcmds | sp_replshowcmds
sp_replcmds | System Stored Procedures


sp_enumcodepages

Returns a list of the code pages and character sets supported by sp_makewebtask.

Syntax

sp_enumcodepages

Return Code Values

0 (success) or 1 (failure)

Result Set
Column name | Data type | Description
Code Page | integer | Code page supporting the character set
Character Set | varchar(50) | Character set alias code recognized by Microsoft® Internet Explorer and other browsers.
Description | varchar(255) | Description of the character set.

Remarks

The appropriate .nls files must be installed by the operating system and made available so that sp_makewebtask can create the .htm file from the proper code page.

Permissions

Execute permissions default to the public role.

Examples

This example returns a list of supported code pages and character sets supported by sp_makewebtask.

EXEC sp_enumcodepages

See Also
sp_makewebtask System Stored Procedures


sp_enumcustomresolvers

Returns a list of all available custom resolvers.

Syntax

sp_enumcustomresolvers [[@distributor =] 'distributor']

Arguments
[@distributor =] 'distributor'
Is the name of the Distributor where the custom resolver is located. distributor is sysname, with a default of NULL.
Result Set
Column name | Data type | Description
value | ntext | Name of the custom resolver
data | ntext | Class ID of the custom resolver

Return Code Values

0 (success) or 1 (failure)

Remarks

sp_enumcustomresolvers is used in merge replication.

Permissions

Only members of the sysadmin fixed server role and the db_owner fixed database role can execute sp_enumcustomresolvers.

See Also
System Stored Procedures


sp_enumdsn

Returns a list of all defined ODBC and OLE DB data source names for a server running under a specific Microsoft® Windows NT® user account.

Syntax

sp_enumdsn

Return Code Values

0 (success) or 1 (failure)

Result Set
Column name | Data type | Description
Data Source Name | sysname | Name of the data source
Description | varchar(255) | Description of the data source
Type | int | Type of data source: 1 = ODBC DSN 3 = OLE DB data source
Provider Name | varchar(255) | Name of the OLE DB provider. Value is NULL for ODBC DSN.

Remarks

Every Microsoft SQL Server™ service has a user context. A user context is a set of Registry entries that includes the definitions of the ODBC data sources for the user. The user context is provided by the username under which the SQL Server is running.

For example, if the server is running under the system account user context, the DSNs that are returned will all be system DSNs that are associated with the system account. If the server is running under a private user account, only the DSNs defined for that user’s private account are returned.

Permissions

Only members of the sysadmin fixed server role can execute sp_enumdsn.

See Also
sp_dsninfo System Stored Procedures


sp_enumfullsubscribers

Returns a list of Subscribers who have subscribed to all articles in a specified publication.

Syntax

sp_enumfullsubscribers [[@publication =] 'publication']

Arguments
[@publication =] 'publication'
Is the name of the publication. publication is sysname, with a default of %. If publication is not specified, all publications are returned.
Return Code Values

0 (success) or 1 (failure)

Result Set
Column name | Data type | Description
subscriber | sysname | Name of the subscribing server

Remarks

sp_enumfullsubscribers is used in snapshot, transactional, and merge replication.

Permissions

Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_enumfullsubscribers.

See Also
sp_addarticle | sp_droppublication
sp_addpublication | sp_helparticle
sp_articlecolumn | sp_helparticlecolumns
sp_changearticle | sp_helppublication
sp_changepublication | System Stored Procedures
sp_droparticle |


sp_executesql

Executes a Transact-SQL statement or batch that can be reused many times, or that has been built dynamically. The Transact-SQL statement or batch can contain embedded parameters.

Syntax

sp_executesql [@stmt =] stmt
[
{, [@params =] N'@parameter_name data_type [,…n]' }
{, [@param1 =] 'value1'[,…n] }
]

Arguments
[@stmt =] stmt
Is a Unicode string containing a Transact-SQL statement or batch. stmt must be either a Unicode constant or a variable that can be implicitly converted to ntext. More complex Unicode expressions (such as concatenating two strings with the + operator) are not allowed. Character constants are not allowed. If a constant is specified, it must be prefixed with an N. For example, the Unicode constant N’sp_who’ is legal, but the character constant ‘sp_who’ is not. The size of the string is limited only by available database server memory.

stmt can contain parameters having the same form as a variable name, for example:

N'SELECT * FROM Employees WHERE EmployeeID = @IDParameter'

Each parameter included in stmt must have a corresponding entry in both the @params parameter definition list and the parameter values list.

[@params =] N'@parameter_name data_type [,…n]'
Is one string that contains the definitions of all parameters that have been embedded in stmt. The string must be either a Unicode constant or a variable that can be implicitly converted to ntext. Each parameter definition consists of a parameter name and a data type. n is a placeholder indicating additional parameter definitions. Every parameter specified in stmt must be defined in @params. If the Transact-SQL statement or batch in stmt does not contain parameters, @params is not needed. The default value for this parameter is NULL.
[@param1 =] 'value1'
Is a value for the first parameter defined in the parameter string. The value can be a constant or a variable. There must be a parameter value supplied for every parameter included in stmt. The values are not needed if the Transact-SQL statement or batch in stmt has no parameters.
n
Is a placeholder for the values of additional parameters. Values can be only constants or variables. Values cannot be more complex expressions such as functions, or expressions built using operators.
Return Code Values

0 (success) or 1 (failure)

Result Sets

Returns the result sets from all the SQL statements built into the SQL string.

Remarks

sp_executesql has the same behavior as EXECUTE with regard to batches, the scope of names, and database context. The Transact-SQL statement or batch in the sp_executesql stmt parameter is not compiled until the sp_executesql statement is executed. The contents of stmt are then compiled and executed as an execution plan separate from the execution plan of the batch that called sp_executesql. The sp_executesql batch cannot reference variables declared in the batch calling sp_executesql. Local cursors or variables in the sp_executesql batch are not visible to the batch calling sp_executesql. Changes in database context last only to the end of the sp_executesql statement.

sp_executesql can be used instead of stored procedures to execute a Transact-SQL statement a number of times when the change in parameter values to the statement is the only variation. Because the Transact-SQL statement itself remains constant and only the parameter values change, the Microsoft® SQL Server™ query optimizer is likely to reuse the execution plan it generates for the first execution.

Note If object names in the statement string are not fully qualified, the execution plan is not reused.

sp_executesql supports the setting of parameter values separately from the Transact-SQL string:

DECLARE @IntVariable INT

DECLARE @SQLString NVARCHAR(500)

DECLARE @ParmDefinition NVARCHAR(500)

/* Build the SQL string once.*/

SET @SQLString =

     N'SELECT * FROM pubs.dbo.employee WHERE job_lvl = @level'

SET @ParmDefinition = N'@level tinyint'

/* Execute the string with the first parameter value. */

SET @IntVariable = 35

EXECUTE sp_executesql @SQLString, @ParmDefinition,

                      @level = @IntVariable

/* Execute the same string with the second parameter value. */

SET @IntVariable = 32

EXECUTE sp_executesql @SQLString, @ParmDefinition,

                      @level = @IntVariable

Being able to substitute parameters in sp_executesql offers these advantages to using the EXECUTE statement to execute a string:

  • Because the actual text of the Transact-SQL statement in the sp_executesql string does not change between executions, the query optimizer will probably match the Transact-SQL statement in the second execution with the execution plan generated for the first execution. Therefore, SQL Server does not have to compile the second statement.
  • The Transact-SQL string is built only once.
  • The integer parameter is specified in its native format. Casting to Unicode is not required.
Permissions

Execute permissions default to the public role.

Examples
A. Execute a simple SELECT statement

This example creates and executes a simple SELECT statement that contains an embedded parameter named @level.

execute sp_executesql

          N'select * from pubs.dbo.employee where job_lvl = @level',

          N'@level tinyint',

          @level = 35

B. Execute a dynamically built string

This example shows using sp_executesql to execute a dynamically built string. The example stored procedure is used to insert data into a set of tables used to partition sales data for a year. There is one table for each month of the year with the following format:

CREATE TABLE May1998Sales

    (OrderID        INT        PRIMARY KEY,

    CustomerID        INT        NOT NULL,

    OrderDate        DATETIME    NULL

        CHECK (DATEPART(yy, OrderDate) = 1998),

    OrderMonth        INT

        CHECK (OrderMonth = 5),

    DeliveryDate    DATETIME    NULL,

        CHECK (DATEPART(mm, OrderDate) = OrderMonth)

    )

The name of each table consists of the first three letters of the month name, the four digits of the year, and the constant Sales. The name can be built dynamically from an order date:

       /* Get the first three characters of the month name. */

       SUBSTRING( DATENAME(mm, @PrmOrderDate), 1, 3) +

       /* Concatenate the four-digit year; cast as character. */

       CAST(DATEPART(yy, @PrmOrderDate) AS CHAR(4) ) +

       /* Concatenate the constant 'Sales'. */

       'Sales'

This sample stored procedure dynamically builds and executes an INSERT statement to insert new orders into the correct table. It uses the order date to build the name of the table that should contain the data, then incorporates that name into an INSERT statement. (This is a simple example for sp_executesql. It does not contain error checking and does not include checks for business rules, such as ensuring that order numbers are not duplicated between tables.)

CREATE PROCEDURE InsertSales @PrmOrderID INT, @PrmCustomerID INT,

                 @PrmOrderDate DATETIME, @PrmDeliveryDate DATETIME

AS

DECLARE @InsertString NVARCHAR(500)

DECLARE @OrderMonth INT

-- Build the INSERT statement.

SET @InsertString = 'INSERT INTO ' +

       /* Build the name of the table. */

       SUBSTRING( DATENAME(mm, @PrmOrderDate), 1, 3) +

       CAST(DATEPART(yy, @PrmOrderDate) AS CHAR(4) ) +

       'Sales' +

       /* Build a VALUES clause. */

       ' VALUES (@InsOrderID, @InsCustID, @InsOrdDate,' +

       ' @InsOrdMonth, @InsDelDate)'

/* Set the value to use for the order month because

   functions are not allowed in the sp_executesql parameter

   list. */

SET @OrderMonth = DATEPART(mm, @PrmOrderDate)

EXEC sp_executesql @InsertString,

     N'@InsOrderID INT, @InsCustID INT, @InsOrdDate DATETIME,

       @InsOrdMonth INT, @InsDelDate DATETIME',

     @PrmOrderID, @PrmCustomerID, @PrmOrderDate,

     @OrderMonth, @PrmDeliveryDate

GO

Using sp_executesql in this procedure is more efficient than using EXECUTE to execute a string. When sp_executesql is used, there are only 12 versions of the INSERT string generated, 1 for each monthly table. With EXECUTE, each INSERT string is unique because the parameter values are different. Although both methods generate the same number of batches, the similarity of the INSERT strings generated by sp_executesql makes it more likely that the query optimizer will reuse execution plans.

See Also
EXECUTE System Stored Procedures


sp_fkeys

Returns logical foreign key information for the current environment. This procedure shows foreign key relationships including disabled foreign keys.

Syntax

sp_fkeys [@pktable_name =] 'pktable_name'
[,[@pktable_owner =] 'pktable_owner']
[,[@pktable_qualifier =] 'pktable_qualifier']
{, [@fktable_name =] 'fktable_name'}
[,[@fktable_owner =] 'fktable_owner']
[,[@fktable_qualifier =] 'fktable_qualifier']

Arguments
[@pktable_name =] 'pktable_name'
Is the name of the table (with the primary key) used to return catalog information. pktable_name is sysname, with a default of NULL. Wildcard pattern matching is not supported. This parameter or the fktable_name parameter, or both, must be supplied.
[@pktable_owner =] 'pktable_owner'
Is the name of the owner of the table (with the primary key) used to return catalog information. pktable_owner is sysname, with a default of NULL. Wildcard pattern matching is not supported. If pktable_owner is not specified, the default table visibility rules of the underlying DBMS apply.

In Microsoft® SQL Server™, if the current user owns a table with the specified name, that table’s columns are returned. If pktable_owner is not specified and the current user does not own a table with the specified pktable_name, the procedure looks for a table with the specified pktable_name owned by the database owner. If one exists, that table’s columns are returned.

[@pktable_qualifier =] 'pktable_qualifier'
Is the name of the table (with the primary key) qualifier. pktable_qualifier is sysname, with a default of NULL. Various DBMS products support three-part naming for tables (qualifier.owner.name). In SQL Server, the qualifier represents the database name. In some products, it represents the server name of the table’s database environment.
[@fktable_name =] 'fktable_name'
Is the name of the table (with a foreign key) used to return catalog information. fktable_name is sysname, with a default of NULL. Wildcard pattern matching is not supported. This parameter or the pktable_name parameter, or both, must be supplied.
[@fktable_owner =] 'fktable_owner'
Is the name of the owner of the table (with a foreign key) used to return catalog information. fktable_owner is sysname, with a default of NULL. Wildcard pattern matching is not supported. If fktable_owner is not specified, the default table visibility rules of the underlying DBMS apply.

In SQL Server, if the current user owns a table with the specified name, that table’s columns are returned. If fktable_owner is not specified and the current user does not own a table with the specified fktable_name, the procedure looks for a table with the specified fktable_name owned by the database owner. If one exists, that table’s columns are returned.

[@fktable_qualifier =] 'fktable_qualifier'
Is the name of the table (with a foreign key) qualifier. fktable_qualifier is sysname, with a default of NULL. In SQL Server, the qualifier represents the database name. In some products, it represents the server name of the table’s database environment.
Return Code Values

None

Result Sets
Column name | Data type | Description
PKTABLE_QUALIFIER | sysname | Name of the table (with the primary key) qualifier. This field can be NULL.
PKTABLE_OWNER | sysname | Name of the table (with the primary key) owner. This field always returns a value.
PKTABLE_NAME | sysname | Name of the table (with the primary key). This field always returns a value.
PKCOLUMN_NAME | sysname | Name of the primary key column(s), for each column of the TABLE_NAME returned. This field always returns a value.
FKTABLE_QUALIFIER | sysname | Name of the table (with a foreign key) qualifier. This field can be NULL.
FKTABLE_OWNER | sysname | Name of the table (with a foreign key) owner. This field always returns a value.
FKTABLE_NAME | sysname | Name of the table (with a foreign key). This field always returns a value.
FKCOLUMN_NAME | varchar(32) | Name of the foreign key column(s), for each column of the TABLE_NAME returned. This field always returns a value.
KEY_SEQ | smallint | Sequence number of the column in a multicolumn primary key. This field always returns a value.
UPDATE_RULE | smallint | Action applied to the foreign key when the SQL operation is an update. SQL Server returns 1 for these columns. Open Data Services gateways can return values of 0, 1, or 2: 0 = CASCADE changes to foreign key. 1 = RESTRICT changes if foreign key is present. 2 = SET_NULL; set foreign key to NULL.
DELETE_RULE | smallint | Action applied to the foreign key when the SQL operation is a deletion. SQL Server returns 1 for these columns. Open Data Services gateways can return values of 0, 1, or 2: 0 = CASCADE changes to foreign key. 1 = RESTRICT changes if foreign key is present. 2 = SET_NULL; set foreign key to NULL.
FK_NAME | sysname | Foreign key identifier. It is NULL if not applicable to the data source. SQL Server returns the FOREIGN KEY constraint name.
PK_NAME | sysname | Primary key identifier. It is NULL if not applicable to the data source. SQL Server returns the PRIMARY KEY constraint name.

The results returned are ordered by FKTABLE_QUALIFIER, FKTABLE_OWNER, FKTABLE_NAME, and KEY_SEQ.

Remarks

Application coding that includes tables with disabled foreign keys can be implemented by:

  • Temporarily disabling constraint checking (ALTER TABLE NOCHECK or CREATE TABLE NOT FOR REPLICATION) while working with the tables, and enabling it again later.
  • Using triggers or application code to enforce relationships.

If the primary key table name is supplied and the foreign key table name is NULL, sp_fkeys returns all tables that include a foreign key to the given table. If the foreign key table name is supplied and the primary key table name is NULL, sp_fkeys returns all tables related by a primary key/foreign key relationship to foreign keys in the foreign key table. Note that this procedure does not support the common key type as specified in the SQL Server syskeys system table.

The sp_fkeys stored procedure is equivalent to SQLForeignKeys in ODBC.

Permissions

Execute permissions default to the public role.

Examples

This example retrieves a list of foreign keys for the Customers table in the Northwind database.

USE Northwind

EXEC sp_fkeys @pktable_name = N'Customers'

See Also

sp_pkeys


sp_foreignkeys

Returns the foreign keys that reference primary keys on the table in the linked server.

Syntax

sp_foreignkeys [@table_server =] 'table_server'
[,[@pktab_name =] 'pktab_name']
[,[@pktab_schema =] 'pktab_schema']
[,[@pktab_catalog =] 'pktab_catalog']
[,[@fktab_name =] 'fktab_name']
[,[@fktab_schema =] 'fktab_schema']
[,[@fktab_catalog =] 'fktab_catalog']

Arguments
[@table_server =] 'table_server'
Is the name of the linked server for which to return table information. table_server is sysname, with no default.
[@pktab_name =] 'pktab_name'
Is the name of the table with a primary key. pktab_name is sysname, with a default of NULL.
[@pktab_schema =] 'pktab_schema'
Is the name of the schema with a primary key. pktab_schema is sysname, with a default of NULL. In SQL Server, this contains the owner name.
[@pktab_catalog =] 'pktab_catalog'
Is the name of the catalog with a primary key. pktab_catalog is sysname, with a default of NULL. In SQL Server, this contains the database name.
[@fktab_name =] 'fktab_name'
Is the name of the table with a foreign key. fktab_name is sysname, with a default of NULL.
[@fktab_schema =] 'fktab_schema'
Is the name of the schema with a foreign key. fktab_schema is sysname, with a default of NULL.
[@fktab_catalog =] 'fktab_catalog'
Is the name of the catalog with a foreign key. fktab_catalog is sysname, with a default of NULL.
Return Code Values

None

Result Sets

Various DBMS products support three-part naming for tables (catalog.schema.table), which is represented in the result set.

Column name | Data type | Description
PKTABLE_CAT | sysname | Catalog for the table in which the primary key resides.
PKTABLE_SCHEM | sysname | Schema for the table in which the primary key resides.
PKTABLE_NAME | sysname | Name of the table (with the primary key). This field always returns a value.
PKCOLUMN_NAME | sysname | Name of the primary key column(s), for each column of the TABLE_NAME returned. This field always returns a value.
FKTABLE_CAT | sysname | Catalog for the table in which the foreign key resides.
FKTABLE_SCHEM | sysname | Schema for the table in which the foreign key resides.
FKTABLE_NAME | sysname | Name of the table (with a foreign key). This field always returns a value.
FKCOLUMN_NAME | sysname | Name of the foreign key column(s), for each column of the TABLE_NAME returned. This field always returns a value.
KEY_SEQ | smallint | Sequence number of the column in a multicolumn primary key. This field always returns a value.
UPDATE_RULE | smallint | Action applied to the foreign key when the SQL operation is an update. SQL Server returns 1 for these columns. Open Data Services gateways can return values of 0, 1, or 2: 0 = CASCADE changes to foreign key. 1 = NO ACTION on changes if foreign key is present. 2 = SET_NULL; set foreign key to NULL.
DELETE_RULE | smallint | Action applied to the foreign key when the SQL operation is a deletion. SQL Server returns 1 for these columns. Open Data Services gateways can return values of 0, 1, or 2: 0 = CASCADE changes to foreign key. 1 = NO ACTION on changes if foreign key is present. 2 = SET_NULL; set foreign key to NULL.
FK_NAME | sysname | Foreign key identifier. It is NULL if not applicable to the data source. SQL Server returns the FOREIGN KEY constraint name.
PK_NAME | sysname | Primary key identifier. It is NULL if not applicable to the data source. SQL Server returns the PRIMARY KEY constraint name.
DEFERRABILITY | smallint | Indicates whether constraint checking is deferrable.

In the result set, the FK_NAME and PK_NAME columns always return NULL.

Remarks

sp_foreignkeys queries the FOREIGN_KEYS rowset of the IDBSchemaRowset interface of the OLE DB provider that corresponds to table_server. The table_name, table_schema, table_catalog, and column parameters are passed to this interface to restrict the rows that are returned.

Examples

This example returns foreign key information about the Customers table in the Northwind database.

USE master

EXEC sp_foreignkeys @table_server = N'LONDON1',
    @pktab_name = N'Customers',
    @pktab_catalog = N'Northwind'

See Also
sp_catalogs | sp_primarykeys
sp_column_privileges | sp_table_privileges
sp_indexes | sp_tables_ex
sp_linkedservers | System Stored Procedures


sp_fulltext_catalog

Creates and drops a full-text catalog, and starts and stops the indexing action for a catalog. Multiple full-text catalogs can be created per database.

Syntax

sp_fulltext_catalog [@ftcat =] 'fulltext_catalog_name',
[@action =] 'action'
[,[@path =] 'root_directory']

Arguments
[@ftcat =] 'fulltext_catalog_name'
Is the name of the full-text catalog. Catalog names must be unique for each database. fulltext_catalog_name is sysname.
[@action =] 'action'
Is the action to be performed. action is varchar(20), and can be one of these values.

Value | Description
create | Creates an empty, new full-text catalog in the file system and adds an associated row in sysfulltextcatalogs with the fulltext_catalog_name and root_directory (if present) values. fulltext_catalog_name must be unique within the database.
drop Drops fulltext_catalog_name by removing it from the file system and deleting the associated row in sysfulltextcatalogs. This action fails if full-text index metadata has been created for the catalog; that is, if sp_fulltext_table with the create option has been executed for this catalog.

An error is displayed if the catalog does not exist.
start_incremental | Starts an incremental population for fulltext_catalog_name. An error is displayed if the catalog does not exist. If a full-text index population is already active, a warning is displayed but no population action occurs. With incremental population, only changed rows are retrieved for full-text indexing, provided there is a timestamp column present in the table being full-text indexed.
start_full | Starts a full population for fulltext_catalog_name. Every row of every table associated with this full-text catalog is retrieved for full-text indexing, even if it already has been indexed.
stop | Stops an index population for fulltext_catalog_name. An error is displayed if the catalog does not exist. No warning is displayed if population is already stopped.
rebuild Rebuilds fulltext_catalog_name by deleting the existing full-text catalog from the file system, re-creating the full-text catalog, and reassociating the full-text catalog with all the tables that have full-text indexing references.

Rebuilding does not change any full-text metadata in the database system tables, nor does it cause the repopulation of the newly created full-text catalog. To repopulate, sp_fulltext_catalog must be executed with the start_full or start_incremental action.

[@path =] 'root_directory'
Is the root directory (not the complete physical path) for a create action. root_directory is nvarchar(100) and has a default value of NULL, which indicates to use the default location specified at setup. (This is the Ftdata subdirectory in the Mssql7 directory; for example, C:\Mssql7\Ftdata.). The specified root directory must exist, reside on a drive on the same computer; consist of more than just the drive letter, and cannot be a relative path. Network drives, removable drives, floppy disks, and UNC paths are not supported. Full-text catalogs must be created on a local hard drive associated with the machine on which SQL Server is running.

@path is valid only when action is create. For actions other than create (stop, rebuild, and so on), @path must be NULL or omitted.

Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

The start_full action is used to create a complete snapshot of the full-text data in fulltext_catalog_name. The start_incremental action is used to reindex only the changed rows in the database. For an incremental index, a timestamp column is required in one column of the table.

Full-text catalog and index data is stored in files created in a full-text catalog directory. The full-text catalog directory is created as a sub-directory of the directory specified in @path, or in the server's default full-text catalog directory if @path is not specified. The name of the full-text catalog directory is built in a way that guarantees it will be unique on the server. Therefore, all full-text catalog directories on a server can share the same path.

Permissions

Only members of the db_owner (or higher) fixed database roles can execute sp_fulltext_catalog.

Examples
A. Create a full-text catalog

This example creates an empty full-text catalog, Cat_Desc, in the Northwind database.

USE Northwind

EXEC sp_fulltext_catalog 'Cat_Desc', 'create'

B. Start the population of a full-text catalog

This example begins a full population of the Cat_Desc catalog.

USE Northwind

EXEC sp_fulltext_catalog 'Cat_Desc', 'start_full'

See Also
FULLTEXTCATALOGPROPERTY | sp_help_fulltext_catalogs_cursor
sp_fulltext_database | System Stored Procedures
sp_help_fulltext_catalogs |


sp_fulltext_column

Specifies whether or not a particular column of a table participates in full-text indexing.

Syntax

sp_fulltext_column [@tabname =] 'qualified_table_name',
[@colname =] 'column_name',
[@action =] 'action'

Arguments
[@tabname =] 'qualified_table_name'
Is a one- or two-part table name. The table must exist in the current database. The table must have a full-text index, but the full-text index must be inactive. qualified_table_name is nvarchar(517), with no default value.
[@colname =] 'column_name'
Is the name of a column in qualified_table_name. The column must be a character column and cannot be a computed column. column_name is sysname, with no default.
[@action =] 'action'
Is the action to be performed. action is varchar(20), with no default value, and can be one of these values.

Value | Description
add | Adds column_name of qualified_table_name to the table’s inactive full-text index.
drop | Removes column_name of qualified_table_name from the table’s inactive full-text index.

Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Permissions

Only qualified table owners or members of the db_ddladmin fixed database role can execute sp_fulltext_column.

Examples

This example adds the Description column from the Categories table to the table's full-text index.

USE Northwind

EXEC sp_fulltext_column Categories, Description, 'add'

See Also
OBJECTPROPERTY | sp_help_fulltext_tables
sp_help_fulltext_columns | sp_help_fulltext_tables_cursor
sp_help_fulltext_columns_cursor | System Stored Procedures


sp_fulltext_database

Initializes full-text indexing or removes all full-text catalogs from the current database.

Syntax

sp_fulltext_database [@action =] 'action'

Arguments
[@action =] 'action'
Is the action to be performed. action is varchar(20), and can be one of these values.

Value | Description
enable | Enables full-text indexing within the current database. If full-text catalogs already exist, this procedure drops all full-text catalogs, re-creates any full-text indexing indicated in the system tables, and marks the database as full-text enabled. This action does not cause index population to begin; an explicit start_full or start_incremental on each catalog must be issued using sp_fulltext_catalog to populate or repopulate the full-text index.
disable | Removes all full-text catalogs in the file system for the current database and marks the database as being disabled for full-text indexing. This action does not change any full-text index metadata at the full-text catalog or table level.

Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

Disabling full-text indexing does not remove rows from sysfulltextcatalogs and does not mean that full-text enabled tables are no longer marked for full-text indexing. All the full-text metadata definitions are still in the system tables. It does mean that full-text indexing has been turned off for the database and no full-text indexing activity can occur.

Permissions

Only members of the db_owner fixed database role can execute sp_fulltext_database.

Examples

This example enables full-text indexing for the Northwind database.

USE Northwind

EXEC sp_fulltext_database 'enable'

See Also
DATABASEPROPERTY FULLTEXTSERVICEPROPERTY


sp_fulltext_service

Changes Microsoft Search Service (Full-text Search) properties.

Syntax

sp_fulltext_service [@action =] 'action'
[,[@value =] 'value']

Arguments
[@action =] 'action'
Is the property to be changed or reset. action is varchar(20), with no default, and can be one of these values.

Value | Description
resource_usage | Specifies the amount of resources to be used for the Microsoft Search Service.
clean_up | Searches for and removes the full-text catalog resources in the file system that do not have corresponding entries in sysfulltextcatalogs.
connect_timeout Is the number of seconds that Microsoft Search Service will wait for connections to Microsoft® SQL Server™ for full-text populations before timing out.

If a time-out occurs before Microsoft SQL Server responds to a database request, the population fails to complete.

[@value =] 'value'
Is the value of the specified property. value is integer, with a default value of NULL. The table shows the required values for the properties.

Property | Value
resource_usage | 1 (background) through 5 (dedicated), with a default of 3
clean_up | NULL
connect_timeout | Between 1 and 32767

Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

There may be times when the metadata for a full-text catalog is changed (for example, when the full-text catalog is being dropped or the database is being dropped) while the Microsoft Search Service (MSSearch) is not running. The drop action changes the metadata related to the full-text catalogs, but is unable to complete execution because the Microsoft Search Service is not running. This leads to inconsistency between the full-text metadata in SQL Server and the associated physical full-text catalog in the file system. This inconsistency can be corrected by using the clean_up action of sp_fulltext_service. (Microsoft Search Service must be running, of course).

Permissions

Only members of the serveradmin fixed server role or the system administrator can execute sp_fulltext_service.

Examples

This example performs a cleanup operation on the full-text catalogs.

EXEC sp_fulltext_service 'clean_up'

See Also
FULLTEXTSERVICEPROPERTY System Stored Procedures


sp_fulltext_table

Marks or unmarks a table for full-text indexing.

Syntax

sp_fulltext_table [@tabname =] 'qualified_table_name',
[@action =] 'action'
[,[@ftcat =] 'fulltext_catalog_name',
[@keyname =] 'unique_index_name']

Arguments
[@tabname =] 'qualified_table_name'
Is a one- or two-part table name. The table must exist in the current database. qualified_table_name is nvarchar(517), with no default.
[@action =] 'action'
Is the action to be performed. action is varchar(20), with no default, and can be one of these values.

Value | Description
create Creates the metadata for a full-text index for the table referenced by qualified_table_name and specifies that the full-text index data for this table should reside in fulltext_catalog_name. This action also designates the use of unique_index_name as the full-text key column. This unique index must already be present and must be defined on one column of the table.

A full-text search cannot be performed against this table until the full-text index has been activated and the full-text catalog has been populated using either the start_incremental or start_full action of sp_fulltext_catalog.
drop | Drops the metadata on the full-text index for qualified_table_name. If the full-text index is active, it is automatically deactivated before being dropped. It is not necessary to remove columns before dropping the full-text index.
activate Activates the ability for full-text index data to be gathered for qualified_table_name. There must be at least one column participating in the full-text index before it can be activated.

Note that this does not actually populate the full-text index, but simply registers the table in the full-text catalog in the file system so that rows from qualified_table_name can be retrieved during the next full-text index population.
deactivate | Deactivates the full-text index for qualified_table_name so that it no longer participates in the population of the full-text catalog. The full-text index metadata remains, however, and the table can be reactivated.

[@ftcat =] 'fulltext_catalog_name'
Is a valid, existing full-text catalog name for a create action. For all other actions, this parameter must be NULL. fulltext_catalog_name is sysname, with a default of NULL.
[@keyname =] 'unique_index_name'
Is a valid single-key-column, unique nonnullable index on qualified_table_name for a create action. For all other actions, this parameter must be NULL. unique_index_name is sysname, with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

After a full-text index has been deactivated for a particular table, the existing full-text index remains in place until the next full population; however, this index is not used because Microsoft® SQL Server™ blocks queries on deactivated tables.

If the table is reactivated and the index is not repopulated, the old index is still available for queries against any remaining (but not new) full-text enabled columns. Data from deleted columns are matched in queries that specify an all-full-text columns (*) search.

After a table has been defined for full-text indexing, switching the full-text unique key column from one data type to another (either by changing the data type of that column or changing the full-text unique key from one column to another) without a full repopulation may cause a failure to occur during a subsequent query (returning the error message: “Conversion to type data_type failed for full-text search key value key_value”). To prevent this, drop the full-text definition for this table altogether (using the drop action of sp_fulltext_table) and redefine it (using sp_fulltext_table and sp_fulltext_column).

If the full-text unique key column is a character or Unicode character column, it must be defined to be 450 bytes or less.

Permissions

Only members of the db_owner and db_ddladmin fixed database roles can execute sp_fulltext_table.

Examples
A. Create metadata for a full-text index on a table

This example creates full-text index metadata for the Categories table of the Northwind database. Cat_Desc is a full-text catalog. PK_Categories is a unique, single-column index on Categories.

USE Northwind

EXEC sp_fulltext_table Categories, 'create', 'Cat_Desc', PK_Categories

B. Activate full-text indexing on a table

This example activates full-text indexing on the Categories table.

USE Northwind

EXEC sp_fulltext_table Categories, 'activate'

See Also
INDEXPROPERTY | sp_help_fulltext_tables_cursor
OBJECTPROPERTY | sp_helpindex
sp_help_fulltext_tables | System Stored Procedures


sp_generatefilters

Creates filters on foreign key tables when a specified table is replicated.

Syntax

sp_generatefilters [@publication =] 'publication'

Arguments
[@publication =] 'publication'
Is the name of the publication to be filtered. publication is sysname, with no default.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_generatefilters is used in merge replication.

Permissions

Only members of the sysadmin fixed server role or the db_owner fixed database role can execute sp_generatefilters.

See Also
sp_bindsession System Stored Procedures


sp_getbindtoken

Creates a bound connection context and returns a unique identifier for the created context. This unique identifier is referred to as a bind token. sp_getbindtoken returns a string representation to use as a token for a shared transaction between two clients.

Syntax

sp_getbindtoken [@out_token =] 'return_value' OUTPUT [, @for_xp_flag]

Arguments
[@out_token =] 'return_value'
Is the token to use to share a transaction context. return_value is varchar(255), with no default.
@for_xp_flag
Is a constant. If equal to 1, a bind token is created that can be passed to an extended stored procedure to call back into the server.
Return Code Values

None

Result Sets

None

Remarks

The bind token can be used with sp_bindsession to bind new sessions to the same transaction context. Sessions on one computer running Microsoft® SQL Server™ that are bound to the same transaction context share a single-transaction lock space during each session.

To obtain and pass a bind token, you must run sp_getbindtoken prior to executing sp_bindsession for sharing the same lock space. If you obtain a bind token, sp_bindsession runs correctly.

If a constant is not used for @for_xp_flag, this error message is returned:

Msg 214, Level 16, State 1, Server <server_name>, Procedure
<procedure_name>, Line 5

Cannot convert parameter @for_xp_flag to type constant expected by
procedure.

Note It is recommended that you use the srv_getbindtoken Open Data Services API to obtain a bind token to be used from an extended stored procedure.

Permissions

Only the owner of the bind token can retrieve that particular bind token.

Examples

A. Obtain a bind token

This example obtains a bind token and displays the bind token name.

DECLARE @bind_token varchar(255)

EXECUTE sp_getbindtoken @bind_token OUTPUT

SELECT @bind_token AS Token

This is the result set:

Token

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

\0]---5^PJK51bP<1F<-7U-]ANZ

Note Your bind token name will differ from the results displayed.

B. Use the @for_xp_flag parameter

    This example specifies a constant to use for calling back to the server.

    DECLARE @bind_token varchar(255)

    EXECUTE sp_getbindtoken @bind_token OUTPUT, 1

    SELECT @bind_token AS Token

    See Also
    sp_bindsession System Stored Procedures


sp_getmergedeletetype

Returns the type of merge delete.

Syntax

sp_getmergedeletetype [@source_object =] 'source_object',
[@rowguid =] 'rowguid', [@delete_type =] delete_type OUTPUT

Arguments
[@source_object =] 'source_object'
Is the name of the source object. source_object is nvarchar(386), with no default.
[@rowguid =] 'rowguid'
Is the row identifier for the delete type. rowguid is uniqueidentifier, with no default.
[@delete_type =] delete_type OUTPUT
Is the code indicating the type of delete. delete_type is int, with no default. delete_type is also an OUTPUT parameter, and can be one of these values.

Value | Description
1 | User delete
5 | Partial delete
6 | System delete

Remarks

sp_getmergedeletetype is used in merge replication.

Permissions

Only members of the sysadmin fixed server role or the db_owner fixed database role can execute sp_getmergedeletetype.

See Also

System Stored Procedures


sp_get_distributor

Determines whether a Distributor is installed on a server.

Syntax

sp_get_distributor

Result Sets
Column name | Data type | Description
installed | int | 0 = No 1 = Yes
distribution server | sysname | Name of the Distributor server
distribution db installed | int | 0 = No 1 = Yes
is distribution publisher | int | 0 = No 1 = Yes
has remote distribution publisher | int | 0 = No 1 = Yes

Remarks

sp_get_distributor is used primarily by the Microsoft SQL Server Enterprise Manager in snapshot, transactional, and merge replication.

Permissions

Members of the public role can execute sp_get_distributor.

See Also

System Stored Procedures


sp_grant_publication_access

Adds a login to the publication’s access list.

Syntax

sp_grant_publication_access [@publication =] 'publication',
[@login =] 'login' [,[@reserved =] 'reserved']

Arguments
[@publication =] 'publication'
Is the name of the publication to access. 'publication' is sysname, with a no default.
[@login =] 'login'
Is the login ID. 'login' is sysname, with no default.
[@reserved =] 'reserved'
For internal use only.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_grant_publication_access is used in snapshot, transactional, and merge replication.

This stored procedure can be called repeatedly.

Permissions

Only members of the sysadmin fixed server role or the db_owner fixed database role can execute sp_grant_publication_access.

See Also
sp_help_publication_access | System Stored Procedures
sp_revoke_publication_access |


sp_grantdbaccess

Adds a security account in the current database for a Microsoft® SQL Server™ login or Microsoft Windows NT® user or group, and enables it to be granted permissions to perform activities in the database.

Syntax

sp_grantdbaccess [@loginame =] 'login'
[,[@name_in_db =] 'name_in_db' [OUTPUT]]

Arguments
[@loginame =] 'login'
Is the name of the login for the new security account in the current database. Windows NT groups and users must be qualified with a Windows NT domain name in the form Domain\User, for example LONDON\Joeb. The login cannot already be aliased to an account in the database. login is sysname, with no default.
[@name_in_db =] 'name_in_db' [OUTPUT]
Is the name for the account in the database. name_in_db is an OUTPUT variable with a data type of sysname, and a default of NULL. If not specified, login is used. If specified as an OUTPUT variable with a value of NULL, @name_in_db is set to login. name_in_db must not already exist in the current database.
Return Code Values

0 (success) or 1 (failure)

Remarks

SQL Server usernames can contain from 1 to 128 characters, including letters, symbols, and numbers. However, usernames cannot:

  • Contain a backslash character (\).
  • Be NULL, or an empty string (‘‘).

The security account must be granted access to the current database before it can use the database. Only accounts in the current database can be managed using sp_grantdbaccess. To remove an account from a database, use sp_revokedbaccess.

A security account for guest can be added if it does not already exist in the current database, and the login is also guest.

The sa login cannot be added to a database.

sp_grantdbaccess cannot be executed from within a user-defined transaction.

Permissions

Only members of the db_accessadmin or db_owner fixed database roles can execute sp_grantdbaccess.

Examples

This example adds an account for the Windows NT user Corporate\GeorgeW to the current database and gives it the name Georgie.

EXEC sp_grantdbaccess 'Corporate\GeorgeW', 'Georgie'

See Also
sp_revokedbaccess System Stored Procedures


sp_grantlogin

Allows a Microsoft® Windows NT® user or group account to connect to Microsoft SQL Server™ using Windows NT Authentication.

Syntax

sp_grantlogin [@loginame =] 'login'

Arguments
[@loginame =] 'login'
Is the name of the Windows NT user or group to be added. The Windows NT user or group must be qualified with a Windows NT domain name in the form Domain\User, for example London\Joeb. login is sysname, with no default.
Return Code Values

0 (success) or 1 (failure)

Remarks

Use sp_grantlogin to reverse the effects of a previous sp_denylogin that has been executed for a Windows NT user.

Use sp_addlogin to allow a SQL Server login to connect to SQL Server.

Although a login can connect to SQL Server after sp_grantlogin has been executed, access to user databases is denied until a user account for the login is created in each database that the login must access. Use sp_grantdbaccess to create a user account in each user database.

sp_grantlogin cannot be executed within a user-defined transaction.

Permissions

Only members of the sysadmin or securityadmin fixed server roles can execute sp_grantlogin.

Examples

This example allows the Windows NT user Corporate\BobJ to connect to SQL Server.

EXEC sp_grantlogin 'Corporate\BobJ'

Or

EXEC sp_grantlogin [Corporate\BobJ]

See Also
sp_addlogin | sp_revokelogin
sp_denylogin | System Stored Procedures


sp_help

Reports information about a database object (any object listed in the sysobjects table), a user-defined data type, or a data type supplied by Microsoft® SQL Server™.

Syntax

sp_help [[@objname =] name]

Arguments
[@objname =] name
Is the name of any object, in sysobjects or any user-defined data type in the systypes table. name is nvarchar(776), with a default of NULL. Database names are not acceptable.
Return Code Values

0 (success) or 1 (failure)

Result Sets

If sp_help is executed with no arguments, summary information of objects of all types that exist in the current database is returned.

Column name | Data type | Description
Name | nvarchar(128) | Object name
Owner | nvarchar(128) | Object owner
Object_type | nvarchar(31) | Object type

If name is a SQL Server data type or user-defined data type, sp_help returns this result set.

Column name | Data type | Description
Type_name | nvarchar(128) | Data type name.
Storage_type | nvarchar(128) | SQL Server type name.
Length | smallint | Physical length of the data type (in bytes).
Prec | int | Precision (total number of digits).
Scale | int | Number of digits to the right of the decimal.
Nullable | varchar(35) | Indicates whether NULL values are allowed: Yes or No
Default_name | nvarchar(128) | Name of a default bound to this type. NULL, if no default is bound.
Rule_name | nvarchar(128) | Name of a rule bound to this type. NULL, if no default is bound.

If name is any database object (other than a date type), sp_help returns this result set, as well as additional result sets based on the type of object specified.

Column name | Data type | Description
Name | nvarchar(128) | Table name
Owner | nvarchar(128) | Table owner
Type | nvarchar(31) | Table type
Created_datetime | datetime | Date table created

Depending on the database object specified, sp_help returns additional result sets.

If name is a system table, user table, or view, sp_help returns these result sets (except the result set describing where the data file is located on a file group is not returned for a view).

Column name | Data type | Description
Column_name | nvarchar(128) | Column name.
Type | nvarchar(128) | Column data type.
Computed | varchar(35) | Indicates whether the values in the column are computed: (Yes or No).
Length | int | Column length in bytes.
Prec | char(5) | Column precision.
Scale | char(5) | Column scale.
Nullable | varchar(35) | Indicates whether NULL values are allowed in the column: Yes or No.
TrimTrailingBlanks | varchar(35) | Trim the trailing blanks (yes or no).
FixedLenNullInSource | varchar(35) | For backward compatibility only.

Column name | Data type | Description
Identity | nvarchar(128) | Column name whose data type is declared as identity.
Seed | numeric | Starting value for the identity column.
Increment | numeric | Increment to use for values in this column.
Not For Replication | int | IDENTITY property is not enforced when a replication login, such as sqlrepl, inserts data into the table: 1 = True 0 = False

Column name | Data type | Description
RowGuidCol | sysname | Name of the global unique identifier column

Column name | Data type | Description
Data_located_on_ filegroup | nvarchar(128) | The file group in which the data is located (Primary, Secondary, or Transaction Log)

Column name | Data type | Description
index_name | sysname | Index name
Index_description | varchar(210) | Description of the index
index_keys | nvarchar(2078) | Column name(s) on which the index is built

Column name | Data type | Description
constraint_type | nvarchar(146) | Type of constraint.
constraint_name | nvarchar(128) | Name of the constraint.
status_enabled | varchar(8) | Indicates whether the constraint is enabled: Enabled, Disabled or N/A. (Only applicable to CHECK and FOREIGN KEY constraints.
status_for_replication | varchar(19) | Indicates whether the constraint is for replication. (Only applicable to CHECK and FOREIGN KEY constraints.)
constraint_keys | nvarchar(2078) | Names of the columns that make up the constraint or, in the case for defaults and rules, the text that defines the default or rule.

Column name | Data type | Description
Table is referenced by | nvarchar(516) | Identifies other database objects that reference the table.

If name is a system stored procedure or an extended stored procedure, sp_help returns this result set.

Column name | Data type | Description
Parameter_name | nvarchar(128) | Stored procedure parameter name
Type | nvarchar(128) | Data type of the stored procedure parameter
Length | smallint | Maximum physical storage length (in bytes)
Prec | int | Precision (total number of digits)
Scale | int | Number of digits to the right of the decimal point
Param_order | smallint | Order of the parameter

Remarks

The sp_help procedure looks for an object in the current database only.

When name is not specified, sp_help lists object names, owners, and object types for all objects in the current database. sp_helptrigger provides information about triggers.

Permissions

Execute permissions default to the public role.

Examples
A. Return information about all objects

This example lists information about each object in sysobjects.

USE master

EXEC sp_help sysobjects

B. Return information about a single object

This example displays information about the publishers table.

USE pubs

EXEC sp_help publishers

See Also
sp_helpgroup | sp_helpuser
sp_helpindex | sp_helptrigger
sp_helprotect | System Stored Procedures
sp_helpserver |


sp_help_agent_default

Retrieves the ID of the default configuration for the agent type passed as parameter.

Syntax

sp_help_agent_default [@profile_id =] profile_id OUTPUT,
[@agent_type =] agent_type

Arguments
[@profile_id =] profile_id OUTPUT
Is the ID of the default configuration for the type of agent. profile_id is int, with no default. profile_id is also an OUTPUT parameter and returns the ID of the default configuration for the type of agent.
[@agent_type =] 'agent_type'
Is the type of agent. agent_type is int, with no default, and can be one of these values.

Value | Description
1 | Snapshot Agent
2 | Log Reader Agent
3 | Distribution Agent
4 | Merge Agent

Remarks

sp_help_agent_default is used in all types of replication.

Permissions

Execute permissions default to the public role.

See Also
System Stored Procedures


sp_help_agent_parameter

Returns all the parameters of a profile from the MSagent_parameters system table.

Syntax

sp_help_agent_parameter [[@profile_id =] profile_id]

Arguments
[@profile_id =] profile_id
Is the ID of the profile from the MSagent_profiles table. profile_id is int, with a default of -1, which returns all parameters.
Result Sets
Column name | Data type | Description
profile_id | int | ID of the agent profile
parameter_name | sysname | Name of the parameter
value | nvarchar(255) | Value of the parameter

Remarks

sp_help_agent_parameter is used in all types of replication.

Permissions

Execute permissions default to the public role.

See Also
sp_add_agent_parameter | System Stored Procedures
sp_drop_agent_parameter |


sp_help_agent_profile

Displays the profile of a specified agent.

Syntax

sp_help_agent_profile [[@agent_type =] agent_type]
[,[@profile_id =] profile_id]

Arguments
[@agent_type =] agent_type
Is the type of agent. agent_type is int, with a default of 0, and can be one of these values.

Value | Description
1 | Snapshot Agent
2 | Log Reader Agent
3 | Distribution Agent
4 | Merge Agent

[@profile_id =] profile_id
Is the ID of the profile to be displayed. profile_id is int, with a default of -1, which returns all the profiles in the MSagent_profiles table.
Result Sets
Column name | Data type | Description
profile_id | int | ID of the profile.
profile_name | sysname | Unique for agent type.
agent_type | int | 1 = Snapshot Agent 2 = Log Reader Agent 3 = Distribution Agent 4 = Merge Agent
type | int | 0 = System 1 = Custom
description | varchar(3000) | Description of the profile.
def_profile | bit | Specifies whether this profile is the default for this agent type.

Remarks

sp_help_agent_profile is used in all types of replication.

Permissions

Execute permissions default to the public role.

See Also
System Stored Procedures


sp_help_alert

Reports information about the alerts defined for the server.

Syntax

sp_help_alert [[@alert_name =] 'alert_name']
[, [@order_by =] 'order_by']
[, [@alert_id =] alert_id]
[, [@category_name =] 'category']

Arguments
[@alert_name =] 'alert_name'
Is the alert name. alert_name is nvarchar(128). If alert_name is not specified, information about all alerts is returned .
[@order_by =] 'order_by'
Is the sorting order to use for producing the results. order_by is sysname, with a default of N ‘name’.
[@alert_id =] alert_id]
Is the identification number of the alert to report information about. alert_id is int, with a default of NULL.
[@category_name =] 'category'
Is the category for the alert. category is sysname, with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Result Sets
Column name | Data type | Description
id | int | System-assigned unique integer identifier.
name | sysname | Alert name (for example, Demo: Full msdb log).
event_source | nvarchar(100) | Source of the event. It will always be MSSQLServer for Microsoft® SQL Server™ 7.0
event_category_id | int | Reserved.
event_id | int | Reserved.
message_id | int | Message error number that defines the alert. (Usually corresponds to an error number in the sysmessages table). If severity is used to define the alert, message_id is 0 or NULL.
severity | int | Severity level (9 through 25, 110, 120, 130, or 140) that defines the alert.
enabled | tinyint | Status of whether the alert is currently enabled (1) or not (0). A nonenabled alert is not sent.
delay_between_responses | int | Wait period, in seconds, between responses to the alert.
last_occurrence_date | int | Data the alert last occurred.
last_occurrence_time | int | Time the alert last occurred.
last_response_date | int | Date the alert was last responded to by the SQL Server Agent service.
last_response_time | int | Time the alert was last responded to by the SQL Server Agent service.
notification_message | nvarchar(512) | Optional additional message sent to the operator as part of the e-mail or pager notification.
include_event_description | tinyint | Is whether the description of the SQL Server error from the Microsoft Windows NT® application log should be included as part of the notification message.
database_name | sysname | Database in which the error must occur for the alert to fire. If the database name is NULL, the alert fires regardless of where the error occurred.
event_description_keyword | nvarchar(100) | Description of the SQL Server error in the Windows NT application log that must be like the supplied sequence of characters.
occurrence_count | int | Number of times the alert occurred.
count_reset_date | int | Date the occurrence_count was last reset.
count_reset_time | int | Time the occurrence_count was last reset.
job_id | uniqueidentifier | Job identification number.
job_name | sysname | An on-demand job to be executed in response to an alert.
has_notification | int | Nonzero if one or more operators are notified for this alert. The value is one or more of the following values (ORed together). 1=has email notification 2=has pager notification 4=has netsend noticication.
flags | int | Reserved.
performance_condition | nvarchar(512) | If type is 2, this column shows the definition of the performance condition; otherwise, the column is NULL.
category_name | sysname | Reserved. Will always be ‘[Uncategorized]’ for SQL Server 7.0.
type | int | 1 = SQL Server event alert 2 = SQL Server performance alert

Remarks

sp_help_alert must be run from the msdb database.

Permissions

Only members of the sysadmin fixed server role can execute sp_help_alert .

Examples

This example reports information about the Demo: Sev. 25 Errors alert.

EXEC sp_help_alert 'Demo: Sev. 25 Errors'

See Also
sp_add_alert | System Stored Procedures
sp_update_alert |


sp_helparticle

Displays information about an article.

Syntax

sp_helparticle [@publication =] 'publication' [,[@article =] 'article']
[,[@returnfilter =] returnfilter]

Arguments
[@publication =] 'publication'
Is the name of the publication. publication is sysname, with no default.
[@article =] 'article'
Is the name of an article in the publication. article is sysname, with a default of %. If article is not supplied, information on all articles for the specified publication is returned.
[@returnfilter =] returnfilter
Is whether the filter clause should be returned. returnfilter is bit, with a default of 1, which returns the filter clause.
Result Sets
Column name | Data type | Description
article id | int | ID of the article.
article name | sysname | Name of the article.
base object | nvarchar(257) | Name of the underlying table represented by the article or stored procedure.
destination object | sysname | Name of the destination (subscription) table, if different from source_table or the stored procedure.
synchronization object | nvarchar(257) | Name of the table or view used for producing a synchronization output file.
type | tinyint | Type of article.
status | tinyint | Bitmask of the article name: 0 = For internal use. 1 = Active. 8 = Include the column name in insert statements. 16 = Use parameterized statements. 24 = Include the column name in INSERT statements and use parameterized statements.
filter | nvarchar(257) | Stored procedure (created with FOR REPLICATION) used to filter the table (horizontal filtering).
description | nvarchar(255) | Descriptive entry for the article.
insert_command | nvarchar(255) | Call to the stored procedure to execute upon insert.
update_command | nvarchar(255) | Call to the stored procedure to execute upon update.
delete_command | nvarchar(255) | Call to the stored procedure to execute upon delete.
creation script path | nvarchar(255) | Path and name of an article schema script used to create target tables.
vertical partition | bit | Columns to replicate.
pre_creation_cmd | tinyint | Precreation command for DROP TABLE, DELETE TABLE, or TRUNCATE TABLE.
filter_clause | ntext | WHERE clause specifying the horizontal filtering.
schema_option | binary(8) | Bitmap of the schema generation option for the given article.
dest_owner | sysname | Name of the owner of the destination object.
source_owner | sysname | Owner of the source object.
unqualified_source_object | sysname | Name of the source object, without the owner name.
sync_object_owner |  | Owner of the synchronization object.
unqualified_sync_object | sysname | Name of the synchronization object, without the owner name.
filter_owner | sysname | Owner of the filter.
unqualified_filter | sysname | Name of the filter, without the owner name.

Remarks

sp_helparticle is used in snapshot and transactional replication.

Permissions

Execute permissions default to the public role.

See Also
sp_addarticle | sp_droparticle
sp_addpublication | sp_droppublication
sp_articlecolumn | sp_enumfullsubscribers
sp_changearticle | sp_helppublication
sp_changepublication | System Stored Procedures


sp_helparticlecolumns

Returns all columns in the underlying table.

Syntax

sp_helparticlecolumns [@publication =] 'publication', [@article =] 'article'

Arguments
[@publication =] 'publication'
Is the name of the publication that contains the article. publication is sysname, with no default.
[@article =] 'article'
Is the name of the article that has its columns returned. article is sysname, with no default.
Return Code Values

0 (columns that are not published) or 1 (columns that are published)

Result Sets
Column name | Data type | Description
column id | int | Object ID of the table to which this column belongs.
column | sysname | Name of the column.
published | bit | Whether column is published: 0 = No 1 = Yes

Remarks

sp_helparticlecolumns is used in snapshot and transactional replication.

sp_helparticlecolumns is useful in checking a vertical partition.

Permissions

Execute permissions default to the public role.

See Also
sp_addarticle | sp_droparticle
sp_addpublication | sp_droppublication
sp_articlecolumn | sp_enumfullsubscribers
sp_changearticle | sp_helppublication
sp_changepublication | System Stored Procedures


sp_help_category

Provides information about the specified classes of jobs, alerts, or operators.

Syntax

sp_help_category [[@class =] 'class']
[,[@type =] 'type']
[,[@name =] 'name']
[,[@suffix =] suffix]

Arguments
[@class =] 'class'
Is the class about which information is requested. class is varchar(8), with a default value of JOB. class can be one of these values.

Value | Description
JOB | Provides information about a job category.
ALERT | Provides information about an alert category.
OPERATOR | Provides information about an operator category.

[@type =] 'type'
Is the type of category for which information is requested. type is varchar(12), with a default of NULL, and can be one of these values.

Value | Description
LOCAL | Local job category.
MULTI -SERVER | Multiserver job category.
NONE | Category for a class other than JOB.

[@name =] 'name'
Is the name of the category for which information is requested. name is sysname, with a default of NULL.
[@suffix =] suffix
Specifies whether the category_type column in the result set is an ID or a name. suffix is bit, with a default of 0. 1 shows the category_type as a name, and 0 shows it as an ID.
Return Code Values

0 (success) or 1 (failure)

Result Sets
Column name | Data type | Description
category_id | int | Category ID
category_type | tinyint | Type of category: 1 = Local 2 = Multiserver 3 = None
name | sysname | Category name

Remarks

sp_help_category must be executed in the msdb database.

If no parameters are specified, the result set provides information about all of the job categories.

Permissions

Execute permissions default to the public role. Anyone who can execute this procedure can also create, delete, or update a job, job step, job category, job schedule, job server, task, or job history information.

Examples
A. Return local job information

This example returns information about jobs that are administered locally.

USE msdb

EXEC sp_help_category @type = 'LOCAL'

B. Return alert information

This example returns information about the Replication alert category.

USE msdb

EXEC sp_help_category @class = 'ALERT', @name = 'Replication'

See Also
sp_add_category | sp_update_category
sp_delete_category | System Stored Procedures


sp_helpconstraint

Returns a list of all constraint types, their user-defined or system-supplied name, the columns on which they have been defined, and the expression that defines the constraint (for DEFAULT and CHECK constraints only).

Syntax

sp_helpconstraint [@objname =] 'table'
[,[@nomsg =] 'no_message']

Arguments
[@objname =] 'table'
Is the table about which constraint information is returned. The table specified must be local to the current database. table is nvarchar(776), with no default.
[@nomsg =] 'no_message'
Is an optional parameter that prints the table name. no_message is varchar(5), with a default of msg. nomsg suppresses the printing.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

Executing sp_help table reports all information about the specified table. To see only the constraint information, use sp_helpconstraint.

Permissions

Execute permissions default to the public role.

Examples

This example shows all constraints for the authors table.

USE pubs

EXEC sp_helpconstraint authors

See Also
ALTER TABLE | sp_help
CREATE TABLE | System Stored Procedures


sp_helpdb

Reports information about a specified database or all databases.

Syntax

sp_helpdb [[@dbname=] 'name']

Arguments
[@dbname=] 'name'
Is the name of the database for which to provide information. name is sysname, with no default. If name is not specified, sp_helpdb reports on all databases in master.dbo.sysdatabases.
Return Code Values

0 (success) or 1 (failure)

Result Sets
Column name | Data type | Description
name | nvarchar(24) | Database name.
db_size | nvarchar(13) | Total size of the database.
owner | nvarchar(24) | Database owner (such as sa).
dbid | smallint | Numeric database ID.
created | char(11) | Date the database was created.
status | varchar(340) | Database status (such as truncate log on check point).

If name is specified, there is an additional result set that shows the file allocation for the specified database.

Column name | Data type | Description
name | nchar(128) | Logical file name.
fileid | smallint | Numeric file identifier.
filename | nchar(260) | Operating-system file name (physical file name).
filegroup | nvarchar(128) | Group in which the file belongs. Database files can be grouped in file groups for allocation and administration purposes. Log files are never a part of a filegroup.
size | nvarchar(18) | File size.
maxsize | nvarchar(18) | Maximum size to which the file can grow. UNLIMITED value in this field indicate that the file grows until the disk is full.
growth | nvarchar(18) | Growth increment of the file. This indicates the amount of space added to the file each time new space is needed.
usage | varchar(9) | Usage of the file. For data file, the usage is data only and for the log file the usage is log only.

Remarks

The status column in the result set reports which bits have been turned on in the status column of sysdatabases. Information from the status2 column of sysdatabases is not reported.

Permissions

Execute permissions default to the public role.

Note sp_helpdb needs to access the database(s) on the server to determine the information to be displayed about the database. Therefore, for each database on the server, either:

  • The user executing sp_helpdb must have permissions to access the database.

Or,

  • The guest user account must exist in the database.

If a database cannot be accessed, sp_helpdb displays error message 15622 and as much information about the database as it can.

Examples
A. Return information about a single database

This example displays information about the pubs database.

exec sp_helpdb pubs

B. Return information about all databases

This example displays information about all databases on the server running Microsoft® SQL Server™, but does not include the device_fragments, size, and usage columns.

exec sp_helpdb

See Also
ALTER DATABASE | sp_dboption
CREATE DATABASE | sp_renamedb
sp_configure | System Stored Procedures


sp_helpdbfixedrole

Returns a list of the fixed database roles.

Syntax

sp_helpdbfixedrole [[@rolename =] 'role']

Arguments
[@rolename =] 'role'
Is the name of a fixed database role. role is sysname, with a default of NULL. If role is specified, only information about that role is returned; otherwise, a list and description of all fixed database roles is returned.
Return Code Values

0 (success) or 1 (failure)

Result Sets
Column name | Data type | Description
DbFixedRole | sysname | Name of the fixed database role
Description | nvarchar(70) | Description of DbFixedRole

Remarks

Fixed database roles are defined at the database level and have permissions to perform specific database-level administrative activities. Fixed database roles cannot be added, removed, or changed.

Fixed database role | Description
db_owner | Database owners
db_accessadmin | Database access administrators
db_securityadmin | Database security administrators
db_ddladmin | Database DDL administrators
db_backupoperator | Database backup operators
db_datareader | Database data readers
db_datawriter | Database data writers
db_denydatareader | Database deny data readers
db_denydatawriter | Database deny data writers

The table shows stored procedures used for modifying database roles.

Stored procedure | Action
sp_addrolemember | Adds a login account to a fixed database role.
sp_helprole | Displays a list of the members of a fixed database role.
sp_droprolemember | Removes a member from a fixed database role.

Permissions

Execute permissions default to the public role.

Examples

This example shows a list of all fixed database roles.

EXEC sp_helpdbfixedrole

See Also
sp_addrolemember | sp_helprole
sp_dbfixedrolepermission | sp_helprolemember
sp_droprolemember | System Stored Procedures


sp_helpdevice

Reports information about Microsoft® SQL Server™ database files. sp_helpdevice is used for backward compatibility with earlier versions of SQL Server that used the term device for a database file.

Syntax

sp_helpdevice [[@devname=] 'name']

Arguments
[@devname=] 'name'
Is the name of the device for which to provide information. name is sysname, with no default.
Return Code Values

0 (success) or 1 (failure)

Result Sets
Column name | Data type | Description
device_name | sysname | Device name (or file name)
physical_name | nvarchar(46) | Physical file name
description | varchar(255) | Description of the device
status | int | A number that corresponds to the status description in the description column
cntrltype | smallint | Controller number of the device: 2 = Hard disk device 3 or 4 = Disk dump device 5 = Tape device 0 = Database device
size | int | Device size in 2 kb pages

Remarks

If name is specified, sp_helpdevice displays information about the specified database device or dump device. If name is not specified, sp_helpdevice displays information about all database devices and dump devices in master.dbo.sysdevices.

Old style database devices are added to the system with the DISK INIT statement. Dump devices are added to the system by sp_addumpdevice.

The device_number column is 0 for dump devices, 0 for the MASTER database device, and a value from 1 through 255 for other database devices.

Permissions

Execute permissions default to the public role.

Examples

This example reports information about all database devices and dump devices on SQL Server.

sp_helpdevice

See Also
sp_dropdevice sp_helpdb


sp_helpdistpublisher

Returns properties of a Publisher that serves as its own Distributor.

Syntax

sp_helpdistpublisher [[@publisher =] 'publisher']

Arguments
[@publisher =] 'publisher'
Is the Publisher for which properties are returned. publisher is sysname, with a default of %.
Result Sets
Column name | Data type | Description
name | sysname | Name of Publisher.
distribution_db | sysname | Distribution database for the specified Publisher.
security_mode | int | Security mode used by the replication agent in a push subscription to connect to the Publisher.
login | sysname | Login name used by the replication agent in a push subscription to connect to the Publisher.
password | sysname | Password returned (in simple encrypted form). Password is NULL for users other than sysadmin.
active | bit | Whether a remote Publisher is using the local server as a Distributor: 0 = No 1 = Yes
working_directory | nvarchar(255) | Name of the working directory.
trusted |  | Security mode implemented at the Distributor: 0 = SQL Server Authentication 1 = Windows NT Authentication
thirdparty_flag | bit | Whether the publication is a Microsoft® SQL Server™ database: 0 = Microsoft SQL Server 1 = Data source other than Microsoft SQL Server

Remarks
  • sp_helpdistpublisher is used in all types of replication.
Permissions

Execute permissions default to the public role.

See Also
sp_adddistpublisher | sp_dropdistpublisher
sp_changedistpublisher | System Stored Procedures


sp_helpdistributiondb

Returns properties of the specified distribution database(s).

Syntax

sp_helpdistributiondb [[@database =] 'database']

Arguments
[@database =] 'database'
Is the database name for which properties are returned. database is sysname, with a default of % for all databases.
Result Sets
Column name | Data type | Description
distribution_database | sysname | Name of the database.
min_distretention | int | Minimum retention period, in hours, before transactions are deleted.
max_distretention | int | Maximum retention period, in hours, before transactions are deleted.
history retention | int | Number of hours to retain history.
history_cleanup_agent | sysname | Name of the History Cleanup Agent.
distribution_cleanup_ agent | sysname | Name of the Distribution Cleanup Agent.
status | int | Not supported.
data_folder | nvarchar(255) | Name of the directory used to store the database files.
data_file | nvarchar(255) | Name of the database file.
data_file_size | int | Initial data file size in megabytes.
log_folder | nvarchar(255) | Name of the directory for the database log file.
log_file | nvarchar(255) | Name of the log file.
log_file_size | int | Initial log file size in megabytes.

Remarks

sp_helpdistributiondb is used in all types of replication.

Permissions

Execute permissions default to the public role.

See Also
sp_adddistributiondb | sp_dropdistributiondb
sp_changedistributiondb | System Stored Procedures


sp_helpdistributor

Lists information about the Distributor, distribution database, working directory, and SQL Server Agent user account.

Syntax

sp_helpdistributor [[@distributor =] 'distributor' OUTPUT]
[,[@distribdb =] 'distribdb' OUTPUT]
[,[@directory =] 'directory' OUTPUT]
[,[@account =] 'account' OUTPUT]
[,[@min_distretention =] min_distretention OUTPUT] [,[@max_distretention =] max_distretention OUTPUT]
[,[@history_retention =] history_retention OUTPUT]
[,[@history_cleanupagent =] 'history_cleanupagent' OUTPUT]
[,[@distrib_cleanupagent =] 'distrib_cleanupagent' OUTPUT]
[,[@publisher =] 'publisher'] [,[@local =] 'local']
[,[@rpcsrvname =] 'rpcsrvname' OUTPUT]

Arguments
[@distributor =] 'distributor' OUTPUT
Is the name of the Distributor. Distributor is sysname, with a default of %, which is the only value that returns a result set.
[@distribdb =] 'distribdb' OUTPUT
Is the name of the distribution database. distribdb is sysname, with a default of %, which is the only value that returns a result set.
[@directory =] 'directory' OUTPUT
Is the working directory. directory is nvarchar(255), with a default of %, which is the only value that returns a result set.
[@account =] 'account' OUTPUT
Is the Windows NT user account. account is nvarchar(255), with a default of %, which is the only value that returns a result set.
[@min_distretention =] min_distretention OUTPUT
Is the minimum distribution retention period, in hours. min_distretention is int, with a default of -1.
[@max_distretention =] max_distretention OUTPUT
Is the maximum distribution retention period, in hours. max_distretention is int, with a default of -1.
[@history_retention =] history_retention OUTPUT
Is the history retention period, in hours. history_retention is int, with a default of -1.
[@history_cleanupagent =] 'history_cleanupagent' OUTPUT
Is the name of the history cleanup agent. history_cleanupagent is nvarchar(100), with a default of %, which is the only value that returns a result set.
[@distrib_cleanupagent =] 'distrib_cleanupagent' OUTPUT
Is the name of the history cleanup agent. distrib_cleanupagent is nvarchar(100), with a default of %, which is the only value that returns a result set.
[@publisher =] 'publisher'
Is the name of the Publisher. publisher is sysname, with a default of NULL.
[@local =] 'local'
Is whether Microsoft® SQL Server™ should get local server values. local is nvarchar(5), with a default of NULL.
[@rpcsrvname =] 'rpcsrvname' OUTPUT
Is the name of the server that issues remote procedure calls. rpcsrvname is sysname, with a default of %, which is the only value that returns a result set.
Result Sets
Column name | Data type | Description
distributor | sysname | Name of the Distributor
distribution database | sysname | Name of the distribution database
directory | nvarchar(255) | Name of the working directory
account | nvarchar(255) | Name of the Microsoft Windows NT® user account
min distrib retention | int | Minimum distribution retention period
max distrib retention | int | Maximum distribution retention period
history retention | int | History retention period
history cleanup agent | nvarchar(100) | Name of the History Cleanup Agent
distribution cleanup agent | nvarchar(100) | Name of the Distribution Cleanup Agent
rpc server name | sysname | Name of the remote or local Distributor
rpc login name | sysname | Login used for remote procedure calls to the remote Distributor

If the distribution database is not installed, a NULL value is returned.

Remarks

sp_helpdistributor is used in all types of replication.

Permissions

Execute permissions default to the public role.

See Also
sp_adddistpublisher | sp_dropsubscriber
sp_addsubscriber | sp_helpserver
sp_changesubscriber | sp_helpsubscriberinfo
sp_changesubstatus | System Stored Procedures
sp_dboption |


sp_help_downloadlist

Lists all rows in the sysdownloadlist system table for the supplied job, or all rows if no job is specified.

Syntax

sp_help_downloadlist [[@job_id =] job_id | [@job_name =] 'job_name']
[,[@operation =] 'operation']
[,[@object_type =] 'object_type']
[,[@object_name =] 'object_name']
[,[@target_server =] 'target_server']
[,[@has_error =] has_error]
[,[@status =] status]
[,[@date_posted =] date_posted]

Arguments
[@job_id =] job_id
Is the job identification number for which to return information. job_id is uniqueidentifier, with a default of NULL.
[@job_name =] 'job_name'
Is the name of the job. job_name is varchar(100), with a default of NULL.
[@operation =] 'operation'
Is the valid operation for the specified job. operation is varchar(64), with a default of NULL, and can be one of these values.

Value | Definition
DEFECT | Server operation that requests the target server to defect from the Master SQL Server Agent.
DELETE | Job operation that removes an entire job.
INSERT | Job operation that inserts an entire job or refreshes an existing job. This operation includes all job steps and schedules, if applicable.
RE-ENLIST | Server operation that causes the target server to resend its enlistment information, including the polling interval and time zone to the multiserver domain. The target server also re-downloads the MSXOperator details.
SET-POLL | Server operation that sets the interval, in seconds, for target servers to poll the multiserver domain. If specified, value is interpreted as the required interval value, and can be a value from 10 to 28,800.
START | Job operation that requests the start of job execution.
STOP | Job operation that requests the stop of job execution.
SYNC-TIME | Server operation that causes the target server to synchronize its system clock with the multiserver domain. Because this is a costly operation, perform this operation on a limited, infrequent basis.
UPDATE | Job operation that updates only the sysjobs information for a job, not the job steps or schedules. Is automatically called by sp_update_job.

[@object_type =] 'object_type'
Is the type of object for the specified job. object_type is varchar(64), with a default of NULL. object_type can be either JOB or SERVER. For more information about valid object_type values, see sp_add_category.
[@object_name =] 'object_name'
Is the name of the object. object_name is varchar(100), with a default of NULL. If object_type is JOB, object_name is the job name. If object_type is SERVER, object_name is the server name.
[@target_server =] 'target_server'
Is the name of the target server. target_server is varchar(30), with a default of NULL.
[@has_error =] has_error
Is whether the job should acknowledge errors. has_error is tinyint, with a default of NULL, which indicates no errors should be acknowledged. 1 indicates that all errors should be acknowledged.
[@status =] status
Is the status for the job. status is tinyint, with a default value of NULL.
[@date_posted =] date_posted
Is the date and time for which all entries made on or after the specified date and time should be included in the result set. date_posted is datetime, with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Result Sets
Column name | Data type | Description
instance_id | int | Unique integer identification number of the instruction.
source_server | nvarchar(30) | Computer name of the server the instruction came from. In Microsoft® SQL Server™ 7.0, this is always the computer name of the master (MSX) server.
operation_code | nvarchar(4000) | Operation code for the instruction.
object_name | sysname | Object affected by the instruction.
object_id | uniqueidentifier | Identification number of the object affected by the instruction (job_id for a job object, or 0x00 for a server object) or a data value specific to the operation_code.
target_server | nvarchar(30) | Target server that this instruction is to be downloaded by.
error_message | nvarchar(1024) | Error message (if any) from the target server if it encountered a problem while processing this instruction. NOTE: Any error message blocks all further downloads by the target server.
date_posted | datetime | Date the instruction was posted to the table.
date_downloaded | datetime | Date the instruction was downloaded by the target server.
Status | tinyint | Status of the job: 0 = Not yet downloaded 1 = Successfully downloaded.

Permissions

Permissions to execute this procedure default to the sysadmin fixed server role or the db_owner fixed database role, who can grant permissions to other users.

Examples

This example lists rows in the sysdownloadlist for the Weekly Sales Data Backup job.

USE msdb

EXEC sp_help_downloadlist @job_name='Weekly Sales Data Backup',     @operation='UPDATE',
    @object_type='JOB',

    @object_name='Weekly Sales Backup',
    @target_server='SEATTLE2',
    @has_error=1,
    @status=NULL,
    @date_posted=NULL

See Also

System Stored Procedures


sp_helpextendedproc

Displays the currently defined extended stored procedures and the name of the dynamic-link library to which the procedure (function) belongs.

Syntax

sp_helpextendedproc [[@funcname =] 'procedure']

Arguments
[@funcname =] 'procedure'
Is the name of the extended stored procedure for which to display information. procedure is sysname, with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Result Sets
Column name | Data Type | Description
name | sysname | Name of the extended stored procedure
dll | nvarchar(255) | Name of the dynamic link library

Remarks

When procedure is specified, sp_helpextendedproc reports on the specified extended stored procedure. When not supplied, sp_helpextendedproc returns all extended stored procedure names and the DLL names to which each extended stored procedure belongs.

Permissions

Execute permissions default to the sysadmin fixed server role, and can be transferred.

Examples
A. Report help on all extended stored procedures

This example reports on all extended stored procedures.

USE master

EXEC sp_helpextendedproc

B. Report help on a single extended stored procedure

This example reports on the xp_cmdshell extended stored procedure.

USE master

EXEC sp_helpextendedproc xp_cmdshell

See Also
sp_addextendedproc | System Stored Procedures
sp_dropextendedproc |


sp_helpfile

Returns the physical names and attributes of files associated with the current database. Use this stored procedure to determine the names of files to attach to or detach from the server.

Syntax

sp_helpfile [[@filename =] 'name']

Arguments
[@filename =] 'name'

Is the logical name of any file in the current database. name is sysname, with a default of NULL. If name is not specified, the attributes of all files in the current database.

Return Code Values

0 (success) or 1 (failure)

Result Sets
Column name | Data type | Description
name | sysname | Logical file name.
fileid | smallint | Numeric identifier of the file.
filename | nchar(260) | Physical file name.
filegroup | sysname | Group to which the file belongs. Database files can be grouped in file groups for allocation and administration purposes. Log files are never a part of a file group.
size | nvarchar(18) | File size.
maxsize | nvarchar(18) | Maximum size to which the file can grow. UNLIMITED value in this field indicate that the file grows until the disk is full.
growth | nvarchar(18) | Growth increment of the file. This indicates the amount of space added to the file each time new space is needed.
usage | varchar(9) | Usage of the file. For a data file, the usage is data only and for the log file the usage is log only.

Permissions

Execute permission defaults to the public role.

Examples

This example returns information about the files in pubs.

USE pubs

EXEC sp_helpfile

See Also
sp_attach_db | sp_helpfilegroup
sp_attach_single_file_db | System Stored Procedures
sp_detach_db |


sp_helpfilegroup

Returns the names and attributes of filegroups associated with the current database.

Syntax

sp_helpfilegroup [[@filegroupname =] 'name]'

Arguments
[@filegroupname =] 'name'

Is the logical name of any filegroup in the current database. name is sysname, with a default of NULL. If name is not specified, the attributes of all filegroups in the current database are listed.

Return Code Values

0 (success) or 1 (failure)

Result Sets
Column name | Data type | Description
name | sysname | Name of the file group
groupid | smallint | Numeric group identifier
filecount | integer | Number of files in the file group

Permissions

Execute permission defaults to the public role.

Examples

This example returns information about the filegroups in pubs.

USE pubs

EXEC sp_helpfilegroup

See Also
sp_attach_db | sp_helpfile
sp_attach_single_file_db | System Stored Procedures
sp_detach_db |


sp_help_fulltext_catalogs

Returns the ID, name, root directory, status, and number of full-text indexed tables for the specified full-text catalog.

Syntax

sp_help_fulltext_catalogs [@fulltext_catalog_name =] 'fulltext_catalog_name'

Arguments
[@fulltext_catalog_name =] 'fulltext_catalog_name'
Is the name of the full-text catalog. fulltext_catalog_name is sysname. If this parameter is omitted or has the value NULL, information about all full-text catalogs associated with the current database is returned.
Return Code Values

0 (success) or (1) failure

Result Sets

This table shows the result set, which is ordered by ftcatid.

Column name | Data type | Description
ftcatid | smallint | Full-text catalog identifier.
NAME | sysname | Name of the full-text catalog.
PATH | nvarchar(260) | Physical location of the full-text catalog root directory. NULL indicates the default directory determined during installation. (This is the Ftdata subdirectory under the Microsoft® SQL Server™ directory; for example, C:\Mssql7\Ftdata.)
STATUS | integer | Full-text index population status of the catalog: 0 = Idle 1 = Full population in progress 2 = Paused 3 = Throttled 4 = Recovering 5 = Shutdown 6 = Incremental population in progress 7 = Updating index
NUMBER_ FULLTEXT_ TABLES | integer | Number of full-text indexed tables associated with the catalog.

Permissions

Execute permissions default to members of the public role.

Examples

This example returns information about the Cat_Desc full-text catalog.

USE Northwind

EXEC sp_help_fulltext_catalogs 'Cat_Desc'

See Also
FULLTEXTCATALOGPROPERTY | sp_help_fulltext_catalogs_cursor
sp_fulltext_catalog | System Stored Procedures


sp_help_fulltext_catalogs_cursor

Uses a cursor to return the ID, name, root directory, status, and number of full-text indexed tables for the specified full-text catalog.

Syntax

sp_help_fulltext_catalogs [@cursor_return =] @cursor_variable OUTPUT,
[@fulltext_catalog_name =] 'fulltext_catalog_name'

Arguments
[@cursor_return =] @cursor_variable OUTPUT
Is the output variable of type cursor. The cursor is a read-only, scrollable, dynamic cursor.
[@fulltext_catalog_name =] 'fulltext_catalog_name'
Is the name of the full-text catalog. fulltext_catalog_name is sysname. If this parameter is omitted or is NULL, information about all full-text catalogs associated with the current database is returned.
Return Code Values

0 (success) or (1) failure

Result Sets
Column name | Data type | Description
ftcatid | smallint | Full-text catalog identifier.
NAME | sysname | Name of the full-text catalog.
PATH | nvarchar(260) | Physical location of the full-text catalog root directory. NULL indicates the default directory determined during installation. (This is the Ftdata subdirectory under the Microsoft® SQL Server™ directory; for example, C:\Mssql7\Ftdata.)
STATUS | integer | Full-text index population status of the catalog: 0 = Idle 1 = Full population in progress 2 = Paused 3 = Throttled 4 = Recovering 5 = Shutdown 6 = Incremental population in progress 7 = Updating index
NUMBER_ FULLTEXT_ TABLES | integer | Number of full-text indexed tables associated with the catalog.

Permissions

Execute permissions default to the public role.

Examples

This example returns information about the Cat_Desc full-text catalog.

USE Northwind

GO

DECLARE @mycursor CURSOR

EXEC sp_help_fulltext_catalogs_cursor @mycursor OUTPUT, 'Cat_Desc'

FETCH NEXT FROM @mycursor

WHILE (@@FETCH_STATUS <> -1)

   BEGIN

      FETCH NEXT FROM @mycursor

   END

CLOSE @mycursor

DEALLOCATE @mycursor

GO

See Also
FULLTEXTCATALOGPROPERTY | sp_help_fulltext_catalogs
sp_fulltext_catalog | System Stored Procedures


sp_help_fulltext_tables

Returns a list of tables that are registered for full-text indexing.

Syntax

sp_help_fulltext_tables [[@fulltext_catalog_name =] 'fulltext_catalog_name'],
[[@table_name =] 'table_name']

Arguments
[@fulltext_catalog_name =] 'fulltext_catalog_name'
Is the name of the full-text catalog. fulltext_catalog_name is sysname, with a default of NULL. If fulltext_catalog_name is omitted or is NULL, all full-text indexed tables associated with the database are returned. If fulltext_catalog_name is specified, but table_name is omitted or is NULL, the full-text index information is retrieved for every full-text indexed table associated with this catalog. If both fulltext_catalog_name and table_name are specified, a row is returned if table_name is associated with fulltext_catalog_name; otherwise, an error is raised.
[@table_name =] 'table_name'
Is the one- or two-part table name for which the full-text metadata is requested. table_name is nvarchar(517), with a default value of NULL. If only table_name is specified, only the row relevant to table_name is returned.
Return Code Values

0 (success) or (1) failure

Result Sets
Column name | Data type | Description
TABLE_OWNER | sysname | Table owner. This is the name of the database user that created the table.
TABLE_NAME | sysname | Table name.
FULLTEXT_KEY_ INDEX_NAME | sysname | Index imposing the UNIQUE constraint on the column designated as the unique key column.
FULLTEXT_KEY_ COLID | integer | Column ID of the unique index identified by FULLTEXT_KEY_NAME.
FULLTEXT_INDEX_ ACTIVE | integer | Specifies whether columns marked for full-text indexing in this table are eligible for queries: 0 = Inactive 1 = Active
FULLTEXT_ CATALOG_NAME | sysname | Full-text catalog in which the full-text index data resides.

Permissions

Execute permissions default to members of the public role.

Examples

This example returns the names of the full-text indexed tables associated with the Cat_Desc full-text catalog.

USE Northwind

EXEC sp_help_fulltext_tables 'Cat_Desc'

See Also
INDEXPROPERTY | sp_help_fulltext_tables_cursor
OBJECTPROPERTY | System Stored Procedures
sp_fulltext_table |


sp_help_fulltext_tables_cursor

Uses a cursor to return a list of tables that are registered for full-text indexing.

Syntax

sp_help_fulltext_tables_cursor [@cursor_return =] @cursor_variable
OUTPUT,
[[@fulltext_catalog_name =] 'fulltext_catalog_name'],
[[@table_name =] 'table_name']

Arguments
[@cursor_return =] @cursor_variable OUTPUT
Is the output variable of type cursor. The cursor is a read-only, scrollable, dynamic cursor.
[@fulltext_catalog_name =] 'fulltext_catalog_name'
Is the name of the full-text catalog. fulltext_catalog_name is sysname, with a default of NULL. If fulltext_catalog_name is omitted or is NULL, all full-text indexed tables associated with the database are returned. If fulltext_catalog_name is specified, but table_name is omitted or is NULL, the full-text index information is retrieved for every full-text indexed table associated with this catalog. If both fulltext_catalog_name and table_name are specified, a row is returned if table_name is associated with fulltext_catalog_name; otherwise, an error is raised.
[@table_name =] 'table_name'
Is the one- or two-part table name for which the full-text metadata is requested. table_name is nvarchar(517), with a default value of NULL. If only table_name is specified, only the row relevant to table_name is returned.
Return Code Values

0 (success) or (1) failure

Result Sets
Column name | Data type | Description
TABLE_OWNER | sysname | Table owner. This is the name of the database user that created the table.
TABLE_NAME | sysname | Table name.
FULLTEXT_KEY_ INDEX_NAME | sysname | Index imposing the UNIQUE constraint on the column designated as the unique key column.
FULLTEXT_KEY_ COLID | integer | Column ID of the unique index identified by FULLTEXT_KEY_NAME.
FULLTEXT_INDEX_ ACTIVE | integer | Specifies whether columns marked for full-text indexing in this table are eligible for queries: 0 = Inactive 1 = Active
FULLTEXT_ CATALOG_NAME | sysname | Full-text catalog in which the full-text index data resides.

Permissions

Execute permissions default to members of the public role.

Examples

This example returns the names of the full-text indexed tables associated with the Cat_Desc full-text catalog.

USE Northwind

GO

DECLARE @mycursor CURSOR

EXEC sp_help_fulltext_tables_cursor @mycursor OUTPUT, 'Cat_Desc'

FETCH NEXT FROM @mycursor

WHILE (@@FETCH_STATUS <> -1)

   BEGIN

      FETCH NEXT FROM @mycursor

   END

CLOSE @mycursor

DEALLOCATE @mycursor

GO

See Also
INDEXPROPERTY | sp_help_fulltext_tables
OBJECTPROPERTY | System Stored Procedures
sp_fulltext_table |


sp_help_fulltext_columns

Returns the columns that have been designated for full-text indexing.

Syntax

sp_help_fulltext_columns [[@table_name =] 'table_name'],
[[@column_name =] 'column_name']

Arguments
[@table_name =] 'table_name'
Is the one- or two-part table name for which full-text index information is requested. table_name is nvarchar(517), with a default value of NULL. If table_name is omitted, full-text index column information is retrieved for every full-text indexed table.
[@column_name =] 'column_name'
Is the name of the column for which full-text index metadata is requested. column_name is sysname, with a default value of NULL. If column_name is omitted or is NULL, full-text column information is returned for every full-text indexed column for table_name. If table_name is also omitted or is NULL, full-text index column information is returned for every full-text indexed column for all tables in the database.
Return Code Values

0 (success) or (1) failure

Result Sets
Column name | Data type | Description
TABLE_OWNER | sysname | Table owner. This is the name of the database user that created the table.
TABLE_NAME | sysname | Name of the table.
FULLTEXT_COLID | integer | Column ID of the full-text indexed column.
FULLTEXT_ COLUMN_NAME | sysname | Column in a full-text indexed table that is designated for indexing.

Permissions

Execute permissions default to members of the public role.

Examples

This example returns information about the columns that have been designated for full-text indexing in the Categories table.

USE Northwind

EXEC sp_help_fulltext_columns Categories

Here is the result set:

TABLE_OWNER     TABLE_NAME    FULLTEXT_COLID  FULLTEXT_COLUMN_NAME

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

dbo             Categories    3               Description

See Also
COLUMNPROPERTY | sp_help_fulltext_columns_cursor
sp_fulltext_column | System Stored Procedures


sp_help_fulltext_columns_cursor

Uses a cursor to return the columns that have been designated for full-text indexing.

Syntax

sp_help_fulltext_columns_cursor [@cursor_return =] @cursor_variable
OUTPUT,
[[@table_name =] 'table_name'],
[[@column_name =] 'column_name']

Arguments
[@cursor_return =] @cursor_variable OUTPUT
Is the output variable of type cursor. The resulting cursor is a read-only, scrollable, dynamic cursor.
[@table_name =] 'table_name'
Is the one- or two-part table name for which full-text index information is requested. table_name is nvarchar(517), with a default value of NULL. If table_name is omitted, full-text index column information is retrieved for every full-text indexed table.
[@column_name =] 'column_name'
Is the name of the column for which full-text index metadata is desired. column_name is sysname with a default value of NULL. If column_name is omitted or is NULL, full-text column information is returned for every full-text indexed column for table_name. If table_name is also omitted or is NULL, full-text index column information is returned for every full-text indexed column for all tables in the database.
Return Code Values

0 (success) or (1) failure

Result Sets
Column name | Data type | Description
TABLE_OWNER | sysname | Table owner. This is the name of the database user that created the table.
TABLE_NAME | sysname | Table name.
FULLTEXT_COLID | integer | Column ID of the full-text indexed column.
FULLTEXT_ COLUMN_NAME | sysname | Column in a full-text indexed table that is designated for indexing.

Permissions

Execute permissions default to members of the public role.

Examples

This example returns information about the columns that have been designated for full-text indexing in all of the tables in the database.

USE Northwind

GO

DECLARE @mycursor CURSOR

EXEC sp_help_fulltext_columns_cursor @mycursor OUTPUT

FETCH NEXT FROM @mycursor

WHILE (@@FETCH_STATUS <> -1)

   BEGIN

      FETCH NEXT FROM @mycursor

   END

CLOSE @mycursor

DEALLOCATE @mycursor

GO

See Also
COLUMNPROPERTY | sp_help_fulltext_columns
sp_fulltext_column | System Stored Procedures


sp_helpgroup

Reports information about a role or all roles in the current database. This procedure is included for backward compatibility. Microsoft® SQL Server™ version 7.0 uses roles instead of groups. Use sp_helprole.

Syntax

sp_helpgroup [[@grpname =] 'role']

Arguments
[@grpname =] 'role'
Is the name of a role. role must exist in the current database. role is sysname, with a default of NULL. If role is specified, information about the name of the role and the members of the role is returned; otherwise, information about all the roles in the current database is returned.
Return Code Values

0 (success) or 1 (failure)

Result Sets

role is not specified.

Column name | Data type | Description
Group_name | sysname | Name of the role in the current database
Group_id | smallint | Role ID for the role in the current database

role is specified.

Column name | Data type | Description
Group_name | sysname | Name of the role in the current database
Group_id | smallint | Role ID for the role in the current database
Users_in_group | sysname | Member of the role in the current database
Userid | smallint | User ID for the member of the role

Remarks

To view the permissions associated with the role, use sp_helprotect.

Permissions

Execute permissions default to the public role.

Examples
A. Return information about a single role

This example returns information about the hackers role.

EXEC sp_helpgroup 'hackers'

B. Return information about all roles

This example returns information about all roles in the current database.

EXEC sp_helpgroup

See Also
sp_helprotect | sp_helpuser
sp_helprole | System Stored Procedures


sp_helphistory

sp_helphistory is provided for backward compatibility.

Remarks

The results of sp_helphistory are determined by a match on all specified parameters.

Permissions

Execute permissions default to the public role. Anyone who can execute this procedure can also create, delete, or update a job, job step, job category, job schedule, job server, task, or job history information.

See Also
sp_addtask | System Stored Procedures
sp_purgehistory |


sp_help_job

Returns information about jobs that are used by SQL Server Agent to perform automated activities in Microsoft® SQL Server™.

Syntax

sp_help_job [[@job_id =] job_id]
[,[@job_name =] 'job_name']
[,[@job_aspect =] 'job_aspect']
[,[@job_type =] 'job_type']
[,[@owner_login_name =] 'login_name']
[,[@subsystem =] 'subsystem']
[,[@category_name =] 'category']
[,[@enabled =] enabled]
[,[@execution_status =] status]
[,[@date_comparator =] 'date_comparison']
[,[@date_created =] date_created]
[,[@date_last_modified =] date_modified]
[,[@description =] 'description_pattern']

Arguments
[@job_id =] job_id
Is the job identification number. job_id is uniqueidentifier, with a default of NULL.
[@job_name =] 'job_name'
Is the name of the job. job_name is varchar(100), with a default of NULL.

Note Either job_id or job_name must be specified, but both cannot be specified.

[@job_aspect =] 'job_aspect'
Is the job attribute to display. job_aspect is varchar(9), with a default of NULL, and can be one of these values.

Value | Description
ALL | Job aspect information
JOB | Job information
SCHEDULES | Scheduleinformation
STEPS | Job step information
TARGETS | Target information

[@job_type =] 'job_type'
Is the type of jobs to include in the report. job_type is varchar(12), with a default of NULL. job_type can be LOCAL or MULTI-SERVER.
[@owner_login_name =] 'login_name'
Is the login name of the owner of the job. login_name is varchar(64), with a default of NULL.
[@subsystem =] 'subsystem'
Is the name of the subsystem. subsystem is varchar(60), with a default of NULL.
[@category_name =] 'category'
Is the name of the category. category is varchar(100), with a default of NULL.
[@enabled =] enabled
Is a number indicating whether information is shown for enabled jobs or disabled jobs. enabled is tinyint, with a default of NULL. 1 indicates enabled jobs, and 0 indicates disabled jobs.
[@execution_status =] status
Is the execution status for the jobs. status is int, with a default of NULL, and can be one of these values.

Value | Description
0 | Returns only those jobs that are not idle or suspended.
1 | Executing.
2 | Waiting for thread.
3 | Between retries.
4 | Idle.
5 | Suspended.
7 | Performing completion actions.

[@date_comparator =] 'date_comparison'
Is the comparison operator to use in comparisons of date_created and date_modified. date_comparison is char(1), and can be =, <, or >.
[@date_created =] date_created
Is the date the job was created. date_created is datetime, with a default of NULL.
[@date_last_modified =] date_modified
Is the date the job was last modified. date_modified is datetime, with a default of NULL.
[@description =] 'description_pattern'
Is the description of the job. description_pattern is varchar(512), with a default of NULL. description_pattern can include the SQL Server wildcard characters for pattern matching.
Return Code Values

0 (success) or 1 (failure)

Result Sets

If no arguments are specified, sp_help_job returns this result set.

Column name | Data type | Description
job_id | uniqueidentifier | Unique ID of the job.
originating_server | nvarchar(30) | Name of the server from which the job came.
name | sysname | Name of the job.
enabled | tinyint | Indicates whether the job is enabled to be executed.
description | nvarchar(512) | Description for the job.
start_step_id | int | ID of the step in the job where execution should begin.
category | sysname | Job category.
owner | sysname | Job owner.
notify_level_ eventlog | int | Bitmask indicating under what circumstances a notification event should be logged to the Microsoft Windows NT® application log. Can be one of these values: 0 = Never 1 = When a succeeds 2 = When the job fails 3 = Whenever the job completes (regardless of the job outcome)
notify_level_email | int | Bitmask indicating under what circumstances a notification e-mail should be sent when a job completes. Possible values are the same as for notify_level_eventlog.
notify_level_netsend | int | Bitmask indicating under what circumstances a network message should be sent when a job completes. Possible values are the same as for notify_level_eventlog.
notify_level_page | int | Bitmask indicating under what circumstances a page should be sent when a job completes. Possible values are the same as for notify_level_eventlog.
notify_email_ operator | sysname | E-mail name of the operator to notify.
notify_netsend_ operator | sysname | Name of the computer or user used when sending network messages.
notify_page_ operator | sysname | Name of the computer or user used when sending a page.
delete_level | int | Bitmask indicating under what circumstances the job should be deleted when a job completes. Possible values are the same as for notify_level_eventlog.
date_created | datetime | Date the job was created.
date_modified | datetime | Date the job was last modified.
version_number | int | Version of the job (automatically updated each time the job is modified).
last_run_date | int | Date the job last started execution.
last_run_time | int | Time the job last started execution.
last_run_outcome | int | Outcome of the job the last time it ran: 0 = Failed 1 = Succeeded 3 = Canceled 5 = Unknown
next_run_date | int | Date the job is scheduled to run next.
next_run_time | int | Time the job is scheduled to run next.
next_run_schedule_id | int | Identification number of the next run schedule.
current_execution_ status | int | Current execution status.
current_execution_step | sysname | Current execution step in the job.
current_retry_ attempt | int | If the job is running and the step has been retried, this is the current retry attempt.
has_step | int | Number of job steps the job has.
has_schedule | int | Number of job schedules the job has.
has_target | int | Number of target servers the job has.
Type | int | 1 = Local job. 2 = Multiserver job. 0 = Job has no target servers.

If job_id or job_name is specified, sp_help_job returns these additional result sets for job steps, job schedules, and job target servers.

This is the result set for job steps.

Column name | Data type | Description
step_id | int | Unique (for this job) identifier for the step.
step_name | sysname | Name of the step.
Subsystem | nvarchar(40) | Subsystem in which to execute the step command.
Command | nvarchar(3200) | Command to execute.
Flags | nvarchar(4000) | Bitmask of values that control step behavior.
cmdexec_success_code | int | For a CmdExec step, this is the process exit code of a successful command.
on_success_action | nvarchar(4000) | What to do if the step succeeds: 1 = Quit with success. 2 = Quit with failure. 3 = Go to next step. 4 = Go to step.
on_success_step_id | int | If on_success_action is 4, this indicates the next step to execute.
on_fail_action | nvarchar(4000) | Action to take if the step fails. Values are the same as for on_success_action.
on_fail_step_id | int | If on_fail_action is 4, this indicates the next step to execute.
Server | sysname | Reserved.
database_name | sysname | For a Transact=SQL step, this is the database in which the command will executes.
database_user_name | sysname | For a Transact=SQL step, this is the database user context in which the command executes.
retry_attempts | int | Maximum number of times the command should be retried (if it is unsuccessful) before the step is deemed to have failed.
retry_interval | int | Interval (in minutes) between any retry attempts.
os_run_priority | varchar(4000) | Reserved.
output_file_name | varchar(200) | File to which command output should be written (Transact=SQL and CmdExec steps only).
last_run_outcome | int | Outcome of the step the last time it ran: 0 = Failed 1 = Succeeded 3 = Canceled 5 = Unknown
last_run_duration | int | Duration (in seconds) of the step the last time it ran.
last_run_retries | int | Number of times the command was retried the last time the step ran.
last_run_date | int | Date the step last started execution.
last_run_time | int | Time the step last started execution.

This is the result set for job schedules.

Column name | Data type | Description
schedule_id | int | Identifier of the schedule (unique across all jobs).
schedule_name | sysname | Name of the schedule (unique for this job only).
Enabled | int | Whether the schedule is active (1) or not (0).
freq_type | int | Value indicating when the job is to be executed: 1 = Once 4 = Daily 8 = Weekly 16 = Monthly 32 = Monthly, relative to the freq_interval 64 = Run when SQL Server Agent starts.
freq_interval | int | Days when the job is executed. The value depends on the value of freq_type. For more information, see sp_add_jobschedule.
freq_subday_type | int | Units for freq_subday_interval. For more information, see sp_add_jobschedule.
freq_subday_interval | int | Number of freq_subday_type periods to occur between each execution of the job. For more information, see sp_add_jobschedule.
freq_relative_interval | int | Scheduled job’s occurrence of the freq_interval in each month. For more information, see sp_add_jobschedule.
freq_recurrence_factor | int | Number of months between the scheduled execution of the job.
active_start_date | int | Date to begin execution of the job.
active_end_date | int | Date to end execution of the job.
active_start_time | int | Time to begin the execution of the job on active_start_date.
active_end_time | int | Time to end execution of the job on active_end_date.
date_created | datetime | Date the schedule is created.
schedule_description | nvarchar(4000) | An English description of the schedule (if requested).
next_run_date | int | Date the schedule will next cause the job to run.
next_run_time | int | Time the schedule will next cause the job to run.

This is the result set for job target servers.

Column name | Data type | Description
server_id | int | Identifier of the target server.
server_name | nvarchar(30) | Computer name of the target server.
enlist_date | datetime | Date the target server enlisted into the master server (MSX).
last_poll_date | datetime | Date the target server last polled the MSX.
last_run_date | int | Date the job last started execution on this target server.
last_run_time | int | Time the job last started execution on this target server.
last_run_duration | int | Duration of the job the last time it ran on this target server.
last_run_outcome | tinyint | Outcome of the job the last time it ran on this server: 0 = Failed 1 = Succeeded 3 = Canceled 5 = Unknown
last_outcome_message | nvarchar(1024) | Outcome message from the job the last time it ran on this target server.

Permissions

Execute permissions default to the public role. Anyone who can execute this procedure can also create, delete, or update a job, job step, job category, job schedule, job server, task, or job history information.

Examples
A. List information for all jobs

    This example executes the sp_help_job procedure with no parameters to return the information for all of the jobs currently defined in the msdb database.

    USE msdb

    EXEC sp_help_job

    B. List information for a specific job

    This example lists all job aspect information for the multiserver job named Archive Tables, in which the job is enabled and has been modified since its creation.

    USE msdb

    EXEC sp_help_job 'Archive Tables', 'ALL', 'MULTI-SERVER', 'janetl',

        NULL, NULL, 1, 1, '<', '12/01/97', '6/25/98', NULL

    See Also
    sp_add_job | sp_update_job
sp_delete_job | System Stored Procedures


sp_help_jobhistory

Provides information about the jobs for servers in the multiserver administration domain.

Syntax

sp_help_jobhistory [[@job_id =] job_id]
[, [@job_name =] 'job_name']
[, [@step_id =] step_id]
[, [@sql_message_id =] sql_message_id]
[, [@sql_severity =] sql_severity]
[, [@start_run_date =] start_run_date]
[, [@end_run_date =] end_run_date]
[, [@start_run_time =] start_run_time]
[, [@end_run_time =] end_run_time]
[, [@minimum_run_duration =] minimum_run_duration]
[, [@run_status =] run_status]
[, [@minimum_retries =] minimum_retries]
[, [@oldest_first =] oldest_first]
[, [@server =] 'server']
[, [@mode =] 'mode']

Arguments
[@job_id =] job_id
Is the job identification number. job_id is uniqueidentifier, with a default of NULL.
[@job_name =] 'job_name'
Is the name of the job. job_name is varchar(100), with a default of NULL.
[@step_id =] step_id
Is the step identification number. step_id is int, with a default of NULL.
[@sql_message_id =] sql_message_id
Is the identification number of the error message returned by Microsoft® SQL Server™ when executing the job. sql_message_id is int, with a default of NULL.
[@sql_severity =] sql_severity
Is the severity level of the error message returned by SQL Server when executing the job. sql_severity is int, with a default of NULL.
[@start_run_date =] start_run_date
Is the date the job was started. start_run_date is int, with a default of NULL. start_run_date must be entered in the form YYYYMMDD, where YYYY is a four-character year, MM is a two-character month name, and DD is a two-character day name.
[@end_run_date =] end_run_date
Is the date the job was completed. end_run_date is int, with a default of NULL. end_run_date must be entered in the form YYYYMMDD, where YYYY is a four-character year, MM is a two-character month name, and DD is a two-character day name.
[@start_run_time =] start_run_time
Is the time the job was started. start_run_time is int, with a default of NULL. start_run_time must be entered in the form HHMMSS, where HH is a two-character hour of the day, MM is a two-character minute of the day, and SS is a two-character second of the day.
[@end_run_time =] end_run_time
Is the time the job completed its execution. end_run_time is int, with a default of NULL. end_run_time must be entered in the form HHMMSS, where HH is a two-character hour of the day, MM is a two-character minute of the day, and SS is a two-character second of the day.
[@minimum_run_duration =] minimum_run_duration
Is the minimum length of time for the completion of the job. minimum_run_duration is int, with a default of NULL. minimum_run_duration must be entered in the form HHMMSS, where HH is a two-character hour of the day, MM is a two-character minute of the day, and SS is a two-character second of the day.
[@run_status =] run_status
Is the execution status of the job. run_status is int, with a default of NULL, and can be one of these values.

Value | Description
0 | Failed
1 | Succeeded
2 | Retry (step only)
3 | Canceled
4 | In-progress message
5 | Unknown

[@minimum_retries =] minimum_retries
Is the minimum number of times a job should retry running. minimum_retries is int, with a default of NULL.
[@oldest_first =] oldest_first
Is whether to present the output with the oldest jobs first. oldest_first is int, with a default of 0, which presents the newest jobs first. 1 presents the oldest jobs first.
[@server =] 'server'
Is the name of the server on which the job was performed. server is varchar(30), with a default of NULL.
[@mode =] 'mode'
Is whether SQL Server prints all columns in the result set (FULL) or a summary of the columns. mode is varchar(7), with a default of SUMMARY.
Return Code Values

0 (success) or 1 (failure)

Result Sets

The actual column list depends on the value of mode. The most comprehensive set of columns is shown below and is returned when mode is FULL.

Column name | Data type | Description
instance_id | int | History entry identification number.
job_id | uniqueidentifier | Job identification number.
job_name | sysname | Job name.
step_id | int | Step identification number (will be 0 for a job history).
step_name | sysname | Step name (will be NULL for a job history).
sql_message_id | int | For Transact-SQL step, the most recent Transact-SQL error number encountered while running the command.
sql_severity | int | For a Transact-SQL step, the highest Transact-SQL error severity encountered while running the command.
message | nvarchar(1024) | Job or step history message.
run_status | int | Outcome of the job or step.
run_date | int | Date the job or step began executing.
run_time | int | Time the job or step began executing.
run_duration | int | Amount of time (in seconds) the job or step took to run to completion.
operator_emailed | nvarchar(20) | Operator who was e-mailed regarding this job (is NULL for step history).
operator_netsent | nvarchar(20) | Operator who was sent a network message regarding this job (is NULL for step history).
operator_paged | nvarchar(20) | Operator who was paged regarding this job (is NULL for step history).
retries_attempted | int | Number of times the step was retried (always 0 for a job history).
server | nvarchar(30) | Server the step or job executes on. Is always (local).

Remarks

sp_help_jobhistory returns a report with the history of the specified scheduled jobs. If no parameters are specified, the report contains the history for all scheduled jobs.

Permissions

Permissions to execute this procedure default to the sysadmin fixed server role or the db-owner fixed database role, who can grant permissions to other users.

Example

This example prints all columns and all job information for any failed jobs and failed job steps with an error message of 50100 (a user-defined error message), a severity of 20, and a start date of June 1, 1998, on the LONDON2 server.

USE msdb

EXEC sp_help_jobhistory NULL, NULL, NULL, 50100, 20, 19980601, NULL,

    NULL, NULL, NULL, 0, NULL, 1, 'LONDON2', FULL

See Also
sp_purge_jobhistory System Stored Procedures


sp_help_jobschedule

Returns information about the scheduling of jobs used by SQL Server Enterprise Manager to perform automated activities.

Syntax

sp_help_jobschedule
[@job_id =] job_id |
[@job_name =] 'job_name'
[,[@schedule_name =] 'schedule_name'] |
[,[@schedule_id =] schedule_id]

Arguments
[@job_id =] job_id
Is the job identification number. job_id is uniqueidentifier, with a default of NULL.
[@job_name =] 'job_name'
Is the name of the job. job_name is varchar(100), with a default of NULL.

Note Either job_id or job_name must be specified, but both cannot be specified.

[@schedule_name =] 'schedule_name'
Is the name of the schedule item for the job. schedule_name is varchar(100), with a default of NULL.
{[@schedule_id =] schedule_id
Is the identification number of the schedule item for the job. schedule_id is int, with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Result Sets
Column name | Data type | Description
schedule_id | int | Schedule identifier number.
schedule_name | sysname | Name of the schedule.
enabled | int | Whether the schedule enabled (1) or not enabled (0).
freq_type | int | Value indicating when the job is to be executed. 1 = Once 4 = Daily 8 = Weekly 16 = Monthly 32 = Monthly, relative to the freq_ interval 64 = Run when SQL Server Agent starts.
freq_interval | int | Days when the job is executed. The value depends on the value of freq_type. For more information, see sp_add_jobschedule.
freq_subday_type | int | Units for freq_subday_interval. For more information, see sp_add_jobschedule.
freq_subday_interval | int | Number of freq_subday_type periods to occur between each execution of the job. For more information, see sp_add_jobschedule.
freq_relative_interval | int | Scheduled job’s occurrence of the freq_interval in each month. For more information, see sp_add_jobschedule.
freq_recurrence_factor | int | Number of months between the scheduled execution of the job.
active_start_date | int | Date the schedule is activated.
active_end_date | int | End date of the schedule.
active_start_time | int | Time of the day the schedule starts.
active_end_time | int | Time of the day schedule ends.
date_created | datetime | Date the schedule is created.
schedule_description | nvarchar(4000) | An English description of the schedule (if scheduled).
next_run_date | int | Date the schedule will next cause the job to run.
next_run_time | int | Time the schedule will next cause the job to run.

Remarks

The parameters of sp_help_jobschedule can be used only in certain combinations. If schedule_id is specified, neither job_id nor job_name can be specified. Otherwise, the job_id or job_name parameters can be used with schedule_name.

Permissions

Execute permissions default to the public role. Anyone who can execute this procedure can also create, delete, or update a job, job step, job category, job schedule, job server, task, or job history information.

Examples
A. Return the job schedule for a specific job

This example returns the scheduling information for a job named Archive Tables.

USE msdb

EXEC sp_help_jobhistory @job_name = 'Archive Tables'

B. Return the job schedule for a named item in the schedule

This example returns the history for a job named Archive Tables and for its schedule item Weekly Archive.

USE msdb

EXEC sp_help_jobhistory @job_name = 'Archive Tables',

    @schedule_name = 'Weekly Archive'

See Also
sp_add_jobschedule | sp_update_jobschedule
sp_delete_jobschedule | System Stored Procedures


sp_help_jobserver

Returns information about the server for a given job.

Syntax

sp_help_jobserver [@job_id =] job_id |
[@job_name =] 'job_name'
[,[@show_last_run_details =] show_last_run_details]

Arguments
[@job_id =] job_id
Is the job identification number for which to return information. job_id is uniqueidentifier, with a default of NULL.
[@show_last_run_detail =] 'job_name'
Is the job name for which to return information. job_name is varchar(100), with a default of NULL.

Note Either job_id or job_name must be specified, but both cannot be specified.

[@show_last_run_details =] show_last_run_details
Is whether the last-run execution information is part of the result set. show_last_run_details is tinyint, with a default of 0. 0 does not include last-run information, and 1 does.
Return Code Values

0 (success) or 1 (failure)

Result Sets
Column name | Data type | Description
server_id | int | Identification number of the target server.
server_name | nvarchar(30) | Computer name of the target server.
enlist_date | datetime | Date the target server enlisted into the master server (MSX).
last_poll_date | datetime | Date the target server last polled the MSX.

If sp_help_jobserver is executed with show_last_run_details set to 1, the result set has these additional columns.

Column name | Data type | Description
last_run_date | int | Date the job last started execution on this target server
last_run_time | int | Time the job last started execution on this server
last_run_duration | int | Duration of the job the last time it ran on this target server (in seconds)
last_outcome_message | nvarchar(1024) | Outcome of the job the last time it ran on this server: 0 = Failed 1 = Succeeded 3 = Canceled 5 = Unknown.

Permissions

Permissions to execute this procedure default to the sysadmin fixed server role or the db_owner fixed data base role, who can grant permissions to other users.

Examples

This example returns information, including last-run information, about the Archive Tables job.

USE msdb

EXEC sp_help_jobserver 'Archive Tables', 1

See Also
sp_add_jobserver | System Stored Procedures
sp_delete_jobserver |


sp_help_jobstep

Returns information for the steps in a job used by SQL Server Agent to perform automated activities.

Syntax

sp_help_jobstep [@job_id =] 'job_id' |
[@job_name =] 'job_name'
[,[@step_id =] step_id]
[,[@step_name =] 'step_name']
[,[@suffix =] suffix]

Arguments
[@job_id =] 'job_id'
Is the job identification number for which to return job information. job_id is uniqueidentifier, with a default of NULL.
[@job_name =] 'job_name'
Is the name of the job. job_name is sysname, with a default NULL.
Is the name of the job. job_name is sysname, with a default of NULL

Note Either job_id or job_name must be specified, but both cannot be specified.

[@step_id =] step_id
Is the identification number of the step in the job. If not included, all steps in the job are included. step_id is int, with a default of NULL.
[@step_name =] 'step_name'
Is the name of the step in the job. step_name is sysname, with a default of NULL.
[@suffix =] suffix
Is a flag indicating whether a text description is appended to the flags column in the output. suffix is bit, with the default of 0. If suffix is 1, a description is appended.
Return Code Values

0 (success) or 1 (failure)

Result Sets
Column name | Data type | Description
step_id | int | Unique identifier for the step.
step_name | sysname | Name of the step in the job.
subsystem | nvarchar(40) | Subsystem in which to execute the step command.
command | nvarchar(3200) | Command executed in the step.
flags | int | A bitmask of values that control step behavior.
cmdexec_success_code | int | For a CmdExec step, this is the process exit code of a successful command.
on_success_action | timyint | Action to take if the step succeeds: 1 = Quit the job reporting success. 2 = Quit the job reporting failure. 3 = Go to the next step. 4 = Go to step.
on_success_step_id | int | If on_success_action is 4, this indicates the next step to execute.
on_fail_action | tinyint | What to do if the step fails. Values are same as on_success_action.
on_fail_step_id | int | If on_fail_action is 4, this indicates the next step to execute.
server | sysname | Reserved.
database_name | sysname | For a Transact-SQL step, this is the database in which the command executes.
database_user_name | sysname | For a Transact-SQL step, this is the database user context in which the command executes.
retry_attempts | int | Maximum number of times the command should be retried (if it is unsuccessful).
retry_interval | int | Interval (in minutes) for any retry attempts.
os_run_priority | int | Reserved.
output_file_name | nvarchar(200) | File to which command output should be written (Transact-SQL and CmdExec steps only).
last_run_outcome | int | Outcome of the step the last time it ran: 0 = Failed 1 = Succeeded 2 = Retry 3 = Canceled 5 = Unknown
last_run_duration | int | Duration (in seconds) of the step the last time it ran.
last_run_retries | int | Number of times the command was retried the last time the step ran.
last_run_date | int | Date the step last started execution.
last_run_time | int | Time the step last started execution.

Permissions

Execute permissions default to the public role. Anyone who can execute this procedure can also create, delete, or update a job, job step, job category, job schedule, job server, task, or job history information.

Examples
A. Return information for all steps in a specific job

This example returns all the job steps for a job named Backup Files.

USE msdb

EXEC sp_help_jobstep @job_name = 'Backup Files'

B. Return information about a specific job step

This example returns information about the first job step for the job named Backup Files.

USE msdb

EXEC sp_help_jobstep job_name = 'Backup Files', @step_id = 1

See Also
sp_add_jobstep | sp_update_jobstep
sp_delete_jobstep | System Stored Procedures
sp_help_job |


sp_helpindex

Reports information about the indexes on a table.

Syntax

sp_helpindex [@objname =] 'name'

Arguments
[@objname =] 'name'
Is the name of a table in the current database. name is nvarchar(776), with no default.
Return Code Values

0 (success) or 1 (failure)

Result Sets
Column name | Data type | Description
index_name | sysname | Index name
index_description | varchar(210) | Index description
index_keys | nvarchar(2078) | Table column(s) upon which the index is built

Remarks

If indexes have been set with the NORECOMPUTE option of UPDATE STATISTICS, that information is shown in the result set of sp_helpindex.

Permissions

Execute permissions default to the public role.

Examples

This example reports on the types of indexes on the sysobjects table.

sp_helpindex sysobjects

See Also
CREATE INDEX | UPDATE STATISTICS
DROP INDEX | DROP STATISTICS
sp_help | System Stored Procedures
sp_statistics |


sp_helplanguage

Reports information about a particular alternate language or about all languages.

Syntax

sp_helplanguage [[@language=]'language']

Arguments
[@language =] 'language'

Is the name of the alternate language for which to display information. language is sysname, with a default of NULL. If language is specified, information about the specified language is returned. If language is not specified, information about all languages in the syslanguages system table is returned.

Return Code Values

0 (success) or 1 (failure)

Result Sets
Column name | Data type | Description
langid | smallint | Language identification number.
dateformat | nchar(3) | Format of the date
datefirst | tinyint | First day of the week: 1 for Monday, 2 for Tuesday, and so on through 7 for Sunday.
upgrade | int | Microsoft® SQL Server™ version of the last upgrade for this language
name | sysname | Language name
alias | sysname | Alternate name of the language
months | nvarchar(372) | Month names
shortmonths | nvarchar(132) | Short month names
days | nvarchar(217) | Day names.
lcid | int | Microsoft Windows NT® locale ID for the language.
msglangid | smallint | SQL Server message group ID.

Permissions

Execute permissions default to the public role.

Examples
A. Return information about a single language

This example displays information about the alternate language French.

sp_helplanguage french

B. Return information about all languages

This example displays information about all installed alternate languages.

sp_helplanguage

See Also
@@LANGUAGE | System Stored Procedures
SET LANGUAGE |


sp_helplinkedsrvlogin

Provides information about login mappings defined against a specific linked server used for distributed queries and remote stored procedures.

Syntax

sp_helplinkedsrvlogin [[@rmtsrvname =] 'rmtsrvname',]
[[@locallogin =] 'locallogin']

Arguments
[@rmtsrvname =] 'rmtsrvname'
Is the name of the linked server that the login mapping applies to. rmtsrvname is sysname, with a default of NULL. If NULL, all login mappings defined against all the linked servers defined in the local computer running Microsoft® SQL Server™ are returned.
[@locallogin =] 'locallogin'
Is the SQL Server login on the local server that has a mapping to the linked server rmtsrvname. locallogin is sysname, with a default of NULL. NULL specifies that all login mappings defined on rmtsrvname are returned. If not NULL, a mapping for locallogin to rmtsrvname must already exist. locallogin can be a SQL Server login or a Microsoft Windows NT® user. The Windows NT user must have been granted access to SQL Server either directly or through its membership in a Windows NT group that has been granted access.
Return Code Values

0 (success) or 1 (failure)

Result Sets
Column name | Data type | Description
Linked Server | sysname | Linked server name.
Local Login | sysname | Local login for which the mapping applies.
Is Self Mapping | smallint | 0 = Local Login is mapped to Remote Login when connecting to Linked Server. 1 = Local Login is mapped to the same login and password when connecting to Linked Server.
Remote Login | sysname | Login name on Linked Server that is mapped to Local Login when Is Self Mapping is 0. If Is Self Mapping is 1, Remote Login is NULL.

Remarks

Before deleting login mappings, use sp_helplinkedsrvlogin to determine the linked servers that are involved.

Permissions

Execution permissions default to the public role.

Examples
A. Display all login mappings for all linked servers

This example displays all login mappings for all linked servers defined on the local computer running SQL Server.

EXEC sp_helplinkedsrvlogin

go

Linked Server    Local Login   Is Self Mapping Remote Login

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

Accounts         NULL          1               NULL

Sales            NULL          1               NULL

Sales            Mary          0               sa

Marketing        NULL          1               NULL

(4 row(s) affected)

B. Display all login mappings for a linked server

This example displays all locally defined login mappings for the Sales linked server.

EXEC sp_helplinkedsrvlogin 'Sales'

go

Linked Server    Local Login   Is Self Mapping Remote Login

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

Sales            NULL          1               NULL

Sales            Mary          0               sa

(2 row(s) affected)

C. Display all login mappings for a local login

This example displays all locally defined login mappings for the login Mary.

EXEC sp_helplinkedsrvlogin NULL, 'Mary'

go

Linked Server    Local Login   Is Self Mapping Remote Login

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

Sales            NULL          1               NULL

Sales            Mary          0               sa

(2 row(s) affected)

See Also
sp_addlinkedserver | System Stored Procedures
sp_droplinkedsrvlogin |


sp_helplogins

Provides information about logins and the associated users in each database.

Syntax

sp_helplogins [[@LoginNamePattern =] 'login']

Arguments
[@LoginNamePattern =] 'login'
Is a login name. login is sysname, with a default of NULL. login must exist if specified. If login is not specified, information about all logins is returned.
Return Code Values

0 (success) or 1 (failure)

Result Sets

The first report contains information about each login specified.

Column name | Data type | Description
LoginName | sysname | Login name.
SID | varbinary(85) | Login security identifier.
DefDBName | sysname | Default database that LoginName uses when connecting to Microsoft® SQL Server™.
DefLangName | sysname | Default language used by LoginName.
AUser | char(5) | Yes = LoginName has an associated username in a database. No = LoginName does not have an associated username.
ARemote | char(7) | Yes = LoginName has an associated remote login. No = LoginName does not have an associated login.

The second report contains information about users and aliases associated with each login.

Column name | Data type | Description
LoginName | sysname | Login name.
DBName | sysname | Default database that LoginName uses when connecting to SQL Server.
UserName | sysname | User account that LoginName is mapped to in DBName, and the roles that LoginName is a member of in DBName.
UserOrAlias | char(8) | MemberOf = UserName is a role. User = UserName is a user account.

Remarks

Before removing logins, use sp_helplogins to determine the user accounts the login maps to.

Permissions

Only members of the sysadmin and securityadmin fixed server roles can execute sp_helplogins.

Note sp_helplogins must check all databases on the server to determine the user accounts in those databases associated with the logins. Therefore, for each database on the server, one of these must apply:

  • The user executing sp_helplogins must have permissions to access the database.
  • The guest user account must exist in the database.

If a database cannot be accessed, sp_helplogins displays error message 15622 and as much information as it can for logins associated with user accounts in those databases.

Examples

This example reports information about the login John.

EXEC sp_helplogins 'John'

go

LoginName SID                        DefDBName DefLangName AUser ARemote

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

John      0x23B348613497D11190C100C  master    us_english  yes   no

(1 row(s) affected)

LoginName   DBName   UserName   UserOrAlias

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

John        pubs     John       User

(1 row(s) affected)

See Also
sp_helpuser System Stored Procedures


sp_helpmergearticle

Returns information about an article.

Syntax

sp_helpmergearticle [[@publication =] 'publication'] [,[@article =]'article']

Arguments
[@publication =] 'publication'
Is the name of the publication about which to retrieve information. publication is sysname, with a default of %, which returns information about all merge articles contained in all publications in the current database.
[@article =] 'article'
Is the name of the article for which to return information. article is sysname, with a default of %, which returns information about all merge articles in the given publication.
Result Set
Column name | Data type | Description
name | sysname | Name of the article
source_object_owner | sysname | Name of the owner of the source object
source_object | sysname | Name of the source object from which to add the article
sync_object_owner | sysname | Name of the owner of the synchronization object
sync_object | sysname | Name of the custom object used to establish the initial data for the partition
description | nvarchar(255) | Description of the article
status | tinyint | Status of the article
creation_script | nvarchar(127) | Optional precreation script for the article
conflict_table | nvarchar(258) | Name of the table storing the insert or update conflicts
pre_creation_command | tinyint | Precreation method
schema_option | binary(8) | Bitmap of the schema generation option for the article
type | tinyint | Type of article
column_tracking | int | Setting for column-level tracking
article_resolver | nvarchar(255) | Custom resolver for the article
subset_filterclause | nvarchar(2000) | WHERE clause specifying the horizontal filtering
resolver_info | sysname | Name of the article resolver

Remarks

sp_helpmergearticle is used in merge replication.

Permissions

Execute permissions default to the public role.

See Also
sp_addmergearticle | sp_dropmergearticle
sp_changemergearticle | System Stored Procedures


sp_helpmergearticleconflicts

Returns the articles in the publication that have conflicts.

Syntax

sp_helpmergearticleconflicts [[@publication =] 'publication']

Arguments
[@publication =] 'publication'
Is the name of the publication. publication is sysname, with a default of %, which returns all articles in the database that have conflicts.
Result Sets
Column name | Data type | Description
article | sysname | Name of the article
source_object | nvarchar(386) | Name of the source object
conflict_table | nvarchar(258) | Name of the table storing the insert or update conflicts
guidcolname | sysname | Name of the RowGuidCol for the source object
centralized_conflicts | int | Whether conflict records are stored on the given Publisher

If the article has only delete conflicts and no conflict_table rows, the name of the conflict_table in the result set is NULL.

Remarks

sp_helpmergearticleconflicts is used in merge replication.

Permissions

Execute permissions default to the public role.

See Also
System Stored Procedures


sp_helpmergeconflictrows

Returns the rows in the specified conflict table.

Syntax

sp_helpmergeconflictrows [[@publication =] 'publication']
{,[@conflict_table =] 'conflict_table'}

Arguments
[@publication =] 'publication'
Is the name of the publication. publication is sysname, with a default of %. If the publication is specified, all conflicts qualified by the publication are returned. For example, if the Conflict_Customers table has conflict rows for the WA and the CA publications, passing in a publication name CA retrieves conflicts that pertain to the CA publication.
[@conflict_table =] 'conflict_table'
Is the name of the conflict table. conflict_table is sysname, with no default.
Result Sets

sp_helpmergeconflictrows returns a result set consisting of the base table structure and these additional columns.

Column name | Data type | Description
origin_datasource | varchar(255) | Origin of the conflict
conflict_type | int | Code indicating the type of conflict: 1 = Update conflict 2 = Upload error 3 = Download error 4 = Update delete conflict 5 = Column update conflict
reason_code | int | Error code that can be context-sensitive
reason_text | varchar(720) | Error description that can be context-sensitive
pubid | uniqueidentifier | Publication identifier

Remarks

sp_helpmergeconflictrows is used in merge replication.

Permissions

Execute permissions default to the public role.

See Also
System Stored Procedures


sp_helpmergedeleteconflictrows

Returns the rows in the specified msmerge_delete_conflicts table.

Syntax

sp_helpmergedeleteconflictrows [[@publication =] 'publication']
[,[@source_object =] 'source_object']

Arguments
[@publication =] 'publication'
Is the name of the publication. publication is sysname, with a default of %. If the publication is specified, all conflicts qualified by the publication are returned. For example, if the msmerge_delete_conflicts table has conflict rows for the WA and the CA publications, passing in a publication name CA retrieves conflicts that pertain to the CA publication only.
[@source_object =] 'source_object'
Is the name of the source object. source_object is nvarchar(386), with a default of NULL.
Result Sets
Column name | Data type | Description
source_object | nvarchar(386) | Source object for the delete conflict
rowguid | uniqueidentifier | Row identifier for the delete conflict
conflict_type | int | Code indicating type of conflict: 1 = Update conflict 2 = Upload error 3 = Download error 4 = Update delete conflict 5 = Column update conflict
reason_code | int | Error code that can be context-sensitive
reason_text | varchar(720) | Error description that can be context-sensitive
origin_datasource | varchar(255) | Origin of the conflict
pubid | uniqueidentifier | Publication identifier

Remarks

sp_helpmergedeleteconflictrows is used in merge replication.

Permissions

Execute permissions default to the public role.

See Also
System Stored Procedures


sp_helpmergefilter

Returns information about merge filter(s).

Syntax

sp_helpmergefilter [@publication =] 'publication' [,[@article =] 'article']
[,[@filtername =] 'filtername']

Arguments
[@publication =] 'publication'
Is the name of the publication. publication is sysname, with no default.
[@article =]'article'
Is the name of the article. article is sysname, with a default of %, which returns the names of all articles.
[@filtername =] 'filtername'
Is the name of the filter about which to return information. filtername is sysname, with a default of %, which returns information about all the filters defined on the article or publication.
Result Sets
Column name | Data type | Description
join_filterid | int | ID of the join filter
filtername | sysname | Name of the filter
join article name | sysname | Name of the join article
join_filterclause | nvarchar(2000) | Filter clause qualifying the join
join_unique_key | int | Whether to join is on a unique key
base table owner | sysname | Name of the owner of the base table
base table name | sysname | Name of the base table
join table owner | sysname | Name of the owner of the table being joined to the base table
join table name | sysname | Name of the table being joined to the base table
article name | sysname | Name of the article

Remarks

sp_helpmergefilter is used in merge replication.

Permissions

Execute permissions default to the public role.

See Also
sp_ addmergefilter | sp_dropmergefilter
sp_changemergefilter | System Stored Procedures


sp_helpmergepublication

Returns information about a merge publication.

Syntax

sp_helpmergepublication [[@publication =] 'publication']
[,[@found =] 'found'] [OUTPUT]
[,[@publication_id =] 'publication_id'] [OUTPUT]
[,[@reserved =] 'reserved']

Arguments
[@publication =] 'publication'
Is the name of the publication. publication is sysname, with a default of %, which returns information about all merge publications in the current database.
[@found =] 'found' [OUTPUT]
Is a flag to indicate returning rows. found is int and an OUTPUT parameter, with a default of NULL. 1 indicates the publication is found. 0 indicates the publication is not found.
[@publication_id =] 'publication_id' [OUTPUT]
Is the publication identification number. publication_id is uniqueidentifier and an OUTPUT parameter, with a default of NULL.
[@reserved =] 'reserved'
Reserved for internal use.
Result Sets
Column name | Data type | Description
id | int | Sequential order of the publication in the list
name | sysname | Name of the publication
description | nvarchar(255) | Description of the publication
status | tinyint | When publication data will be available
retention | int | Amount of change, in days, to save for the given publication
sync_mode | tinyint | Mode of the synchronization
allow_push | int | Whether push subscriptions can be created for the given publication
allow_pull | int | Whether pull subscriptions can be created for the given publication
allow_anonymous | int | Whether anonymous subscriptions can be created for the given publication
centralized_conflicts | int | Whether conflict records are stored on the given Publisher
priority | float(8) | Priority of the loop-back subscription
snapshot_ready | tinyint | Whether the snapshot of this publication is ready
publication_type | int | Type of publication
pubid | uniqueidentifier | Unique identifier of this publication
snapshot_jobid | binary(16) | Job ID of the Snapshot Agent
enabled_for_internet | int | Whether the publication is enabled for the Internet
dynamic_filter | int | Whether a dynamic filter is used
has_subscription | bit | Whether the publication has any subscriptions

Remarks

sp_helpmergepublication is used in merge replication.

Permissions

Execute permissions default to the public role.

See Also
sp_addmergepublication | sp_dropmergepublication
sp_changemergepublication | System Stored Procedures


sp_helpmergepullsubscription

Returns information about the pull subscription.

Syntax

sp_helpmergepullsubscription [[@publication =] 'publication']
[,[@publisher =] 'publisher'] [,[@publisher_db =] 'publisher_db']
[,[@subscription_type =] 'subscription_type']

Argument
[@publication =] 'publication'
Is the name of the publication. publication is sysname, with a default of %. If publication is %, information about all merge publications and subscriptions in the current database is returned.
[@publisher =] 'publisher'
Is the name of the Publisher. publisher is sysname, with a default of %.
[@publisher_db =] 'publisher_db'
Is the name of the Publisher database. publisher_db is sysname, with a default of %.
[@subscription_type =] 'subscription_type'
Is whether to show pull subscriptions. subscription_type is nvarchar(10), with a default of pull.
Result Sets
Column name | Data type | Description
publication | sysname | Name of the publication
publisher | sysname | Name of the Publisher
publisher_db | sysname | Name of the Publisher database
subscriber | sysname | Name of the Subscriber
subscription _db | sysname | Name of the subscription database
status | int | Subscription status
subscriber_type | int | Type of Subscriber: 1 = Global 2 = Local 3 = Anonymous
subscription_type | int | Type of subscription: 0 = Push 1 = Pull 2 = Anonymous
priority | float(8) | Subscription priority. The value must be less than 100.00.
sync_type | tinyint | Subscription sync type: 1 = Automatic 2 = Nosync
description | nvarchar(255) | Brief description of this pull subscription
merge_jobid | binary(16) | Job ID of the Merge Agent
enabled_for_synmgr | int | Whether the subscription can be synchronized through the Microsoft Synchronization Manager.

Note that the result set is identical to that of sp_helpmergesubscription.

Remarks

sp_helpmergepullsubscription is used in merge replication.

Permissions

Execute permissions default to the public role.

See Also
sp_addmergepullsubscription | sp_dropmergepullsubscription
sp_changemergepullsubscription | System Stored Procedures


sp_helpmergesubscription

Returns information about a push subscription.

Syntax

sp_helpmergesubscription [[@publication =] 'publication']
[,[@subscriber =] 'subscriber'] [,[@subscriber_db =] 'subscriber_db'] [,[@publisher =] 'publisher'] [,[@publisher_db =] 'publisher_db']
[,[@subscription_type =] 'subscription_type']

Arguments
[@publication =] 'publication'
Is the name of the publication. publication is sysname, with a default of %. The publication must already exist and conform to the rules for identifiers. If NULL or %, information about all merge publications and subscriptions in the current database is returned.
[@subscriber =] 'subscriber'
Is the name of the Subscriber. subscriber is sysname, with a default of %. If NULL or %, information about all subscriptions to the given publication is returned.
[@subscriber_db =] 'subscriber_db'
Is the name of the subscription database. subscriber_db is sysname, with a default of %, which returns information about all subscription databases.
[@publisher =] 'publisher'
Is the name of the Publisher. The Publisher must be a valid server. publisher is sysname, with a default of %, which returns information about all Publishers.
[@publisher_db =] 'publisher_db']
Is the name of the Publisher database. publisher_db is sysname, with a default of %, which returns information about all Publisher databases.
[@subscription_type =] 'subscription_type'
Is the type of subscription. subscription_type is nvarchar(15), and can be one of these values.

Value | Description
push (default) | Push subscription
pull | Pull subscription
both | Both a push and pull subscription

Result Sets
Column name | Data type | Description
publication | sysname | Name of the publication
publisher | sysname | Name of the Publisher
publisher_db | sysname | Name of the Publisher database
subscriber | sysname | Name of the Subscriber
subscriber_db | sysname | Name of the subscription database
status | int | Status of the subscription
subscriber_type | int | Type of Subscriber
subscription_type | int | Type of subscription: 0 = Push 1 = Pull 2 = Both
priority | float(8) | Number indicating the priority for the subscription
sync_type | tinyint | Subscription sync type
description | nvarchar(255) | Brief description of this merge subscription
merge_jobid | binary(16) | Job ID of the Merge Agent
full_publication | tinyint | Whether the subscription is to a full or filtered publication

Remarks

sp_helpmergesubscription is used in merge replication.

Permissions

Execute permissions default to the public role.

See Also
sp_addmergesubscription | sp_dropmergesubscription
sp_changemergesubscription | System Stored Procedures


sp_help_notification

Reports a list of alerts for a given operator or a list of operators for a given alert.

Syntax

sp_help_notification [@object_type =] 'object_type',
[@name =] 'name',
[@enum_type =] 'enum_type',
[@notification_method =] notification_method
[, [@target_name =] 'target_name']

Arguments
[@object_type =] 'object_type'
Is the type of information to be returned. object_type is char(9), with no default. object_type can be ALERTS, which lists the alerts assigned to the supplied operator name, or OPERATORS, which lists the operators responsible for the supplied alert name.
[@name =] 'name'
Is either an alert name (if object_type is ALERTS) or an operator name (if object_type is OPERATORS). name is char(100), with no default.
[@enum_type =] 'enum_type'
Is the object_type information that is returned. enum_type is ACTUAL in most cases. enum_type is char(10), with no default, and can be one of these values.

Value | Description
ACTUAL | Lists only the object_types associated with name.
ALL | Lists all the object_types including those that are not associated with name.
TARGET | Lists only the object_types matching the supplied target_name, regardless of association with name.

[@notification_method =] notification_method
Is a numeric value that determines the notification method columns to return. notification_method is tinyint, and can be one of the following values.

Value | Description
1 | E-mail: returns only the use_email column.
2 | Pager: returns only the use_pager column.
4 | NetSend: returns only the use_netsend column.
7 | All: returns all columns.

[@target_name =] 'target_name'
Is an alert name to search for (if object_type is ALERTS) or an operator name to search for (if object_type is OPERATORS). target_name is needed only if enum_type is TARGET. target_name is char(100), with a default of NULL.
Return Code Valves

0 (success) or 1 (failure)

Result Sets

If object_type is ALERTS, the result set lists all the alerts for a given operator.

Column name | Data type | Description
alert_id | int | Alert identifier number.
alert_name | sysname | Alert name.
use_email | int | E-mail is used to notify the operator: 1 = Yes 0 = No
use_pager | int | Pager is used to notify operator: 1 = Yes 0 = No
use_netsend | int | Network pop-up is used to notify the operator: 1 = Yes 0 = No
has_email | int | Number of e-mail notifications sent for this alert.
has_pager | int | Number of pager notifications sent for this alert.
has_netsend | int | Number of netsend notifications sent for this alert.

If object_type is OPERATORS, the result set lists all the operators for a given alert.

Column name | Data type | Description
operator_id | int | Operator identification number.
operator_name | sysname | Operator name.
use_email | int | E-mail is used to send notification of the operator: 1 = Yes 0 = No
use_pager | int | Pager is used to send notification of the operator: 1 = Yes 0 = No
use_netsend | int | Is a network pop-up used to notify the operator: 1 = Yes 0 = No
has_email | int | Operator has an e-mail address: 1 = Yes 0 = No
has_pager | int | Operator has a pager address: 1 = Yes 0 = No

Remarks

This stored procedure must be run from the msdb database.

Permissions

Permissions to execute this procedure default to the sysadmin fixed server role and the db_owner fixed database role, who can grant permissions to other users.

Examples
A. List alerts for a specific operator

This example returns all alerts for which the operator John Doe receives any kind of notification.

USE msdb

EXEC sp_help_notification 'ALERTS', 'John Doe', 'ACTUAL', 7

B. List operators for a specific alert

This example returns all operators who receive any kind of notification for the Test Alert alert.

USE msdb

EXEC sp_help_notification 'OPERATORS', 'Test Alert', 'ACTUAL', 7

See Also
sp_add_notification | sp_update_notification
sp_delete_notification | System Stored Procedures


sp_helpntgroup

Reports information about Microsoft® Windows NT® groups with accounts in the current database.

Syntax

sp_helpntgroup [[@ntname =] 'name']

Arguments
[@ntname =] 'name'
Is the name of the Windows NT group. name is sysname, with a default of NULL. name must be a valid Windows NT group in the current database. If name is not specified, all Windows NT groups in the current database are included in the output. Specify the name that the Windows NT group is known by in the database (added using sp_grantdbaccess).
Return Code Values

0 (success) or 1 (failure)

Result Sets
Column name | Data type | Description
NTGroupName | sysname | Name of the Windows NT group.
NTGroupId | smallint | Group ID.
SID | varbinary(85) | Security identifier of NTGroupName.
HasDbAccess | int | 1 = Windows NT group has permission access to the database.

Remarks

To see a list of the Microsoft SQL Server™ roles in the current database, use sp_helprole.

Permissions

Execute permissions default to the public role.

Examples

This example prints a list of the Windows NT groups in the current database.

EXEC sp_helpntgroup

See Also
sp_grantdbaccess | sp_revokedbaccess
sp_helprole | System Stored Procedures


sp_help_operator

Reports information about the operators defined for the server.

Syntax

sp_help_operator [[@operator_name =] 'operator_name']
[,[@operator_id =] operator_id]

Arguments
[@operator_name =] 'operator_name'
Is the operator name. operator_name is sysname. If operator_name is not specified, information about all operators is returned.
[@operator_id =] operator_id
Is the identification number of the operator for which information is requested. operator_id is int, with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Result Sets
Column name | Data type | Description
id | int | Operator identification number.
name | sysname | Operator Name.
enabled | tinyint | Operator is available to receive any notifications: 1 = Yes 0 = No
email_address | nvarchar(100) | Operator e-mail address.
last_email_date | int | Date the operator was last notified by e-mail.
last_email_time | int | Time the operator was last notified by e-mail.
pager_address | nvarchar(100) | Operator pager address.
last_pager_date | int | Date the operator was last notified by pager.
last_pager_time | int | Time the operator was last notified by pager.
weekday_pager_ start_time | int | The start of the time period during which the operator is available to receive pager notifications on a weekday.
weekday_pager_ end_time | int | The end of the time period during which the operator is available to receive pager notifications on a weekday.
Saturday_pager_ start_time | int | The start of the time period during which the operator is available to receive pager notifications on Saturdays.
Saturday_pager_ end_time | int | The end of the time period during which the operator is available to receive pager notifications on Saturdays.
Sunday_pager_ start_time | int | The start of the time period during which the operator is available to receive pager notifications on Sundays.
Sunday_pager_ end_time | int | The end of the time period during which the operator is available to receive pager notifications on Sundays.
pager_days | tinyint | A bitmask (1 = Sunday, 64 = Saturday) of days-of-the week indicating when the operator is available to receive pager notifications.
netsend_address | nvarchar(100) | Operator address for network pop-up notifications.
last_netsend_date | int | Date the operator was last notified by network pop-up.
last_netsend_time | int | Time the operator was last notified by network pop-up.
category_name | sysname | Name of the operator category to which this operator belongs.

Remarks

sp_help_operator must be run from the msdb database.

Permissions

Permissions to execute this procedure default to the sysadmin fixed server role and the db_owner fixed database role, who can grant permissions to other users.

Examples

This example reports information about operator andrewf.

USE msdb

EXEC sp_help_operator 'andrewf'

See Also
sp_add_operator | sp_update_operator
sp_delete_operator | System Stored Procedures


sp_helppublication

Returns information about a publication.

Syntax

sp_helppublication [[@publication =] 'publication']

Arguments
[@publication =] 'publication'
Is the name of the publication to be viewed. publication is sysname, with a default of %, which returns information about all publications..
Result Sets
Column name | Data type | Description
pubid | int | ID for the publication.
name | sysname | Name of the publication.
restricted | int | Not used, set to 0.
status | tinyint | When publication data will be available.
task |  | Used for backward compatibility.
replication frequency | tinyint | Type of replication frequency: 0 = Transaction based 1 = Scheduled table refresh
synchronization method | tinyint | Synchronization mode: 0 = Native bulk copy program (bcp utility) 1 = Character bulk copy
description | nvarchar(255) | Optional description for the publication.
immediate_sync | bit | Whether the synchronization files are created or re-created each time the Snapshot Agent runs.
enabled_for_internet | bit | Whether the synchronization files for the publication are exposed to the Internet, through FTP and other services.
allow_push | bit | Whether push subscriptions are allowed on the publication.
allow_pull | bit | Whether pull subscriptions are allowed on the publication.
allow_anonymous | bit | Whether anonymous subscriptions are allowed on the publication.
independent_agent | bit | Whether there is a stand-alone Distribution Agent for this publication.
immediate_sync_ready | bit | Whether the Snapshot Agent is completed once for the immediate_sync publication. It has no definition for a nonimmediate_sync publication.
allow_sync_tran | bit | Whether immediate-updating subscriptions are allowed on the publication.
autogen_sync_procs | bit | Whether to automatically generate stored procedures to support immediate-updating subscriptions.
snapshot_jobid | binary(16) | Scheduled task ID.
retention | int | Amount of change, in days, to save for the given publication.

Remarks

sp_helppublication is used in snapshot and transactional replication.

Permissions

Execute permissions default to the public role.

See Also
sp_addarticle | sp_droppublication
sp_addpublication | sp_enumfullsubscribers
sp_articlecolumn | sp_helparticle
sp_changearticle | sp_helparticlecolumns
sp_changepublication | System Stored Procedures
sp_droparticle |


sp_help_publication_access

Returns a list of all granted logins for a publication.

Syntax

sp_help_publication_access [@publication =] 'publication',
[@return_granted =] 'return_granted'] [,[@login =] 'login']
[,[@initial_list =] initial_list]

Arguments
[@publication =] 'publication'
Is the name of the publication to access. publication is sysname, with no default.
[@return_granted =] 'return_granted'
Is the login ID. return_granted is bit, with a default of 1. If 0 is specified and SQL Server Authentication is used, the available logins that appear at the Publisher but not at the Distributor are returned. If 0 is specified and Windows NT Authentication is used, the logins not specifically denied access at either the Publisher or Distributor are returned.
[@login =] 'login'
Is the standard security login ID. login is sysname, with a default of %.
[@initial_list =] initial_list
Is whether to get the initial publication access list for the new publication. initial_list is bit, with a default of 0. If 1, returns the publication access list, which includes all the members of the sysadmin that have valid logins at the Distributor and the current login.
Result Sets
Column name | Data type | Description
loginname | nvarchar(256) | Actual login name.
isntname | int | 0 = Login is a Microsoft SQL Server login. 1 = Login is a Windows NT user or group.
isntgroup | int | 0 = Login is a Microsoft SQL Server login. 1 = Login is a Windows NT user or group.

Remarks

sp_help_publication_access is used in all types of replication.

Permissions

Execute permissions default to the public role.

See Also
sp_grant_publication_access | System Stored Procedures
sp_revoke_publication_access |


sp_helppullsubscription

Displays information about one or more subscriptions at the Subscriber.

Syntax

sp_helppullsubscription [[@publisher =] 'publisher']
[,[@publisher_db =] 'publisher_db'] [,[@publication =] 'publication']
[,[@show_push =] 'show_push']

Arguments
[@publisher =] 'publisher'
Is the name of the remote server. publisher is sysname, with a default of %, which returns all the Publishers.
[@publisher_db =] 'publisher_db'
Is the name of the Publisher database. publisher_db is sysname, with a default of %, which returns all the Publisher databases.
[@publication =] 'publication'
Is the name of the publication. publication is sysname, with a default of %, which returns all the publications.
[@show_push =] 'show_push'
Is whether all push subscriptions are to be returned. show_push is nvarchar(5), with a default of FALSE, which does not return all push subscriptions.
Result Sets
Column name | Data type | Description
publisher | sysname | Name of the Publisher
publisher database | sysname | Name of the Publisher database
publication | sysname | Name of the publication
subscription type | int | Subscription type to the publication
distribution agent | nvarchar(100) | Distribution Agent handling the subscription
publication description | nvarchar(255) | Description of the publication
last updating time | date | Time the subscription information was updated
subscription name | varchar(386) | Name of the subscription
last transaction timestamp | varbinary(16) | Timestamp of the last replicated transaction
update mode | tinyint | Type of updates allowed
distribution agent job_id | int | Job ID of the Distribution Agent
subscription guid | binary(16) | Global identifier for the version of the subscription on the publication
subid | binary(16) | Global identifier for an anonymous subscription
immediate_sync | bit | Whether the synchronization files are created or re-created each time the Snapshot Agent runs
enabled_for_synmgr | int | Whether the subscription can be synchronized through the Microsoft Synchronization Manager.

Remarks

sp_helppullsubscription is used in snapshot and transactional replication.

Permissions

Execute permissions default to the public role.

See Also
sp_addpullsubscription | System Stored Procedures
sp_droppullsubscription |


sp_helpremotelogin

Reports information about remote logins for a particular remote server, or for all remote servers, defined on the local server.

Syntax

sp_helpremotelogin [[@remoteserver =] 'remoteserver']
[,[@remotename =] 'remote_name']

Arguments
[@remoteserver =] 'remoteserver'
Is the remote server about which the remote login information is returned. remoteserver is sysname, with a default of NULL. If remoteserver is not specified, information about all remote servers defined on the local server is returned.
[@remotename =] 'remote_name'
Is a specific remote login on the remote server. remote_name is sysname, with a default of NULL. If remote_name is not specified, information about all remote users defined for remoteserver is returned.
Return Code Values

0 (success) or 1 (failure)

Result Sets
Column name | Data type | Description
server | sysname | Name of a remote server defined on the local server.
local_user_name | sysname | Login on the local server that remote logins from server map to.
remote_user_name | sysname | Login on the remote server that maps to local_user_name.
options | sysname | Trusted = The remote login does not need to supply a password when connecting to the local server from the remote server. Untrusted (or blank) = The remote login is prompted for a password when connecting to the local server from the remote server.

Remarks

Use sp_helpserver to list the names of remote servers defined on the local server.

Permissions

Execute permissions default to the public role.

Examples
A. Report help on a single server

This example displays information about all remote users on the remote server Accounts.

EXEC sp_helpremotelogin 'Accounts'

B. Report help on all remote users

This example displays information about all remote users on all remote servers known to the local server.

EXEC sp_helpremotelogin

See Also
sp_addremotelogin | sp_remoteoption
sp_dropremotelogin | System Stored Procedures
sp_helpserver |


sp_helpreplicationdboption

Shows the databases that have the replication option enabled.

Syntax

sp_helpreplicationdboption [[@dbname =] 'dbname'] [,[@type =] 'type']

Arguments
[@dbname =] 'dbname'
Is the name of the database. dbname is sysname, with a default of %.
[@type =] 'type'
Is whether replication is allowed. type is sysname, and can be one of the following values.

Value | Description
publish | Transactional replication allowed
merge publish | Merge replication allowed
replication allowed (default) | Either transactional or merge replication allowed.

Result Sets
Column name | Data type | Description
name | sysname | Name of the database
id | sysname | ID of the database

Remarks

sp_helpreplicationdboption is used in snapshot, transactional, and merge replication.

Permissions

Execute permissions default to the public role.

See Also
System Stored Procedures


sp_helprole

Returns information about the roles in the current database.

Syntax

sp_helprole [[@rolename =] 'role']

Arguments
[@rolename =] 'role'
Is the name of a role in the current database. role is sysname, with a default of NULL. role must exist in the current database. If role is not specified, information about all roles in the current database is returned.
Return Code Values

0 (success) or 1 (failure)

Result Sets
Column name | Data type | Description
RoleName | sysname | Name of the role in the current database.
RoleId | smallint | ID of RoleName.
IsAppRole | int | 0 = RoleName is not an application role. 1 = RoleName is an application role.

Remarks

To view the permissions associated with the role, use sp_helprotect.

To view the members of a database role, use sp_helprolemember.

Permissions

Execute permissions default to the public role.

Examples

This example displays all the roles in the current database.

EXEC sp_helprole

See Also
sp_addapprole | sp_helprolemember
sp_addrole | sp_helpsrvrolemember
sp_droprole | System Stored Procedures


sp_helprolemember

Returns information about the members of a role in the current database.

Syntax

sp_helprolemember [[@rolename =] 'role']

Arguments
[@rolename =] 'role'
Is the name of a role in the current database. role is sysname, with a default of NULL. role must exist in the current database. If role is not specified, then all roles that contain at least one member from the current database are returned.
Return Code Values

0 (success) or 1 (failure)

Result Sets
Column name | Data type | Description
DbRole | sysname | Name of the role in the current database
MemberName | sysname | Name of a member of DbRole
MemberSID | varbinary(85) | Security identifier of MemberName

Remarks

If a subrole is a member of the specified role, use sp_helprolemember with the name of the subrole to see the members of the subrole.

Use sp_helpsrvrolemember to display the members of a fixed server role.

Permissions

Execute permissions default to the public role.

Examples

This example displays the members of the Sales role.

EXEC sp_helprolemember 'Sales'

See Also
sp_addrolemember | sp_helpsrvrolemember
sp_droprolemember | System Stored Procedures
sp_helprole |


sp_helprotect

Returns a report with information about user permissions for an object, or statement permissions, in the current database.

Syntax

sp_helprotect [[@name =] 'object_statement']
[,[@username =] 'security_account']
[,[@grantorname =] 'grantor']
[,[@permissionarea =] 'type']

Arguments
[@name =] 'object_statement'
Is the name of the object in the current database, or a statement, with the permissions to report. object_statement is nvarchar(776), with a default of NULL, which returns all object and statement permissions. If the value is an object (table, view, stored procedure, or extended stored procedure), it must be a valid object in the current database. The object name can include an owner qualifier in the form owner.object.

If object_statement is a statement, it can be:

  • CREATE DATABASE
  • CREATE DEFAULT
  • CREATE PROCEDURE
  • CREATE RULE
  • CREATE TABLE
  • CREATE VIEW
  • BACKUP DATABASE
  • BACKUP LOG
[@username =] 'security_account'
Is the name of the security account for which permissions are returned. security_account is sysname, with a default of NULL, which returns all security accounts in the current database. security_account must be a valid security account in the current database. When specifying a Microsoft® Windows NT® user, specify the name the Windows NT user is known by in the database (added using sp_grantdbaccess).
[@grantorname =] 'grantor'
Is the name of the security account that has granted permissions. grantor is sysname, with a default of NULL, which returns all information for permissions granted by any security account in the database. When specifying a Windows NT user, specify the name that the Windows NT user is known by in the database (added using sp_grantdbaccess).
[@permissionarea =] 'type'
Is a character string indicating whether to display object permissions (character string o), statement permissions (character string s), or both (o s). type is varchar(10), with a default of o s. type may be any combination of o and s, with or without commas or spaces between o and s.
Return Code Values

0 (success) or 1 (failure)

Result Sets
Column name | Data type | Description
Owner | sysname | Name of the object owner.
Object | sysname | Name of the object.
Grantee | sysname | Name of the person granted permissions.
Grantor | sysname | Name of the person who granted permissions to the specified grantee.
ProtectType | char(10) | Name of the type of protection: GRANT REVOKE
Action | varchar(20) | Name of the permission: REFERENCES SELECT INSERT DELETE UPDATE CREATE TABLE CREATE DATABASE CREATE RULE CREATE VIEW CREATE PROCEDURE EXECUTE BACKUP DATABASE CREATE DEFAULT BACKUP LOG
Column | sysname | Type of permission: All = Permission covers all current columns of the object. New = Permission covers any new columns that might be altered (by using the ALTER statement) on the object in the future. All+New = Combination of All and New.

Remarks

All of the parameters of this procedure are optional. If executed with no parameters, sp_helprotect displays all of the permissions that have been granted or denied in the current database.

If some, but not all of the parameters are specified, use named parameters to identify the particular parameter, or NULL as a placeholder. For example, to report all permissions for the grantor dbo, execute:

EXEC sp_helprotect NULL, NULL, dbo

Or

EXEC sp_helprotect @grantorname = 'dbo'

The output report is sorted by permission category, owner, object, grantee, grantor, protection type category, protection type, action, and column sequential ID.

Permissions

Execute permissions default to the public role.

Examples
A. List the permissions for a table

This example lists the permissions for the titles table.

EXEC sp_helprotect 'titles'

B. List the permissions for a user

This example lists all permissions that user Judy has in the current database.

EXEC sp_helprotect NULL, 'Judy'

C. List the permissions granted by a specific user

This example lists all permissions that were granted by user Judy in the current database, using a NULL as a placeholder for the missing parameters.

EXEC sp_helprotect NULL, NULL, 'Judy'

D. List the statement permissions only

This example lists all the statement permissions in the current database, using NULL as a placeholder for the missing parameters.

EXEC sp_helprotect NULL, NULL, NULL, 's'

See Also
GRANT | REVOKE
DENY | System Stored Procedures


sp_helpserver

Reports information about a particular remote or replication server, or about all servers of both types. Provides the server name, the server’s network name, the server’s replication status, and the server’s identification number.

Syntax

sp_helpserver [[@server=] 'server']
[,[@optname=] 'option']
[,[@show_topology=] 'show_topology']

Arguments
[@server=] 'server'
Is the server about which information is reported. When no server is supplied, reports about all servers in master.dbo.sysservers. server is sysname, with a default of NULL.
[@optname=] 'option'
Is the option describing the server. option is varchar(35), with a default of NULL, and must be one of these values.

Value | Description
collation compatible | Afftects the Distributed Query execution against linked servers. If this option is set to true, Microsoft SQL Server assumes that all characters in the linked server are compatible with the local server, with regard to character set and collation sequence (or sort order).
data access | Enables and disables a linked server for distributed query access.
dist | Distributor
dpub | Remote Publisher to this Distributor
pub | Publisher
rpc | Enables RPC from the given server.
rpc out | Enables RPC to the given server.
sub | Subscriber
system | For internal use only.

[@show_topology=] 'show_topology'
Is the relationship of the given server to other servers. show_topology is varchar(1), with a default of NULL. If show_topology is not equal to t or is NULL, sp_helpserver returns the server’s name, network name, status, and ID. Otherwise, sp_helpserver returns the server’s name, network name, status, ID, and topology information.
Return Code Values

0 (success) or 1 (failure).

Result Sets
Column name | Data type | Description
name | sysname | Server name
network_name | sysname | Server’s network name
status | varchar(70) | Server status
id | char(4) | Server’s identification number

Remarks

A server can have more than one status.

Permissions

Execute permissions default to the public role.

Examples
A. Display information about all servers

This example displays information about all servers (sp_helpserver with no parameters).

USE master

EXEC sp_helpserver

B. Display information about a specific server

This example displays all information about the SEATTLE2 server.

USE master

EXEC sp_helpserver 'SEATTLE2'

See Also
sp_adddistpublisher | sp_dropsubscriber
sp_addserver | sp_helpdistributor
sp_addsubscriber | sp_helpremotelogin
sp_changesubscriber | sp_helpsubscriberinfo
sp_dboption | sp_serveroption
sp_dropserver | System Stored Procedures


sp_helpsort

Displays the Microsoft® SQL Server™ sort order and character set.

Syntax

sp_helpsort

Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

The default is case-insensitive dictionary sort order.

For the output of sp_helpsort to appear correctly on a client computer, the client must be running the same character set and code page as the server running SQL Server.

Permissions

Execute permissions default to the public role.

Examples

This example displays the name of the server’s default sort order, its character set, and a table of its primary sort values.

sp_helpsort

go


sp_helpsrvrole

Returns a list of the Microsoft® SQL Server™ fixed server roles.

Syntax

sp_helpsrvrole [[@srvrolename =] 'role']

Arguments
[@srvrolename =] 'role'
Is the name of the fixed server role. role is sysname, with a default of NULL, and can be any of these values.

Fixed server role | Description
sysadmin | System administrators
securityadmin | Security administrators
serveradmin | Server administrators
setupadmin | Setup administrators
processadmin | Process administrators
diskadmin | Disk administrators
dbcreator | Database creators

Return Code Values

0 (success) or 1 (failure)

Result Sets
Column name | Data type | Description
ServerRole | sysname | Name of the server role
Description | sysname | Description of ServerRole

Remarks

Fixed server roles are defined at the server level and have permissions to perform specific server-level administrative activities. Fixed server roles cannot be added, removed, or changed.

The table shows stored procedures that can be used to modify server roles.

Stored procedure | Action
sp_addsrvrolemember | Adds a login account to a fixed server role.
sp_helpsrvrolemember | Displays a list of the members of a fixed server role.
sp_dropsrvrolemember | Removes a member of a server role.

Permissions

Execute permissions default to the public role.

Examples

This example shows the list of available fixed server roles.

EXEC sp_helpsrvrole

See Also
sp_addsrvrolemember | sp_helpsrvrolemember
sp_dropsrvrolemember | System Stored Procedures


sp_helpsrvrolemember

Returns information about the members of a Microsoft® SQL Server™ fixed server role.

Syntax

sp_helpsrvrolemember [[@srvrolename =] 'role']

Arguments
[@srvrolename =] 'role'
Is the name of a fixed server role about whose members information is returned. role is sysname, with a default of NULL. If role is not specified, the result set includes information regarding all fixed server roles.

role can be any of these values.

Fixed server role | Description
sysadmin | System administrators
securityadmin | Security administrators
serveradmin | Server administrators
setupadmin | Setup administrators
processadmin | Process administrators
diskadmin | Disk administrators
dbcreator | Database creators

Return Code Values

0 (success) or 1 (failure)

Result Sets
Column name | Data type | Description
ServerRole | sysname | Name of the server role
MemberName | sysname | Name of a member of ServerRole
MemberSID | varbinary(85) | Security identifier of MemberName

Remarks

Use sp_helprolemember to display the members of a database role.

Permissions

Execute permissions default to the public role.

Examples

This example lists the members of the sysadmin fixed server role.

EXEC sp_helpsrvrolemember 'sysadmin'

See Also
sp_addsrvrolemember | sp_helprolemember
sp_dropsrvrolemember | System Stored Procedures
sp_helprole |


sp_helpsubscriberinfo

Displays information about a Subscriber.

Syntax

sp_helpsubscriberinfo [[@subscriber =] 'subscriber']

Arguments
[@subscriber =] 'subscriber'
Is the name of the Subscriber. subscriber is sysname, with a default of %, which returns all information.
Result Sets
Column name | Data type | Description
publisher | sysname | Name of the Publisher.
subscriber | sysname | Name of the Subscriber.
type | tinyint | Type of Subscriber: 0 = Microsoft SQL Server database 1 = ODBC data source
login | sysname | Login ID for SQL Server Authentication.
password | sysname | Password for SQL Server Authentication.
commit_batch_size | int | Not supported.
status_batch_size | int | Not supported.
flush_frequency | int | Not supported.
frequency_type | int | Frequency with which the Distribution Agent is run: 1 = One time 2 = On demand 4 = Daily 8 = Weekly 16 = Monthly 32 = Monthly relative 64 = Autostart 124 = Recurring
frequency_interval | int | Value applied to the frequency set by frequency_type.
frequency_relative_interval | int | Date of the Distribution Agent Used when frequency_type is set to 32 (monthly relative): 1 = First 2 = Second 4 = Third 8 = Fourth 16 = Last
frequency_recurrence_factor | int | Recurrence factor used by frequency_type.
frequency_subday | int | How often to reschedule during the defined period: 1 = Once 2 = Second 4 = Minute 8 = Hour
frequency_subday_interval | int | Interval for frequency_subday.
active_start_time_of_day | int | Time of day when the Distribution Agent is first scheduled, formatted as HHMMSS.
active_end_time_of_day | int | Time of day when the Distribution Agent stops being scheduled, formatted as HHMMSS.
active_start_date | int | Date when the Distribution Agent is first scheduled, formatted as YYYYMMDD.
active_end_date | int | Date when the Distribution Agent stops being scheduled, formatted as YYYYMMDD.
retryattempt | int | Not supported.
retrydelay | int | Not supported.
description | nvarchar(255) | Text description of the Subscriber.
security_mode | int | Implemented security mode: 0 = SQL Server Authentication 1 = Windows NTAuthentication

Remarks

sp_helpsubscriberinfo is used in snapshot, transactional, and merge replication.

Permissions

Only members of the sysadmin fixed server role can execute sp_helpsubscriberinfo.

See Also
sp_adddistpublisher | sp_dropsubscriber
sp_addsubscriber | sp_helpdistributor
sp_changesubscriber | sp_helpserver
sp_dboption | System Stored Procedures


sp_helpsubscription

Lists subscription information associated with a particular publication, article, Subscriber, or set of subscriptions.

Syntax

sp_helpsubscription [[@publication =] 'publication'] [,[@article =] 'article'] [,[@subscriber =] 'subscriber'] [,[@destination_db =] 'destination_db']

Arguments
[@publication =] 'publication'
Is the name of the associated publication. publication is sysname, with a default of %, which returns all subscription information for this server.
[@article =] 'article'
Is the name of the article. article is sysname, with a default of %, which returns all subscription information for the selected publications and Subscribers. If all, only one entry is returned for the a full subscription on a publication.
[@subscriber =] 'subscriber'
Is the name of the Subscriber viewing subscriptions. subscriber is sysname, with a default of %, which returns all subscription information for the selected publications and articles.
[@destination_db =] 'destination_db'
Is the name of the destination database. destination_db is sysname, with a default of %.
Result Sets
Column name | Data type | Description
subscriber | sysname | Name of the Subscriber
publication | sysname | Name of the publication
article | sysname | Name of the article
destination database | sysname | Name of the destination database in which replicated data is placed
subscription status | tinyint | Subscription status: 0 = Inactive 1 = Subscribed 2 = Active
synchronization type | tinyint | Subscription synchronization type: 1 = Automatic 2 = None
subscription type | int | Type of subscription: 0 = Push 1 = Pull 2 = Anonymous
full subscription | bit | Whether subscription is to all articles in the publication: 0 = No 1 = Yes
subscription name | nvarchar(255) | Name of the subscription
update mode | int | 0 = Read-only 1 = Immediate-updating subscription
distribution job id | binary(16) | Job ID of the Distribution Agent
loopback_detection | bit | 0 = No 1 = Yes

Remarks

sp_helpsubscription is used in snapshot, transactional, and merge replication.

Permissions

Execute permissions default to the public role.

See Also
sp_addsubscription | sp_dropsubscription
sp_changesubstatus | System Stored Procedures


sp_helpsubscription_properties

Retrieves security information from the MSsubscription_properties table.

Syntax

sp_helpsubscription_properties [[@publisher =] 'publisher']
[,[@publisher_db =] 'publisher_db'] [,[@publication =] 'publication']
[,[@publication_type =] publication_type]

Arguments
[@publisher =] 'publisher'
Is the name of the Publisher. publisher is sysname, with a default of %.
[@publisher_db =] 'publisher_db'
Is the name of the Publisher database. publisher_db is sysname, with a default of %.
[@publication =] 'publication'
Is the name of the publication. publication is sysname, with a default of %.
[@publication_type =] publication_type
Is the type of publication. publication_type is int, with a default of NULL.
Result Sets
Column name | Data type | Description
publisher | sysname | Name of the Publisher.
publisher_db | sysname | Name of the Publisher database.
publication | sysname | Name of the publication.
publication_type | int | Type of publication: 0 = Snapshot 1 = Transactional 2 = Merge
publisher_login | sysname | Login ID used at the Publisher for SQL Server Authentication.
publisher_password | sysname | Password used at the Publisher for SQL Server Authentication.
publisher_security_mode | int | Security mode used at the Publisher: 0 = SQL Server Authentication 1 = Windows NT Authentication
encrypted_publisher_password | bit | Indicates whether password is encrypted.
distributor_login | sysname | Distributor login.
distributor_password | sysname | Distributor password.
distributor_security_mode | int | Security mode used at the Distributor: 0 = SQL Server Authentication 1 = Windows NT Authentication
encrypted_distributor_password | bit | For internal use only.
ftp_address | sysname | Network address of the FTP service for the Distributor.
ftp_port | int | Port number of the FTP service for the Distributor.
ftp_login | sysname | Username used to connect to the FTP service.
ftp_password | sysname | User password used to connect to the FTP service.

Remarks

sp_helpsubscription_properties is used in snapshot, transactional, and merge replication.

Permissions

Only members of the sysadmin fixed server role can execute sp_helpsubscription_properties.

See Also
System Stored Procedures


sp_help_targetserver

Lists all target servers.

Syntax

sp_help_targetserver [[@server_name =] 'server_name']

Argument
[@server_name =] 'server_name'
Is the name of the server for which to return information. server_name is varchar(100), with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Result Sets

If server_name is not specified, sp_help_targetserver returns this result set.

Column name | Data type | Description
server_id | int | Server identification number.
server_name | nvarchar(30) | Server name.
location | nvarchar(200) | Location of the specified server.
time_zone_adjustment | int | Time zone adjustment, in hours, from Greenwich mean time (GMT).
enlist_date | datetime | Date of the specified server’s enlistment.
last_poll_date | datetime | Date the server was last polled for jobs.
status | int | Status of the specified server.
unread_instructions | int | Whether the server has unread instructions. (If all rows have been downloaded, this column is 0.)
local_time | datetime | Local date and time on the target server, which is based on the local time on the target server as of the last poll of the master server.
Enlisted_by_nt_user | nvarchar(100) | MicroSoft®Windows NT® user that enlisted the target server.
poll_interval | int | Frequency with which the target server polls the Master SQL Server Agent in order to download jobs and upload job status.

Permissions

Permissions to execute this procedure default to the sysadmin fixed server role and the db_owner fixed database role, who can grant permissions to other users.

Examples

This example lists information for all servers, and then only for the LONDON1 target server.

USE msdb

EXEC sp_help_targetserver

EXEC sp_help_targetserver 'LONDON1'

See Also
sp_add_targetservergroup | sp_update_targetservergroup
sp_delete_targetserver | sysdownloadlist
sp_delete_targetservergroup | System Stored Procedures


sp_help_targetservergroup

Lists all target servers in the specified group. If no group is specified, Microsoft® SQL Server™ returns information on all target server groups.

Syntax

sp_help_targetservergroup [[@name =] 'name']

Argument
[@name =] 'name'
Is the name of the target server group for which to return information. name is varchar(100), with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Result Sets
Column name | Data type | Description
servergroup_id | int | Identification number of the server group
name | sysname | Name of the server group

Permissions

Permissions to execute this procedure default to the sysadmin fixed server role and the db_owner fixed database role, who can grant permissions to other users.

Examples

This example lists all target server groups first, followed by all other target servers in the Servers Maintaining Customer Information target server group.

USE msdb

EXEC sp_help_targetserver

EXEC sp_help_targetserver 'Servers Maintaining Customer Information'

See Also
sp_add_targetservergroup | sp_delete_targetservergroup
sp_update_targetservergroup | System Stored Procedures


sp_helptask

sp_helptask is provided for backward compatibility only.

Provides information about one or more tasks that the user owns. sp_helptask prevents sensitive information stored in the systasks table from being returned to all users.

Important For information about syntax used in earlier versions of SQL Server, see the Microsoft SQL Server Transact-SQL Reference for version 6.x.

Permissions

Execute permissions default to the public role. Anyone who can execute this procedure can also create, delete, or update a job, job step, job category, job schedule, job server, task, or job history information.

See Also
sp_addtask | sp_purgehistory
sp_droptask | System Stored Procedures
sp_updatetask |


sp_helptext

Prints the text of a rule, a default, or an unencrypted stored procedure, trigger, or view.

Syntax

sp_helptext [@objname =] 'name'

Arguments
[@objname =] 'name'
Is the name of the object for which to display definition information. The object must be in the current database. name is nvarchar(776), with no default.
Return Code Values

0 (success) or 1 (failure)

Result Sets
Column name | Data type | Description
Text | nvarchar(255) | Stored procedure text

Remarks

sp_helptext prints out the text used to create an object in multiple rows, each with 255 characters of the Transact-SQL definition. The definition resides in the text in the syscomments table of the current database only.

Permissions

Execute permissions default to the public role.

Examples

This example displays the text of the employee_insupd trigger, which is in the pubs database.

USE pubs

EXEC sp_helptext 'employee_insupd'

See Also
CREATE PROCEDURE | sp_help
CREATE TRIGGER | System Stored Procedures
CREATE VIEW |


sp_helptrigger

Returns the type or types of triggers defined on the specified table for the current database.

Syntax

sp_helptrigger [@tabname =] 'table'
[,[@triggertype =] 'type']

Arguments
[@tabname =] 'table'
Is the name of the table in the current database for which to return trigger information. table is nvarchar(776), with no default.
[@triggertype =] 'type'
Is the type of trigger to return information about. type is char(6), with a default of NULL, and can be one of these values.

Value | Description
DELETE | Returns DELETE trigger information.
INSERT | Returns INSERT trigger information.
UPDATE | Returns UPDATE trigger information.

Return Code Values

0 (success) or 1 (failure)

Remarks
Column name | Data type | Description
trigger_name | sysname | Name of the trigger
trigger_owner | sysname | Name of the trigger owner
isupdate | int | 1 = UPDATE trigger 0 = Not an UPDATE trigger
isdelete | int | 1 = DELETE trigger 0 = Not a DELETE trigger
isinsert | int | 1 = INSERT trigger 0 = Not an INSERT trigger

Permissions

Execute permissions default to the public role.

Examples

This example creates a trigger named sales_warn that raises error 50010 when the amount of books sold is 10. Then, sp_helptrigger is executed to produce information about the trigger(s) on the sales table.

USE pubs

CREATE TRIGGER sales_warn

ON sales

FOR INSERT, UPDATE

AS RAISERROR (50010, 16, 10)

EXEC sp_helptrigger sales

Here is the result set:

trigger_name  trigger_owner           isupdate    isdelete    isinsert

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

sales_warn        dbo                 1           0         1

(1 row(s) affected)

See Also
ALTER TRIGGER | DROP TRIGGER
CREATE TRIGGER | System Stored Procedures


sp_helpuser

Reports information about Microsoft® SQL Server™ users, Microsoft Windows NT® users, and database roles in the current database.

Syntax

sp_helpuser [[@name_in_db =] 'security_account']

Arguments
[@name_in_db =] 'security_account'
Is the name of a SQL Server user, Windows NT user, or database role in the current database. security_account must exist in the current database. security_account is sysname, with a default of NULL. If security_account is not specified, the system procedure reports on all users, Windows NT users, and roles in the current database. When specifying a Windows NT user, specify the name that the Windows NT user is known by in the database (added using sp_grantdbaccess).
Return Code Values

0 (success) or 1 (failure)

Result Sets

Neither a user account nor a SQL Server or Windows NT user is specified for security_account.

Column name | Data type | Description
UserName | sysname | Users and Windows NT users in the current database
GroupName | sysname | Roles to which UserName belongs
LoginName | sysname | Login of UserName
DefDBName | sysname | Default database of UserName
UserID | smallint | ID of UserName in the current database
SuserID | smallint | Server user ID

No user account is specified and aliases exist in the current database.

Column name | Data type | Description
LoginName | sysname | Logins aliased to users in the current database
UserNameAliasedTo | sysname | Username in the current database that the login is aliased to

A role is specified for security_account.

Column name | Data type | Description
Group_name | sysname | Name of the role in the current database
Group_id | smallint | Role ID for the role in the current database
Users_in_group | sysname | Member of the role in the current database
Userid | smallint | User ID for the member of the role

Remarks

Use sp_helpsrvrole and sp_helpsrvrolemember to return information about fixed server roles.

Executing sp_helpuser for a database role is equivalent to executing sp_helpgroup for that database role.

Permissions

Execute permissions default to the public role.

Examples
A. List all users

This example lists all users in the current database.

EXEC sp_helpuser

B. List information for a single user

This example lists information about the user dbo.

EXEC sp_helpuser 'dbo'

C. List information for a database role

This example lists information about the db_securityadmin fixed database role.

EXEC sp_helpuser 'db_securityadmin'

See Also
sp_adduser | sp_helpsrvrole
sp_dropuser | sp_helpsrvrolemember
sp_helpgroup | System Stored Procedures
sp_helprole |


sp_indexes

Returns index information for the specified remote table.

Syntax

sp_indexes [@table_server =] 'table_server'
[,[@table_name =] 'table_name']
[,[@table_schema =] 'table_schema']
[,[@table_catalog =] 'table_db']
[,[@index_name =] 'index_name']
[,[@is_unique =] 'is_unique']

Arguments
[@table_server =] 'table_server'
Is the name of a linked server running Microsoft® SQL Server™ for which table information is being requested. table_server is sysname, with no default.
[@table_name =] 'table_name'
Is the name of the remote table for which to provide index information. table_name is sysname, with a default of NULL. If NULL, all tables in the specified database are returned.
[@table_schema =] 'table_schema'
Specifies the table schema. In the Microsoft SQL Server environment, this corresponds to the table owner. table_schema is sysname, with a default of NULL.
[@table_catalog =] 'table_db'
Is the name of the database in which table_name resides. table_db is sysname, with a default of NULL. If NULL, table_db defaults to master.
[@index_name =] 'index_name'
Is the name of the index for which information is being requested. index is sysname, with a default of NULL.
[@is_unique =] 'is_unique'
Is the type of index for which to return information. is_unique is bit, with a default of NULL, and can be one of these values.

Value | Description
1 | Returns information about unique indexes.
0 | Returns information about indexes that are not unique.
NULL | Returns information about all indexes.

Result Sets
Column name | Data type | Description
TABLE_CAT | sysname | Name of the database in which the specified table resides.
TABLE_SCHEM | sysname | Schema for the table.
TABLE_NAME | sysname | Name of the remote table.
NON_UNIQUE | smallint | Whether the index is unique or not unique: 0 = Unique 1 = Not unique
INDEX_QUALIFER | sysname | Name of the index owner. Some DBMS products allow users other than the table owner to create indexes. In SQL Server, this column is always the same as TABLE_NAME.
INDEX_NAME | sysname | Name of the index.
TYPE | smallint | Type of index: 0 = Statistics for a table 1 = Clustered 2 = Hashed 3 = Other
ORDINAL_POSITION | int | Ordinal position of the column in the table. The first column in the table is 1. This column always returns a value.
COLUMN_NAME | sysname | Is the corresponding name of the column for each column of the TABLE_NAME returned.
ASC_OR_DESC | varchar | Is the order used in collation: A = Ascending D = Descending NULL = Not applicable SQL Server always returns A.
CARDINALITY | int | Is the number of rows in the table or unique values in the index.
PAGES | int | Is the number of pages to store the index or table.
FILTER_CONDITION | nvarchar(4000) | SQL Server does not return a value.

Permissions

Execute permissions default to the public role.

Examples

This example returns all index information from the Employees table of the Northwind database on the LONDON1 database server.

EXEC sp_indexes @table_server = 'LONDON1',

    @table_name = 'Employees',
    @table_catalog = 'Northwind',
    @is_unique = 0

See Also
sp_catalogs | sp_linkedservers
sp_column_privileges | sp_table_privileges
sp_foreignkeys | sp_tables_ex
sp_indexes | System Stored Procedures


sp_indexoption

Sets option values for user-defined indexes.

Note Microsoft® SQL Server™ automatically makes choices of page-, row-, or table-level locking. It is not necessary to set these options manually. sp_indexoption is provided for expert users who know with certainty that a particular type of lock is always appropriate.

Syntax

sp_indexoption [@IndexNamePattern =] 'index_name'
[,[@OptionName =] 'option_name']
[,[@OptionValue =] 'value']

Arguments
[@IndexNamePattern =] 'index_name'
Is the qualified or nonqualified name of a user-defined database table or index. Quotation marks are not necessary if a single index or table name is specified. Even if a fully qualified table name, including a database name, is provided, the database name must be the name of the current database. If a table name is given with no index, the specified option value is set for all indexes on that table. index_pattern is nvarchar(1035), with no default.

[@OptionName =] 'option_name'

Is an index option name. option_name is varchar(35), with a default of NULL, which lists all available table options and the corresponding default values assigned to new tables (0 = FALSE or off, 1 = TRUE or on). option_name can have these values.

Value | Description
AllowRowLocks | When FALSE, row locks are not used. Access to the specified indexes is obtained using page- and table-level locks.
AllowPageLocks | When FALSE, page locks are not used. Access to the specified indexes is obtained using row- and table-level locks.

[@OptionValue =] 'value'

Specifies whether the option_name setting is TRUE (on) or FALSE (off). value is varchar(12), with a default of NULL, which lists the current settings for all matching tables.

Return Code Values

0 (success) or greater than 0 (failure)

Result Sets
Column name | Data type | Description
Available Index Options | nvarchar(35) | The options that are available.
Default Value | int | The default values for the options.

Permissions

Members of the sysadmin fixed server role or the db_owner fixed database role can modify the AllowRowLocks and AllowPageLocks options for any user-defined indexes. Other users can modify options only for tables they own.

Any user can run sp_indexoption to generate a report listing index option values for all user-defined indexes.

Examples

This example reports the available index options for the PK_Customers index on the Customers table in the Northwind database.

USE Northwind

EXEC sp_indexoption @IndexNamePattern = 'Customers.PK_Customers'

See Also

System Stored Procedures


sp_link_publication

Sets the configuration and security information used by synchronization triggers of immediate updating Subscribers when connecting to the Publisher.

Syntax

sp_link_publication [@publisher =] 'publisher',
[@publisher_db =] 'publisher_db', [@publication =] 'publication',
 [@security_mode =] security_mode [,[@login = ] 'login']
[,[@password =] 'password']

Arguments
[@publisher =] 'publisher'
Is the name of the Publisher to link to. publisher is sysname, with no default.
[@publisher_db =] 'publisher_db'
Is the name of the Publisher database to link to. publisher_db is sysname, with no default.
[@publication =] 'publication'
Is the name of the publication to link to. publication is sysname, with no default.
[@security_mode =] security_mode
Is the security mode used when linking to the Publisher. security_mode is int, with no default. If 0, the synchronization triggers use a dynamic RPC connection to the Publisher. If 2, the synchronization triggers use a static sysservers entry to do RPC, and publisher must be defined in the sysservers table as a remote server or linked server.
[@login =] 'login'
Is the login. login is sysname, with a default of NULL.
[@password =] 'password'
Is the password. password is sysname, with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_link_publication is used by immediate updating Subscribers in snapshot and transactional replication.

sp_link_publication can be used for both push and pull subscriptions. It can be called before or after the subscription is created. An entry is inserted or updated in the MSsubscription_properties system table. Use sp_helpsubscription_properties to view the values (publisher_security_mode, publisher_login, publisher_password) being set.

For push subscriptions, the entry can be cleaned up by sp_subscription_cleanup. For pull subscriptions, the entry can be cleaned up by sp_droppullsubscription or sp_subscription_cleanup. You can also call sp_link_publisher with a NULL password to clear the entry in the MSsubscription_properties system table for security concerns.

Permissions

Only members of the sysadmin fixed server role can execute sp_link_publication.

See Also
sp_droppullsubscription | sp_subscription_cleanup
sp_helpsubscription_properties | System Stored Procedures


sp_linkedservers

Returns the list of linked servers defined in the local server.

Syntax

sp_linkedservers

Return Code Values

0 (success) or a nonzero number (failure)

Result Sets
Column name | Data type | Description
SRV_NAME | sysname | Name of the linked server
SRV_PROVIDERNAME | nvarchar(128) | Friendly name of the OLE DB provider managing access to the specified linked server
SRV_PRODUCT | nvarchar(128) | Product name of the linked server
SRV_DATASOURCE | nvarchar(4000) | OLE DB data source property corresponding to the specified linked server
SRV_PROVIDERSTRING | nvarchar(4000) | OLE DB provider string property corresponding to the linked server
SRV_LOCATION | nvarchar(4000) | OLE DB location property corresponding to the specified linked server
SRV_CAT | sysname | OLE DB catalog property corresponding to the specified linked server

See Also
sp_catalogs | sp_tables_ex
sp_indexes | sp_column_privileges
sp_foreignkeys | sp_table_privileges
sp_primarykeys | System Stored Procedures
sp_columns_ex |


sp_lock

Reports information about locks.

Syntax

sp_lock [[@spid1 =] 'spid1'] [,[@spid2 =] 'spid2']

Arguments
[@spid1 =] 'spid1'
Is the Microsoft® SQL Server™ process ID number from master.dbo.sysprocesses. spid1 is int, with a default of NULL. Execute sp_who to obtain process information about the lock. If spid1 is not specified, information about all locks is displayed.
[@spid2 =] 'spid2'
Is another SQL Server process ID number to check for locks. spid2 is int, with a default of NULL.
Return Code Values

0 (success)

Result Sets
Column name | Data type | Description
spid | smallint | The SQL Server process ID number.
dbid | smallint | The database identification number requesting a lock.
ObjId | int | The object identification number of the object requesting a lock.
IndId | smallint | The index identification number.
Type | nchar(4) | The lock type: DB = Database FIL = File IDX = Index PG = PAGE KEY = Key TAB = Table EXT = Extent RID = Row identifier
Resource | nchar(16) | The lock resource that corresponds to the value in syslockinfo.restext.
Mode | nvarchar(8) | The lock requester’s lock mode. This lock mode represents the granted mode, the convert mode, or the waiting mode.
Status | int | The lock request status: GRANT WAIT CNVRT

Remarks

Users can control locking by adding an optimizer hint to the FROM clause of a SELECT statement or by setting the SET TRANSACTION ISOLATION LEVEL option. For syntax and restrictions, see SELECT and SET TRANSACTION ISOLATION LEVEL.

In general, read operations, acquire shared locks, and write operations acquire exclusive locks. Update locks are acquired during the initial portion of an update operation when the data is being read. Update locks are compatible with shared locks. Later, if the data is changed, the update locks are promoted to exclusive locks. There are times when changing data that an update lock is briefly acquired prior to an exclusive lock. This update lock will then be automatically promoted to an exclusive lock.

Different levels of data can be locked including an entire table, one or more pages of the table, and one or more rows of a table. Intent locks at a higher level of granularity mean locks are either being acquired or intending to be acquired at a lower level of lock granularity. For example, a table intent lock indicates the intention to acquire a shared or exclusive page level lock. An intent lock prevents another transaction from acquiring a table lock for that table.

An extent lock is held on a group of eight database pages while they are being allocated or freed. Extent locks are set while a CREATE or DROP statement is running or while an INSERT or UPDATE statement that requires new data or index pages is running.

When reading sp_lock information, use the OBJECT_NAME( ) function to get the name of a table from its ID number, for example:

SELECT object_name(16003088)

For information about using the Windows NT Performance Monitor to view information about a specific process ID, see the DBCC topics.

Permissions

Execute permissions default to the public role.

Examples
A. List all locks

This example displays information about all locks currently held in SQL Server.

USE master

EXEC sp_lock

B. List a lock from a single-server process

This example displays information about locks currently held on process ID 18.

USE master

EXEC sp_lock 18

See Also
DBCC | SET TRANSACTION ISOLATION LEVEL
Functions | sp_who
KILL | System Stored Procedures
SELECT |


sp_makewebtask

Creates a task that produces an HTML document containing data returned by executed queries.

Note All Web jobs are categorized as Web Assistant in the Job Categories dialog box in SQL Server Enterprise Manager.

Syntax

sp_makewebtask [@outputfile =] 'outputfile', [@query =] 'query'
[, [@fixedfont =] fixedfont]
[, [@bold =] bold]
[, [@italic =] italic]
[, [@colheaders =] colheaders]
[, [@lastupdated =] lastupdated]
[, [@HTMLHeader =] HTMLHeader]
[, [@username =] username]
[, [@dbname =] dbname]
[, [@templatefile =] 'templatefile']
[, [@webpagetitle =] 'webpagetitle']
[, [@resultstitle =] 'resultstitle']
[
[, [@URL =] 'URL', [@reftext =] 'reftext']
| [, [@table_urls =] table_urls, [@url_query =] 'url_query']
]
[, [@whentype =] whentype]
[, [@targetdate =] targetdate]
[, [@targettime =] targettime]
[, [@dayflags =] dayflags]
[, [@numunits =] numunits]
[, [@unittype =] unittype]
[, [@procname =] procname ]
[, [@maketask =] maketask]
[, [@rowcnt =] rowcnt]
[, [@tabborder =] tabborder]
[, [@singlerow =] singlerow]
[, [@blobfmt =] blobfmt]
[, [@nrowsperpage =] n]
[, [@datachg =] table_column_list]
[, [@charset =] characterset]
[, [@codepage =] codepage]

Arguments
[@outputfile =] 'outputfile'
Is the location of the generated HTML file on the computer running Microsoft® SQL Server™. It can be a UNC name if the file is to be created on a remote computer. outputfile is nvarchar(255), with no default.
[@query =] 'query'
Is the query to be run. query is ntext, with no default. Query results are displayed in the HTML document in a table format when the task is run with sp_runwebtask. Multiple SELECT queries can be specified and result in multiple tables being displayed in outputfile.
[@fixedfont =] fixedfont
Specifies that the query results be displayed in a fixed font (1) or a proportional font (0). fixedfont is tinyint, with a default of 1.
[@bold =] bold
Specifies that the query results be displayed in a bold font (1) or nonbold font (0). bold is tinyint, with a default of 0.
[@italic =] italic
Specifies that the query results be displayed in an italic font (1) or nonitalic font (0). italic is tinyint, with a default of 0.
[@colheaders =] colheaders
Specifies that the query results be displayed with column headers (1) or no column headers (0). colheaders is tinyint, with a default of 1.
[@lastupdated =] lastupdated
Specifies whether the generated HTML document displays a Last Updated: timestamp indicating the last updated date and time (1) or no timestamp (0). The timestamp appears one line before the query results in the HTML document. lastupdated is tinyint, with a default of 1.
[@HTMLHeader =] HTMLHeader
Specifies the HTML formatting code for displaying the text contained in resultstitle. HTMLHeader is tinyint, and can be one of these values.

Value | HTML formatting code
1 | H1
2 | H2
3 | H3
4 | H4
5 | H5
6 | H6

[@username =] username
Is the username for executing the query. username is narchar(128), with a default of the current user. The system administrator or database owner can specify another username.
[@dbname =] dbname
Is the database name to run the query on. dbname is nvarchar(128), with a default of the current database.
[@templatefile =] 'templatefile'
Is the path of the template file used to generate the HTML document. The template file contains information about the formatting characteristics for HTML documents and contains the tag <%insert_data_here%>, which indicates the position to which the query results will be added in an HTML table. templatefile is nvarchar(255).

There are two ways to specify the location of the results of a query in a template file:

  • Specify a general table format by including the <%insert_data_here%> marker, which indicates the position to add the query results in an HTML table. There are no spaces in the tag. When <%insert_data_here%> is used, the fixedfont, bold, italic, colheaders, and tabborders values are applied to the query results.
  • Specify a complete row format to produce a more precise layout. Use the <%begindetail%> and <%enddetail%> markers and define a complete row format between them with <TR>, </TR>, <TD>, and </TD> HTML tags. For each column to be displayed in the result set, insert the <%insert_data_here%> marker. When the complete row format is used, these sp_makewebtask parameters are ignored:

bold | lastupdated | table_urls
colheaders | reftext | URL
fixedfont | resultstitle | url_query
HTMLHeader | singlerow | webpagetitle
italic | tabborder

The extended procedure that is called by sp_makewebtask can read both Unicode and non-Unicode template files. If a Unicode file contains a signature header, the header is removed when the HTML file is generated.

[@webpagetitle =] 'webpagetitle'
Is the title of the HTML document. webpagetitle is nvarchar(255), with a default of SQL Server Web Assistant. For a blank title, specify two space characters for the title, or edit the HTML source to remove the <TITLE> and </TITLE> tags and the text of the title between the tags.
[@resultstitle =] 'resultstitle'
Is the title displayed above the query results in the HTML document. resultstitle is nvarchar(255), with a default of Query Results.
[@URL =] 'URL'
Is a hyperlink to another HTML document. The hyperlink is placed after the query results and at the end of the HTML document. URL is nvarchar(255). If URL is specified, reftext must also be specified, and table_urls and url_query cannot be specified.
[@reftext =] 'reftext'
Is the hyperlink that describes to which HTML document the hyperlink should take the user. reftext is nvarchar(255). The hyperlink text describes the destination and the hyperlink address comes from URL.
[@table_urls =] table_urls
Is whether hyperlinks are included on the HTML document and come from a SELECT statement executed on SQL Server. table_urls is tinyint, with a default of 0, which indicates that no query will generate hyperlinks. A value of 1 indicates that a list of hyperlinks will be created by using url_query.

Important If table_urls is 1, url_query must be included to specify the query to be executed for retrieving hyperlink information, and URL and reftext cannot be specified.

[@url_query =] 'url_query'
Is the SELECT statement to create the URL and its hyperlink text. URLs and hyperlink text come from a SQL Server table. With this parameter, multiple URLs with associated hyperlinks can be generated. Use url_query with table_urls. url_query is nvarchar(255). url_query must return a result set containing two columns: The first column is the address of a hyperlink, and the second column describes the hyperlink. The number of hyperlinks inserted into the HTML document equals the number of rows returned by executing url_query.
[@whentype =] whentype
Specifies when to run the task that creates the HTML document. whentype is tinyint, and can have these values.

Value | Description
1 (default) | Create page now. The Web job is created, executed immediately, and deleted immediately after execution.
2 | Create page later. The stored procedure for creating the HTML document is created immediately, but execution of the Web job is deferred until the date and time specified by targetdate and targettime (optional). If targettime is not specified, the Web job is executed at 12:00 A.M. targetdate is required when whentype is 2. This Web job is deleted automatically after the targeted date and time have passed.
3 | Create page every n day(s) of the week. The HTML document is created on day(s) specified in dayflags and at the time specified by targettime (optional), beginning with the date in targetdate. If targettime is omitted, the default is 12:00 A.M. targetdate is required when whentype is 3. The day(s) of the week are specified in dayflags, and more than one day of the week can be specified. Web jobs created with whentype is 3 are not deleted automatically and continue to run on the specified day(s) of the week until the user deletes them with sp_dropwebtask.
4 | Create page every n minutes, hours, days, or weeks. The HTML document is created every n time period beginning with the date and time specified in targetdate and targettime. If targettime is not specified, the Web job is executed at 12:00 A.M. targetdate is required in this case. The job runs automatically every n minutes, hours, days, or weeks as specified by numunits and unittype, and continues to run until the user deletes them with sp_dropwebtask.
5 | Create page upon request. The procedure is created without automatic scheduling. The user creates a HTML document by running sp_runwebtask and deletes it only with sp_dropwebtask.
6 | Create page now and later. The HTML document is created immediately and re-created, as when whentype is 2.
7 | Create page now and every n day(s) of the week. The HTML document is created immediately and re-created, as when whentype is 3, except targetdate is not required.
8 | Create page now and periodically thereafter. The HTML document is created immediately and re-created, as when whentype is 4, except targetdate is not required.
9 | Create page now and upon request. The HTML document is created immediately and re-created, as when whentype is 5. The task must be deleted manually.
10 | Create page now and when data changes. Creates the page immediately and later whenever the data in the table changes. datachg is required with this value.

Important SQL Server Agent must be running when a job is scheduled to run periodically; otherwise, the HTML page is not generated.

[@targetdate =] targetdate
Specifies the date the page should be built. The format is YYYYMMDD. When targetdate is omitted, the current date is used. If whentype is 2 (later), 3 (dayofweek), 4 (periodic), or 6 (now and later), targetdate is required. targetdate is int, with a default of 0.
[@targettime =] targettime
Specifies the time the HTML document should be created. targettime is int, with a default of 12:00 A.M. The format is HHMMSS.
[@dayflags =] dayflags
Specifies the day of the week to update the HTML document. dayflags is required when whentype is 3 (dayofweek) or 7 (now and dayofweek). dayflags is tinyint, and can be one of these values.

Value | Day of the week
1 (default) | Sunday
2 | Monday
4 | Tuesday
8 | Wednesday
16 | Thursday
32 | Friday
64 | Saturday

To specify multiple days, add the values. For example, to specify Monday and Thursday, set dayflags to 18.

[@numunits =] numunits
Specifies how often to update the HTML document. numunits is used only when whentype is 4 (periodic) or 8 (now and periodically thereafter). For example, if whentype is 4, numunits is 6, and unittype is 1 (hours), the specified HTML document is updated every six hours. numunits is tinyint, with a default of 1. Values can range from 1 through 255.
[@unittype =] unittype
Specifies how often the HTML document should be updated when numunits is 4 (periodic) or whentype is 8 (now and later). unittype is tinyint, and can be one of these values.

Value | Description
1 (default) | Hours
2 | Days
3 | Weeks
4 | Minutes

[@procname =] procname
Is the procedure or task name for the HTML document. If procname is not specified, the procedure name generated by sp_makewebtask is in the form of Web_YYMMDDHHMMSS<spid>. If procname is user-specified, the procedure name must meet the conditions for valid procedure names, and must be unique. procname is nvarchar(128). If procname is longer, it is truncated.
[@maketask =] maketask
Specifies whether a task should be created to execute an internal stored procedure that generates an HTML document. maketask is int, and can be one of these values.

Value | Description
0 | Generates an unencrypted stored procedure but does not create the task.
1 | Generates an encrypted stored procedure and generates the task.
2 (default) | Generates an unencrypted stored procedure and generates the task.

[@rowcnt =] rowcnt
Specifies the maximum number of rows to display in the generated HTML document. rowcnt is int, with a default of 0, which specifies that all rows satisfying the given query be displayed in the HTML document.
[@tabborder =] tabborder
Specifies whether a border should be drawn around the results table. tabborder is tinyint. If tabborder is 1 (the default), a border is drawn. If 0, no border is drawn.
[@singlerow =] singlerow
Specifies whether the results are to be displayed as one row per page. singlerow is tinyint. If singlerow is 0 (the default), all results appear on the same page and in the same table. If singlerow is 1, a new HTML page is generated for every qualifying row in the result set. Successive HTML pages are generated with a number appended to the specified output_filename. For example, if Web.html is specified as the output file name, pages are called Web1.html, Web2.html, and so on.
[@blobfmt =] blobfmt
Specifies whether all columns of ntext or image data types should be embedded in the same results page (NULL, the default), or whether these columns should be saved in another page and linked to the main HTML document by a URL. blobfmt is ntext or image.

To place the ntext or image data in a separate HTML page, use this format to specify a value for blobfmt:

"%n% FILE=output_filename TPLT=template_filename URL=url_link_name…"

where

n
Is the column number in the result list corresponding to a text field, and n+1 is the URL hyperlink text to the separate ntext or image HTML file.

Note Do not add spaces before or after the equal sign (=) and do not put file names in quotation marks (‘).

Output file names end with a number that indicates successive rows, similar to singlerow. output_filename is required, but template_filename and url_link_name are optional. The FILE = output_filename is the full path to the output file location. If provided, url_link_name is the http:// link to the file that is accessible through the World Wide Web. If url_link_name is not provided, the full physical file name preceded by the file:/// tag is used as the url_link_name. The same syntax in blobfmt (%n% FILE=…) can be repeated for multiple text or image columns.

If template_filename is provided, use the <%insert_data_here%> method to indicate the data insertion point.

The URL text is part of the result set and is always the column after the original ntext or image column. This URL text column is not displayed as a separate column in the result set.

[@nrowsperpage =] n
Specifies that the result set should be displayed in multiple pages of n rows in each page, and the successive pages are linked with NEXT and PREVIOUS URLs. n is int, with a default of 0, which means all results are to be displayed in a single page. If singlerow is specified, this parameter cannot be used.
[@datachg =] table_column_list
Is the list of table and optional column names that triggers the new page creation when the data changes. table_columns_list is ntext. The format of this value is:

{TABLE=name[COLUMN=name]}[,…]

This parameter is required when whentype is 10. With this option, three triggers (UPDATE, INSERT, and DELETE) are created on the specified table (and columns) executing the Web task when these triggers are fired. If there are preexisting triggers on the table, sp_runwebtask is added to the end of the trigger, provided that the trigger is not created with WITH ENCRYPTION, and the COLUMN field specification in this parameter is ignored. If there is an existing trigger on the table created with the WITH ENCRYPTION option, sp_makewebtask fails.

[@charset =] characterset
Is a character set alias code that is recognized by Microsoft Internet Explorer or compatible browsers. characterset is nvarchar(25) with a default value of N’utf-8’. characterset is used to specify a value for the META element charset tag in the .htm file.
[@codepage =] codepage
Is a numeric value corresponding to the character set. For example, code page 65001 corresponds to character set UTF-8. codepage is int with a default of 65001. For a complete list of supported code pages, use sp_enumcodepages.
Return Code Values

0 (success) or nonzero (failure)

Important The return code values have changed from earlier versions of Microsoft SQL Server.

Result Sets

None

Remarks

For scheduled tasks, all errors are reported in the Microsoft Windows NT® application log on the computer running SQL Server, and have a source of xpsqlweb.

Important The sp_dropwebtask, sp_makewebtask, and sp_runwebtask stored procedures can be run only on SQL Server versions 6.5 and later.

The SQL Server Web Assistant provides an interface for using the sp_makewebtask stored procedure. For more information about creating Web pages with the Web Assistant, see SQL Server Web Assistant.

Fonts available for HTML documents depend upon the capabilities of your Web browser software. Consult your browser software for information about font availability and HTML formatting.

Important All Microsoft Windows® 95/98 Web Assistant users must have user accounts in the database being used. Use sp_adduser to add accounts to each database a user may access. When running the Windows 95/98 operating system, an on-demand task can only be run by the task owner or the system administrator.

Permissions

The user must have SELECT permissions to run the specified query and CREATE PROCEDURE permissions in the database in which the query will run. The SQL Server account must have permissions to write the generated HTML document to the specified location. Only the members of the sysadmin fixed server role can impersonate other users.

Examples
A. Create multiple queries by using a template file

This example creates an HTML document and upon request and retrieves five book titles and prices, five author first and last names, five publisher names, and five author first and last names. In this document, placement of data is specified by the <%insert_data_here%> marker.

This section shows the template file named C:\Web\Multiple.tpl.

Note For this example to work properly, the template file code presented here must be saved in a file named C:\Web\Multiple.tpl. You must also create the C:\Web directory before saving the template in the C:\Web directory.

<HTML>

<HEAD>

<TITLE>SQL Server Multiple Queries with Template Web Sample</TITLE>

<BODY>

<H1>Books For Sale</H1>

<HR>

<P>

<TABLE BORDER>

<TR> <TH><I>Title</I></TH> <TH><B>Price</B></TH> </TR>

<%begindetail%>

<TR> <TD><I> <%insert_data_here%> </I> </TD>

    <TD ALIGN=RIGHT><B> $<%insert_data_here%></B></TD> </TR>

<%enddetail%>

</TABLE>

<P>

<HR>

<%insert_data_here%>

<P>

<TABLE BORDER>

<TR> <TH ALIGN=CENTER>ID</TH> <TH ALIGN=LEFT><I>Publiher's Name</I></TH> </TR>

<%begindetail%>

<TR> <TD> <%insert_data_here%> </TD>

    <TD ALIGN=LEFT><I> <%insert_data_here%></I></TD> </TR>

<%enddetail%>

</TABLE>

<HR>

<%insert_data_here%>

<P>

<A HREF = "http://www.microsoft.com">Microsoft</A><P>

<A HREF = "http://www.microsoft.com/msdn">MSDN</A><P>

</BODY>

</HTML>

This section of the example shows using sp_makewebtask to execute the query.

USE pubs

GO

EXECUTE sp_makewebtask @outputfile = 'C:\WEB\MULTIPLE.HTM',

@query = 'SELECT title, price FROM titles SELECT au_lname, au_fname
FROM authors SELECT pub_id, pub_name FROM publishers SELECT au_lname,
au_fname FROM authors', @templatefile = 'C:\WEB\MULTIPLE.TPL',

@dbname = 'pubs', @rowcnt = 5, @whentype = 9

GO

Here is the result set:

<HTML>

<HEAD>

<TITLE>SQL Server Multiple Queries with Template Web Sample</TITLE>

<BODY>

<H1>Books For Sale</H1>

<HR>

<P>

<TABLE BORDER>

<TR> <TH><I>Title</I></TH> <TH><B>Price</B></TH> </TR>

<TR> <TD><I> The Busy Executive's Database Guide </I> </TD>

    <TD ALIGN=RIGHT><B> $19.9900</B></TD> </TR>

<TR> <TD><I> Cooking with Computers: Surreptitious Balance Sheets </I> </TD>

    <TD ALIGN=RIGHT><B> $11.9500</B></TD> </TR>

<TR> <TD><I> You Can Combat Computer Stress! </I> </TD>

    <TD ALIGN=RIGHT><B> $2.9900</B></TD> </TR>

<TR> <TD><I> Straight Talk About Computers </I> </TD>

    <TD ALIGN=RIGHT><B> $19.9900</B></TD> </TR>

<TR> <TD><I> Silicon Valley Gastronomic Treats </I> </TD>

    <TD ALIGN=RIGHT><B> $19.9900</B></TD> </TR>

</TABLE>

<P>

<HR>

<P>

<P><TABLE BORDER=1>

<TR><TH ALIGN=LEFT>au_lname</TH><TH ALIGN=LEFT>au_fname</TH></TR>

<TR><TD><TT>Bennet</TT></TD><TD><TT>Abraham</TT></TD></TR>

<TR><TD><TT>Blotchet-Halls</TT></TD><TD><TT>Reginald</TT></TD></TR>

<TR><TD><TT>Carson</TT></TD><TD><TT>Cheryl</TT></TD></TR>

<TR><TD><TT>DeFrance</TT></TD><TD><TT>Michel</TT></TD></TR>

<TR><TD><TT>del Castillo</TT></TD><TD><TT>Innes</TT></TD></TR>

</TABLE>

<HR>

<P>

<TABLE BORDER>

<TR> <TH ALIGN=CENTER>ID</TH> <TH ALIGN=LEFT><I>Publiher's Name</I></TH> </TR>

<TR> <TD> 0736 </TD>

    <TD ALIGN=LEFT><I> New Moon Books</I></TD> </TR>

<TR> <TD> 0877 </TD>

    <TD ALIGN=LEFT><I> Binnet & Hardley</I></TD> </TR>

<TR> <TD> 1389 </TD>

    <TD ALIGN=LEFT><I> Algodata Infosystems</I></TD> </TR>

<TR> <TD> 1622 </TD>

    <TD ALIGN=LEFT><I> Five Lakes Publishing</I></TD> </TR>

<TR> <TD> 1756 </TD>

    <TD ALIGN=LEFT><I> Ramona Publishers</I></TD> </TR>

</TABLE>

<HR>

<P>

<P><TABLE BORDER=1>

<TR><TH ALIGN=LEFT>au_lname</TH><TH ALIGN=LEFT>au_fname</TH></TR>

<TR><TD><TT>Bennet</TT></TD><TD><TT>Abraham</TT></TD></TR>

<TR><TD><TT>Blotchet-Halls</TT></TD><TD><TT>Reginald</TT></TD></TR>

<TR><TD><TT>Carson</TT></TD><TD><TT>Cheryl</TT></TD></TR>

<TR><TD><TT>DeFrance</TT></TD><TD><TT>Michel</TT></TD></TR>

<TR><TD><TT>del Castillo</TT></TD><TD><TT>Innes</TT></TD></TR>

</TABLE>

<HR>

<P>

<A HREF = "http://www.microsoft.com">Microsoft</A><P>

<A HREF = "http://www.microsoft.com/msdn">MSDN</A><P>

</BODY>

</HTML>

B. Create hyperlinks

This example creates a two-column table called my_favorite_sites. The first column url_def is the URL to a specific Web location, and the second column display_text is the hyperlink text for the corresponding URL. After creating the table and filling it with values, the HTML document is created.

USE pubs

GO

CREATE TABLE my_favorite_web_sites(url_def varchar(255), display_text varchar(255) NULL)

GO

INSERT my_favorite_web_sites(url_def, display_text)
VALUES ('http://www.micsosoft.com', 'Microsoft Home Page')

INSERT my_favorite_web_sites(url_def) VALUES ('http://www.yahoo.com')

GO

EXECUTE sp_makewebtask @outputfile = 'C:\WEB\URL.HTM',
@query='SELECT title, price FROM titles ORDER BY price desc',
@table_urls = 1, @tabborder = 0, @lastupdated=0, @colheaders = 0,
@url_query= 'SELECT url_def, display_text FROM
my_favorite_web_sites', @whentype = 9

GO

Here is the result set:

<HTML>

<HEAD>

<TITLE>Microsoft SQL Server Web Assistant</TITLE>

</HEAD>

<BODY>

<H1>Query Results</H1>

<HR>

<P>

<P><TABLE BORDER=0>

<TR><TD><TT>But Is It User Friendly?</TT></TD><TD><TT>22.9500</TT></TD></TR>

<TR><TD><TT>Computer Phobic AND Non-Phobic Individuals: Behavior Variations</TT></TD><TD><TT>21.5900</TT></TD></TR>

<TR><TD><TT>Onions, Leeks, and Garlic: Cooking Secrets of the Mediterranean</TT></TD><TD><TT>20.9500</TT></TD></TR>

<TR><TD><TT>Secrets of Silicon Valley</TT></TD><TD><TT>20.0000</TT></TD></TR>

<TR><TD><TT>The Busy Executive's Database Guide</TT></TD><TD><TT>19.9900</TT></TD></TR>

<TR><TD><TT>Straight Talk About Computers</TT></TD><TD><TT>19.9900</TT></TD></TR>

<TR><TD><TT>Silicon Valley Gastronomic Treats</TT></TD><TD><TT>19.9900</TT></TD></TR>

<TR><TD><TT>Prolonged Data Deprivation: Four Case Studies</TT></TD><TD><TT>19.9900</TT></TD></TR>

<TR><TD><TT>Sushi, Anyone?</TT></TD><TD><TT>14.9900</TT></TD></TR>

<TR><TD><TT>Cooking with Computers: Surreptitious Balance Sheets</TT></TD><TD><TT>11.9500</TT></TD></TR>

<TR><TD><TT>Fifty Years in Buckingham Palace Kitchens</TT></TD><TD><TT>11.9500</TT></TD></TR>

<TR><TD><TT>Is Anger the Enemy?</TT></TD><TD><TT>10.9500</TT></TD></TR>

<TR><TD><TT>Emotional Security: A New Algorithm</TT></TD><TD><TT>7.9900</TT></TD></TR>

<TR><TD><TT>Life Without Fear</TT></TD><TD><TT>7.0000</TT></TD></TR>

<TR><TD><TT>You Can Combat Computer Stress!</TT></TD><TD><TT>2.9900</TT></TD></TR>

<TR><TD><TT>The Gourmet Microwave</TT></TD><TD><TT>2.9900</TT></TD></TR>

<TR><TD><TT>The Psychology of Computer Cooking</TT></TD><TD>n/a</TD></TR>

<TR><TD><TT>Net Etiquette</TT></TD><TD>n/a</TD></TR>

</TABLE>

<HR>

<A HREF = "http://www.micsosoft.com">Microsoft Home Page</A><P>

<A HREF = "http://www.yahoo.com">http://www.yahoo.com</A><P>

</BODY>

</HTML>

C. Execute multiple queries with single-row mode

This example creates eight HTML documents from multiple queries and uses the single-row mode.

This is the query:

USE pubs

GO

EXECUTE sp_makewebtask @outputfile = 'C:\WEB\SROW.HTM',
@query = 'SELECT title, price FROM titles ORDER BY price desc
SELECT au_lname, au_fname FROM authors WHERE state = ''CA'' ',
@fixedfont = 0, @webpagetitle = 'Single row SQL Web Assistant',
@resultstitle = 'One row per page results', @singlerow = 1,
@rowcnt = 4,@URL = "http://www.microsoft.com",
@reftext = 'Microsoft Home Page'

GO

This is the first file of the result set called C:\Web\Srow1.htm:

<HTML>

<HEAD>

<TITLE>Single row SQL Web Assistant</TITLE>

</HEAD>

<BODY>

<H1>One row per page results</H1>

<HR>

<PRE>Last updated: Jun 17 1997  9:14AM</PRE>

<P>

<P><TABLE BORDER=1>

<TR><TH ALIGN=LEFT>title</TH><TH ALIGN=LEFT>price</TH></TR>

<TR><TD>But Is It User Friendly?</TD><TD>22.9500</TD></TR>

</TABLE>

<HR>

<A HREF = "http://www.microsoft.com">Microsoft Home Page</A><P>

<TABLE BORDER=0 CELLPADDING=6>

<TR><TD>More results can be found in:</TD>

<TD><A HREF = "SROW2.HTM">Next</A></TD>

</TR></TABLE>

</BODY>

</HTML>

This is the second file of the result set called C:\Web\Srow2.htm:

<HTML>

<HEAD>

<TITLE>Single row SQL Web Assistant</TITLE>

</HEAD>

<BODY>

<H1>One row per page results</H1>

<HR>

<PRE>Last updated: Jun 17 1997  9:14AM</PRE>

<P>

<P><TABLE BORDER=1>

<TR><TH ALIGN=LEFT>title</TH><TH ALIGN=LEFT>price</TH></TR>

<TR><TD>Computer Phobic AND Non-Phobic Individuals: Behavior Variations</TD><TD>21.5900</TD></TR>

</TABLE>

<HR>

<A HREF = "http://www.microsoft.com">Microsoft Home Page</A><P>

<TABLE BORDER=0 CELLPADDING=6>

<TR><TD>More results can be found in:</TD>

<TD><A HREF = "SROW1.HTM">First</A></TD>

<TD><A HREF = "SROW1.HTM">Previous</A></TD>

<TD><A HREF = "SROW3.HTM">Next</A></TD>

</TR></TABLE>

</BODY>

</HTML>

D. Execute multiple queries using data insert markers and a template

This example creates two HTML documents from multiple queries by using a template that places each book title and price in separate HTML files.

This is the template file named C:\Web\Datains.tpl:

<HTML>

<HEAD>

<TITLE>SQL Server Multiple Queries, Data Insert Markers, & Template Web Sample</TITLE>

<BODY>

<H1>Books For Sale</H1>

<HR>

<P>

<TABLE BORDER>

<TR> <TH><I>Title</I></TH> <TH><B>Price</B></TH> </TR>

<%begindetail%>

<TR> <TD><I> <%insert_data_here%> </I> </TD>

    <TD ALIGN=RIGHT><B> $<%insert_data_here%></B></TD> </TR>

<%enddetail%>

</TABLE>

<P>

<HR>

<A HREF = "http://www.microsoft.com">Microsoft</A><P>

<A HREF = "http://www.microsoft.com/msdn">MSDN</A><P>

</BODY>

</HTML>

This is the query:

USE pubs

GO

EXECUTE sp_makewebtask @outputfile = 'C:\WEB\DATAINS.HTM',
@query = 'SELECT title, price FROM titles',
@templatefile = 'C:\WEB\DATAINS.TPL', @dbname = 'pubs',
@rowcnt = 2, @whentype = 9, @singlerow = 1

GO

This is the first file of the result set called C:\Web\Datains1.htm:

<HTML>

<HEAD>

<TITLE>SQL Server Multiple Queries, Data Insert Markers, & Template Web Sample</TITLE>

<BODY>

<H1>Books For Sale</H1>

<HR>

<P>

<TABLE BORDER>

<TR> <TH><I>Title</I></TH> <TH><B>Price</B></TH> </TR>

<TR> <TD><I> The Busy Executive's Database Guide </I> </TD>

    <TD ALIGN=RIGHT><B> $19.9900</B></TD> </TR>

</TABLE>

<P>

<HR>

<A HREF = "http://www.microsoft.com">Microsoft</A><P>

<A HREF = "http://www.microsoft.com/msdn">MSDN</A><P>

<TABLE BORDER=0 CELLPADDING=6>

<TR><TD>More results can be found in:</TD>

<TD><A HREF = "DATAINS2.HTM">Next</A></TD>

</TR></TABLE></BODY>

</HTML>

This is the second file of the result set called C:\Web\Datains2.htm:

<HTML>

<HEAD>

<TITLE>SQL Server Multiple Queries, Data Insert Markers, & Template Web Sample</TITLE>

<BODY>

<H1>Books For Sale</H1>

<HR>

<P>

<TABLE BORDER>

<TR> <TH><I>Title</I></TH> <TH><B>Price</B></TH> </TR>

<TR> <TD><I> Cooking with Computers: Surreptitious Balance Sheets </I> </TD>

    <TD ALIGN=RIGHT><B> $11.9500</B></TD> </TR>

</TABLE>

<P>

<HR>

<A HREF = "http://www.microsoft.com">Microsoft</A><P>

<A HREF = "http://www.microsoft.com/msdn">MSDN</A><P>

<TABLE BORDER=0 CELLPADDING=6>

<TR><TD>More results can be found in:</TD>

<TD><A HREF = "DATAINS1.HTM">First</A></TD>

<TD><A HREF = "DATAINS1.HTM">Previous</A></TD>

</TR></TABLE></BODY>

</HTML>

E. Execute query using @blobfmt

This example executes a single query and places the information in HTML documents. The publishers table is linked with the pub_info table to provide company logos in the HTML documents.

This is the template file called C:\Web\Blobsmp.tpl:

<HTML>

<HEAD>

<TITLE>Publishers PR Info</TITLE>

</HEAD>

<BODY>

<HR>

<PRE>

<%insert_data_here%>

</PRE>

</BODY>

</HTML>

This is the query:

USE pubs

GO

EXECUTE sp_makewebtask @outputfile = 'C:\WEB\BLOBSMP.HTM',
@query = 'SELECT pr_info, pub_name, city, state, country, logo,
pub_info.pub_id FROM pub_info, publishers
WHERE pub_info.pub_id = publishers.pub_id',
@webpagetitle = 'Publishers Home Page',
@resultstitle = 'Premier Publishers and Their Home Page Links',
@whentype = 9, @blobfmt='%1% FILE=C:\WEB\BLOBSMP.HTM
TPLT=C:\WEB\BLOBSMP.TPL %6% FILE=C:\WEB\PUBLOGO.GIF', @rowcnt = 2

GO

This is the main HTML document Blobsmp.htm, which contains hyperlinks to the logo bitmaps and to the Publisher’s Home Web pages:

<HTML>

<HEAD>

<TITLE>Publishers Home Page</TITLE>

<BODY>

<H1>Premier Publishers and Their Home Page Links</H1>

<HR>

<PRE><TT>Last updated: Jun 28 1996  3:15PM</TT></PRE>

<P>

<P><TABLE BORDER=1>

<TR><TH ALIGN=LEFT>pr_info</TH><TH ALIGN=LEFT>city</TH><TH ALIGN=LEFT>state</TH><TH ALIGN=LEFT>country</TH><TH ALIGN=LEFT>logo</TH></TR>

<TR><TD NOWRAP><A HREF = "file:///c:\web\blobfmt1.htm">New Moon Books</A></TD><TD NOWRAP><TT>Boston</TT></TD><TD NOWRAP><TT>MA</TT></TD><TD NOWRAP><TT>USA</TT></TD><TD NOWRAP><A HREF = "file:///c:\web\publogo1.gif">0736</A></TD></TR>

<TR><TD NOWRAP><A HREF = "file:///c:\web\blobfmt2.htm">Binnet & Hardley</A></TD><TD NOWRAP><TT>Washington</TT></TD><TD NOWRAP><TT>DC</TT></TD><TD NOWRAP><TT>USA</TT></TD><TD NOWRAP><A HREF = "file:///c:\web\publogo2.gif">0877</A></TD></TR>

</TABLE>

<HR>

</BODY>

</HTML>

Here are the first few lines of the first file of the result set called C:\Web\Blobsmp1.htm:

Note Not all output lines are shown here. Complete output appears in C:\Web\Blobsmp1.htm.

<HTML>

<HEAD>

<TITLE>Publishers PR Info</TITLE>

</HEAD>

<BODY>

<HR>

<PRE>

This is sample text data for New Moon Books, publisher 0736 in the pubs database. New Moon Books is located in Boston, Massachusetts.

…

This is sample text data for New Moon Books, publisher 0736 in the pubs database. New Moon Boo

</PRE>

</BODY>

</HTML>

This is the second file of the result set called C:\Web\Blobsmp2.htm:

<HTML>

<HEAD>

<TITLE>Publishers PR Info</TITLE>

</HEAD>

<BODY>

<HR>

<PRE>

This is sample text data for Binnet & Hardley, publisher 0877 in the pubs database. Binnet & Hardley is located in Washington, D.C.

…

This is sample text data for Binnet & Hardley, publisher 0877 in the pubs database. Binnet & Hardley is located in Washington, D.C.

</PRE>

</BODY>

</HTML>

See Also
sp_enumcodepages | System Stored Procedures
sp_runwebtask |


sp_manage_jobs_by_login

Deletes or reassigns jobs belonging to the specified login.

Syntax

sp_manage_jobs_by_login [@action =] 'action'
[, [@current_owner_login_name =] 'current_owner_login_name']
[, [@new_owner_login_name =] 'new_owner_login_name']

Arguments
[@action =] 'action'
Is the action to take for the specified login. action is varchar(10), with no default. When action is DELETE, sp_manage_jobs_by_login deletes all jobs owned by current_owner_login_name. When action is REASSIGN, all jobs are assigned to new_owner_login_name.
[@current_owner_login_name =] 'current_owner_login_name'
Is the login name of the current job owner. current_owner_login_name is sysname, with no default.
[@new_owner_login_name =] 'new_owner_login_name'
Is the login name of the new job owner. Use this parameter only if action is REASSIGN. new_owner_login_name is sysname, with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Permissions

Only members of the sysadmin fixed server role can execute sp_manage_jobs_by_login.

Examples

This example reassigns all jobs from janetl to stevenb.

USE msdb

EXEC sp_manage_jobs_by_login 'REASSIGN', 'janetl', 'stevenb'

See Also
sp_delete_job System Stored Procedures


sp_mergedummyupdate

Does a dummy update on the given row so that it will be sent again during the next merge.

Syntax

sp_mergedummyupdate [@source_object =] 'source_object',
[@rowguid =] 'rowguid'

Arguments
[@source_object =] 'source_object'
Is the name of the source object. source_object is nvarchar(386), with no default.
[@rowguid =] 'rowguid'
Is the row identifier. rowguid is uniqueidentifier, with no default.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_mergedummyupdate is used in merge replication.

sp_mergedummyupdate is useful if you write your own alternative to the Replication Conflict Viewer (Wzcnflct.exe).

Permissions

Only members of the db_owner fixed database role can execute sp_mergedummyupdate.

See Also
System Stored Procedures


sp_mergesubscription_cleanup

Removes metadata such as triggers and entries in sysmergesubscription and sysmergearticles when a merge subscription is dropped at a Subscriber.

Syntax

sp_mergesubscription_cleanup [@publisher =] 'publisher',
[@publisher_db =] 'publisher_db' [,[@publication =] 'publication']

Arguments
[@publisher =] 'publisher'
Is the name of the Publisher. publisher is sysname, with no default.
[@publisher_db =] 'publisher_db'
Is the name of the Publisher database. publisher_db is sysname, with no default.
[@publication =] 'publication'
Is the name of the publication. publication is sysname, with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_mergesubscription_cleanup is used in merge replication.

sp_mergesubscription_cleanup periodically checks the status of all the subscriptions of every merge publication. If any of them is out-of-date, that is, has lost contact with the Publisher for too long a period, the publication is declared expired and the traces of the subscription are cleaned up at the Publisher.

Permissions

Only members of the sysadmin fixed server role or the db_owner fixed database role can execute sp_mergesubscription_cleanup.

See Also
System Stored Procedures


sp_monitor

Displays statistics about Microsoft® SQL Server™.

Syntax

sp_monitor

Return Code Values

0 (success) or 1 (failure)

Result Sets
Column name | Description
last_run | Time sp_monitor was last run
current_run | Time sp_monitor is being run
seconds | Number of elapsed seconds since sp_monitor was run
cpu_busy | Number of seconds that the server computer’s CPU has been doing SQL Server work
io_busy | Number of seconds that SQL Server has spent doing input and output operations
idle | Number of seconds that SQL Server has been idle
packets_received | Number of input packets read by SQL Server
packets_sent | Number of output packets written by SQL Server
packet_errors | Number of errors encountered by SQL Server while reading and writing packets
total_read | Number of reads by SQL Server
total_write | Number of writes by SQL Server
total_errors | Number of errors encountered by SQL Server while reading and writing
connections | Number of logins or attempted logins to SQL Server

Remarks

SQL Server keeps track, through a series of functions, of how much work it has done. Executing sp_monitor displays the current values returned by these functions and shows how much they have changed since the last time the procedure was run.

For each column, the statistic is printed in the form number(number)-number% or number(number). The first number refers to the number of seconds (for cpu_busy, io_busy, and idle) or the total number (for the other variables) since SQL Server was restarted. The number in parentheses refers to the number of seconds or total number since the last time sp_monitor was run. The percentage is the percentage of time since sp_monitor was last run. For example, if the report shows cpu_busy as 4250(215)-68%, the CPU has been busy 4250 seconds since SQL Server was last started up, 215 seconds since sp_monitor was last run, and 68 percent of the total time since sp_monitor was last run.

Permissions

Execute permissions default to members of the sysadmin fixed server role.

Examples

This example reports information about how busy SQL Server has been.

USE master

EXEC sp_monitor

Here is the result set:

last_run | current_run | seconds
------------------ | -------------------- | -------------
Mar 29 1998 11:55AM | Apr 4 1993 2:22 PM | 561

cpu_busy | io_busy | idle
----------------- | --------------- | -------------
190(0)-0% | 187(0)-0% | 148(556)-99%

packets_received | packets_sent | packet_errors
----------------- | ----------------- | -------------
16(1) | 20(2) | 0(0)

total_read | total_write | total_errors | connections
----------------- | ----------------- | ------------- | ------------
141(0) | 54920(127) | 0(0) | 4(0)

See Also
sp_who System Stored Procedures


sp_msx_defect

Removes the current server from multiserver operations.

Caution sp_msx_defect edits the registry. Manual editing of the registry is not recommended because inappropriate or incorrect changes can cause serious configuration problems for your system. Therefore, only experienced users should use the Registry Editor program to edit the registry. For more information, see your Microsoft® Windows NT® or Microsoft Windows® 95 documentation.

Syntax

sp_msx_defect [@forced_defection =] forced_defection

Argument
[@forced_defection =] forced_defection
Is whether or not to force the defection to occur if the Master SQL Server Agent has been permanently lost due to an irreversibly corrupt msdb database, or no msdb database backup. forced_defection is bit, with a default of 0, which indicates that no forced defection should occur. A value of 1 forces defection.

Note After forcing a defection by executing sp_msx_defect, a member of the sysadmin fixed server role at the Master SQL Server Agent must run the following command to complete the defection:

EXECUTE msdb.dbo.sp_delete_targetserver @server_name = 'tsx-server', @post_defection =  0

Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

When sp_msx_defect properly completes, a message is returned:

Server defected from MSX ''. n Job(s) deleted.

Permissions

Only members of the sysadmin fixed server role can execute sp_msx_defect.

See Also
sp_msx_enlist System Stored Procedures


sp_msx_enlist

Adds the current server to the list of target servers available for multiserver operations.

Caution sp_msx_enlist edits the registry. Manual editing of the registry is not recommended because inappropriate or incorrect changes can cause serious configuration problems for your system. Therefore, only experienced users should use the Registry Editor program to edit the registry. For more information, see your Microsoft® Windows NT® or Microsoft Windows® 95 documentation.

Syntax

sp_msx_enlist [@msx_server_name =] 'msx_server'
[, [@location =] 'location']

Arguments
[@msx_server_name =] 'msx_server'
Is the name of the multiserver administration server (master server) to add. msx_server is nvarchar(30), with no default.
[@location =] 'location'
Is the location of the target server that is enlisting. location is nvarchar(100), with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Permissions

Only members of the sysadmin fixed server role can execute sp_msx_enlist.

Examples

This example enlists the current server into the LONDON2 master server.

USE msdb

EXEC sp_msx_enlist 'LONDON2',
    'Paris Subsidiary, Bldg 21, Room 309, Rack 5'

See Also
sp_msx_defect | System Stored Procedures
xp_cmdshell |


sp_OACreate

Creates an instance of the OLE object on the computer running Microsoft® SQL Server™.

Syntax

sp_OACreate progid, | clsid,
objecttoken OUTPUT
[, context]

Arguments
progid
Is the programmatic identifier (ProgID) of the OLE object to create. This character string describes the class of the OLE object and has the form:

'OLEComponent.Object'

OLEComponent is the component name of the OLE Automation server, and Object is the name of the OLE object. The specified OLE object must be valid and must support the IDispatch interface.

For example, SQLDMO.SQLServer is the ProgID of the SQL-DMO SQLServer object. SQL-DMO has a component name of SQLDMO, the SQLServer object is valid, and (like all SQL-DMO objects) the SQLServer object supports IDispatch.

clsid
Is the class identifier (CLSID) of the OLE object to create. This character string describes the class of the OLE object and has the form:

'{nnnnnnnn-nnnn-nnnn-nnnn-nnnnnnnnnnnn}'

The specified OLE object must be valid and must support the IDispatch interface.

For example, {00026BA1-0000-0000-C000-000000000046} is the CLSID of the SQL-DMO SQLServer object.

objecttoken OUTPUT
Is the returned object token, and must be a local variable of data type int. This object token identifies the created OLE object and is used in calls to the other OLE Automation stored procedures.
context
Specifies the execution context in which the newly created OLE object runs. If specified, this value must be one of the following:

1 = In-process (.dll) OLE server only
4 = Local (.exe) OLE server only
5 = Both in-process and local OLE server allowed

If not specified, the default value is 5. This value is passed as the dwClsContext parameter of the call to CoCreateInstance.

If an in-process OLE server is allowed (by using a context value of 1 or 5 or by not specifying a context value), it has access to memory and other resources owned by SQL Server. An in-process OLE server may damage SQL Server memory or resources and cause unpredictable results, such as a SQL Server access violation.

When you specify a context value of 4, a local OLE server does not have access to any SQL Server resources, and it cannot damage SQL Server memory or resources.

Note The parameters for this stored procedure are specified by position, not name.

Return Code Values

0 (success) or a nonzero number (failure) that is the integer value of the HRESULT returned by the OLE Automation object.

Result Sets

None

Remarks

The created OLE object is automatically destroyed at the end of the Transact-SQL statement batch.

Examples
A. Use Prog ID

This example creates a SQL-DMO SQLServer object by using its ProgID.

DECLARE @object int

DECLARE @hr int

EXEC @hr = sp_OACreate 'SQLDMO.SQLServer', @object OUT

IF @hr <> 0

BEGIN

    EXEC sp_displayoaerrorinfo @object, @hr

    RETURN

END

B. Use CLSID

This example creates a SQL-DMO SQLServer object by using its CLSID.

DECLARE @object int

DECLARE @hr int

EXEC @hr = sp_OACreate '{00026BA1-0000-0000-C000-000000000046}',

    @object OUT

IF @hr <> 0

BEGIN

    EXEC sp_displayoaerrorinfo @object, @hr

    RETURN

END

See Also
System Stored Procedures (OLE Automation Extended Stored Procedures)


sp_OADestroy

Destroys a created OLE object.

Syntax

sp_OADestroy objecttoken

Arguments
objecttoken
Is the object token of an OLE object previously created by sp_OACreate.
Return Code Values

0 (success) or a nonzero number (failure) that is the integer value of the HRESULT returned by the OLE Automation object.

Result Sets

None

Remarks

If sp_OADestroy is not called, the created OLE object is automatically destroyed at the end of the batch.

Examples

This example destroys the previously created SQLServer object.

EXEC @hr = sp_OADestroy @object

IF @hr <> 0

BEGIN

    EXEC sp_displayoaerrorinfo @object, @hr

    RETURN

END

See Also
System Stored Procedures (OLE Automation Extended Stored Procedures)


sp_OAGetErrorInfo

Obtains OLE Automation error information.

Syntax

sp_OAGetErrorInfo [objecttoken ]
[, source OUTPUT]
[, description OUTPUT]
[, helpfile OUTPUT]
[, helpid OUTPUT]

Arguments
objecttoken
Is either the object token of an OLE object previously created by sp_OACreate or it is NULL. If objecttoken is specified, error information for that object is returned. If NULL is specified, the error information for the entire batch is returned.
source OUTPUT
Is the source of the error information. If specified, it must be a local char or varchar variable. The return value is truncated to fit the local variable if necessary.
description OUTPUT
Is the description of the error. If specified, it must be a local char or varchar variable. The return value is truncated to fit the local variable if necessary.
helpfile OUTPUT
Is the Help file for the OLE object. If specified, it must be a local char or varchar variable. The return value is truncated to fit the local variable if necessary.
helpid OUTPUT
Is the Help file context ID. If specified, it must be a local int variable.

Note The parameters for this stored procedure are specified by position, not name.

Return Code Values

0 (success) or a nonzero number (failure) that is the integer value of the HRESULT returned by the OLE Automation object.

Result Sets

If no output parameters are specified, the error information is returned to the client as a result set.

Column names | Data type | Description
Error | binary(4) | Binary representation of the error number
Source | varchar(nn) | Source of the error
Description | varchar(nn) | Description of the error
Helpfile | varchar(nn) | Help file for the source
HelpID | int | Help context ID in the Help source file

Remarks

Each call to an OLE Automation stored procedure (except sp_OAGetErrorInfo) resets the error information; therefore, sp_OAGetErrorInfo obtains error information only for the most recent OLE Automation stored procedure call. Note that because sp_OAGetErrorInfo does not reset the error information, it can be called multiple times to get the same error information.

This table lists OLE Automation errors and their common causes.

Error and HRESULT | Common cause
Bad variable type (0x80020008) | Data type of a Transact-SQL value passed as a method parameter did not match the Microsoft® Visual Basic® data type of the method parameter, or a NULL value was passed as a method parameter.
Unknown name (0x8002006) | Specified property or method name was not found for the specified object.
Invalid class string (0x800401f3) | Specified ProgID or CLSID has not been registered as an OLE object on the computer running Microsoft SQL Server™.
Server execution failed (0x80080005) | Specified OLE object is registered as a local OLE server (.exe file) but the .exe file could not be found or started.
The specified module could not be found (0x8007007e) | Specified OLE object is registered as an in-process OLE server (.dll file), but the .dll file could not be found or loaded.
Type mismatch (0x80020005) | Data type of a Transact-SQL local variable used to store a returned property value or a method return value did not match the Visual Basic data type of the property or method return value. Or, the return value of a property or a method was requested, but it does not return a value.
Parameter not found (0x80020004) | Named parameter was specified before a positional parameter. Ensure that all named parameters are specified after all positional parameters.
The parameter is incorrect (0x80070057) | Number specified as the context parameter of sp_OACreate was not valid.

Examples

This example displays OLE Automation error information.

DECLARE @output varchar(255)

DECLARE @hr int

DECLARE @source varchar(255)

DECLARE @description varchar(255)

PRINT 'OLE Automation Error Information'

EXEC @hr = sp_OAGetErrorInfo @object, @source OUT, @description OUT

IF @hr = 0

BEGIN

    SELECT @output = '  Source: ' + @source

    PRINT @output

    SELECT @output = '  Description: ' + @description

    PRINT @output

END

ELSE

BEGIN

    PRINT '  sp_OAGetErrorInfo failed.'

    RETURN

END

See Also
System Stored Procedures (OLE Automation Extended Stored Procedures)


sp_OAGetProperty

Gets a property value of an OLE object.

Syntax

sp_OAGetProperty objecttoken,
propertyname
[, propertyvalue OUTPUT]
[, index…]

Arguments
objecttoken
Is the object token of an OLE object previously created by sp_OACreate.
propertyname
Is the property name of the OLE object to return.
propertyvalue OUTPUT
Is the returned property value. If specified, it must be a local variable of the appropriate data type.

If the property returns an OLE object, propertyvalue must be a local variable of data type int. An object token is stored in the local variable, and this object token can be used with other OLE Automation stored procedures.

If the property returns a single value, either specify a local variable for propertyvalue, which returns the property value in the local variable, or do not specify propertyvalue, which returns the property value to the client as a single-column, single-row result set.

When the property returns an array, if propertyvalue is specified, it is set to NULL.

If propertyvalue is specified, but the property does not return a value, an error occurs. If the property returns an array with more than two dimensions, an error occurs.

index
Is an index parameter. If specified, it must be a value of the appropriate data type.

Some properties have parameters. These properties are called indexed properties, and the parameters are called index parameters. A property can have multiple index parameters.

Note The parameters for this stored procedure are specified by position, not name.

Return Code Values

0 (success) or a nonzero number (failure) that is the integer value of the HRESULT returned by the OLE Automation object.

Result Sets

If the property returns an array with one or two dimensions, the array is returned to the client as a result set:

  • A one-dimensional array is returned to the client as a single-row result set with as many columns as there are elements in the array. In other words, the array is returned as (columns).
  • A two-dimensional array is returned to the client as a result set with as many columns as there are elements in the first dimension of the array and with as many rows as there are elements in the second dimension of the array. In other words, the array is returned as (columns, rows).

When a property return value or method return value is an array, sp_OAGetProperty or sp_OAMethod returns a result set to the client. (Method output parameters cannot be arrays.) These procedures scan all the data values in the array to determine the appropriate Microsoft® SQL Server™ data types and data lengths to use for each column in the result set. For a particular column, these procedures use the data type and length required to represent all data values in that column.

When all data values in a column share the same data type, that data type is used for the whole column. When data values in a column use different data types, the data type of the whole column is chosen based on the following chart.

 | int | float | money | datetime | varchar
int | int | float | money | varchar | varchar
float | float | float | money | varchar | varchar
money | money | money | money | varchar | varchar
datetime | varchar | varchar | varchar | datetime | varchar
varchar | varchar | varchar | varchar | varchar | varchar

Remarks

You can also use sp_OAMethod to get a property value.

Examples
A. Use local variable

This example gets the HostName property (of the previously created SQLServer object) and stores it in a local variable.

DECLARE @property varchar(255)

EXEC @hr = sp_OAGetProperty @object, 'HostName', @property OUT

IF @hr <> 0

BEGIN

    EXEC sp_displayoaerrorinfo @object, @hr

    RETURN

END

PRINT @property

B. Use result set

This example gets the HostName property (of the previously created SQLServer object) and returns it to the client as a result set.

EXEC @hr = sp_OAGetProperty @object, 'HostName'

IF @hr <> 0

BEGIN

    EXEC sp_displayoaerrorinfo @object, @hr

    RETURN

END

See Also
System Stored Procedures (OLE Automation Extended Stored Procedures)


sp_OAMethod

Calls a method of an OLE object.

Syntax

sp_OAMethod objecttoken,
methodname
[, returnvalue OUTPUT]
[, [@parametername =] parameter [OUTPUT]
[…n]]

Arguments
objecttoken
Is the object token of an OLE object previously created by sp_OACreate.
methodname
Is the method name of the OLE object to call.
returnvalue OUTPUT
Is the return value of the method of the OLE object. If specified, it must be a local variable of the appropriate data type.

If the method returns a single value, either specify a local variable for returnvalue, which returns the method return value in the local variable, or do not specify returnvalue, which returns the method return value to the client as a single-column, single-row result set.

If the method return value is an OLE object, returnvalue must be a local variable of data type int. An object token is stored in the local variable, and this object token can be used with other OLE Automation stored procedures.

When the method return value is an array, if returnvalue is specified, it is set to NULL.

An error occurs when:

  • returnvalue is specified, but the method does not return a value.
  • The method returns an array with more than two dimensions.
  • The method returns an array as an output parameter.
[@parametername =] parameter [OUTPUT]
Is a method parameter. If specified, parameter must be a value of the appropriate data type.

To obtain the return value of an output parameter, parameter must be a local variable of the appropriate data type, and OUTPUT must be specified. If a constant parameter is specified, or if OUTPUT is not specified, any return value from an output parameter is ignored.

If specified, parametername must be the name of the Microsoft® Visual Basic® named parameter. Note that @parametername is not a Transact-SQL local variable. The at sign (@) is removed, and parametername is passed to the OLE object as the parameter name. All named parameters must be specified after all positional parameters are specified.

n
Is a placeholder indicating that multiple parameters can be specified.

Note @parametername can be a named parameter because it is part of the specified method and is passed through to the object. The other parameters for this stored procedure are specified by position, not name.

Return Code Values

0 (success) or a nonzero number (failure) that is the integer value of the HRESULT returned by the OLE Automation object.

Result Sets

If the method return value is an array with one or two dimensions, the array is returned to the client as a result set:

  • A one-dimensional array is returned to the client as a single-row result set with as many columns as there are elements in the array. In other words, the array is returned as (columns).
  • A two-dimensional array is returned to the client as a result set with as many columns as there are elements in the first dimension of the array and with as many rows as there are elements in the second dimension of the array. In other words, the array is returned as (columns, rows).

When a property return value or method return value is an array, sp_OAGetProperty or sp_OAMethod returns a result set to the client. (Method output parameters cannot be arrays.) These procedures scan all the data values in the array to determine the appropriate Microsoft SQL Server™ data types and data lengths to use for each column in the result set. For a particular column, these procedures use the data type and length required to represent all data values in that column.

When all data values in a column share the same data type, that data type is used for the whole column. When data values in a column use different data types, the data type of the whole column is chosen based on the following chart.

 | int | float | money | datetime | varchar
int | int | float | money | varchar | varchar
float | float | float | money | varchar | varchar
money | money | money | money | varchar | varchar
datetime | varchar | varchar | varchar | datetime | varchar
varchar | varchar | varchar | varchar | varchar | varchar

Remarks

You can also use sp_OAMethod to get a property value.

Examples
A. Call a method

This example calls the Connect method of the previously created SQLServer object.

EXEC @hr = sp_OAMethod @object, 'Connect', NULL, 'my_server',

    'my_login', 'my_password'

IF @hr <> 0

BEGIN

    EXEC sp_displayoaerrorinfo @object, @hr

    RETURN

END

B. Get a property

This example gets the HostName property (of the previously created SQLServer object) and stores it in a local variable.

DECLARE @property varchar(255)

EXEC @hr = sp_OAMethod @object, 'HostName', @property OUT

IF @hr <> 0

BEGIN

    EXEC sp_displayoaerrorinfo @object, @hr

    RETURN

END

PRINT @property

See Also
System Stored Procedures (OLE Automation Extended Stored Procedures)


sp_OASetProperty

Sets a property of an OLE object to a new value.

Syntax

sp_OASetProperty objecttoken,
propertyname,
newvalue
[, index…]

Arguments
objecttoken
Is the object token of an OLE object previously created by sp_OACreate.
propertyname
Is the property name of the OLE object to set to a new value.
newvalue
Is the new value of the property, and must be a value of the appropriate data type.
index
Is an index parameter. If specified, it must be a value of the appropriate data type.

Some properties have parameters. These properties are called indexed properties, and the parameters are called index parameters. A property can have multiple index parameters.

Note The parameters for this stored procedure are specified by position, not name.

Return Code Values

0 (success) or a nonzero number (failure) that is the integer value of the HRESULT returned by the OLE Automation object.

Result Sets

None

Examples

This example sets the HostName property (of the previously created SQLServer object) to a new value.

EXEC @hr = sp_OASetProperty @object, 'HostName', 'Gizmo'

IF @hr <> 0

BEGIN

    EXEC sp_displayoaerrorinfo @object, @hr

    RETURN

END

See Also
System Stored Procedures (OLE Automation Extended Stored Procedures)


sp_OAStop

Stops the server-wide OLE Automation stored procedure execution environment.

Syntax

sp_OAStop

Return Code Values

0 (success) or a nonzero number (failure) that is the integer value of the HRESULT returned by the OLE Automation object.

Result Sets

None

Remarks

After Microsoft® SQL Server™ is started, the shared OLE Automation stored procedure execution environment is automatically started when sp_OACreate is first called by a client. A single execution environment is shared by all clients using the OLE Automation stored procedures.

It is not necessary to call sp_OAStop. If sp_OAStop is not called, the execution environment is automatically stopped when SQL Server is shut down. After the execution environment has been stopped, any call to sp_OACreate restarts the execution environment.

Note If one client calls sp_OAStop to stop the execution environment, any client currently executing a statement batch that uses the OLE Automation stored procedures receives an error message when any OLE Automation stored procedure (except sp_OACreate) is called.

Examples

This example stops the shared OLE Automation execution environment.

EXEC sp_OAStop

See Also
System Stored Procedures (OLE Automation Extended Stored Procedures)


sp_password

Adds or changes a password for a Microsoft® SQL Server™ login.

Syntax

sp_password [[@old =] 'old_password',] {[@new =] 'new_password'}
[,[@loginame =] 'login']

Arguments
[@old =] 'old_password'
Is the old password. old_password is sysname, with a default of NULL.
[@new =] 'new_password'
Is the new password. new_password is sysname, with no default. old_password must be specified if named parameters are not used.
[@loginame =] 'login'
Is the name of the login affected by the password change. login is sysname, with a default of NULL. login must already exist and can only be specified by a member of the sysadmin fixed server role.
Return Code Values

0 (success) or 1 (failure)

Remarks

SQL Server passwords can contain from 1 to 128 characters, including any letters, symbols, and numbers.

The new password is updated and stored in an encrypted form so that no user, not even system administrators, can view the password.

sp_password cannot be used with Microsoft Windows NT® security accounts. Users connecting to SQL Server through their Windows NT network account are authenticated by Windows NT, therefore their passwords can be changed only in Windows NT.

sp_password cannot be executed within a user-defined transaction.

Permissions

Execute permissions default to the public role for a user changing the password for his or her own login. Only members of the sysadmin role can change the password for another user’s login.

Examples
A. Change the password of a login without the former password

This example changes the password for the login Victoria to ok.

EXEC sp_password NULL, 'ok', 'Victoria'

B. Change a password

This example changes the password for the login Victoria from ok to coffee.

EXEC sp_password 'ok', 'coffee'

See Also
sp_addlogin | sp_revokelogin
sp_adduser | System Stored Procedures
sp_grantlogin |


sp_pkeys

Returns primary key information for a single table in the current environment.

Syntax

sp_pkeys [@table_name =] 'name'
[,[@table_owner =] 'owner']
[,[@table_qualifier =] 'qualifier']

Arguments
[@table_name =] 'name'
Is the table for which to return information. name is sysname, with no default. Wildcard pattern matching is not supported.
[@table_owner =] 'owner'
Specifies the table owner of the specified table. owner is sysname, with a default of NULL. Wildcard pattern matching is not supported. If owner is not specified, the default table visibility rules of the underlying DBMS apply.

In Microsoft® SQL Server™, if the current user owns a table with the specified name, the columns of that table are returned. If the owner is not specified and the current user does not own a table with the specified name, this procedure looks for a table with the specified name owned by the database owner. If one exists, the columns of that table are returned.

[@table_qualifier =] 'qualifier'
Is the table qualifier. qualifier is sysname, with a default of NULL. Various DBMS products support three-part naming for tables (qualifier.owner.name). In SQL Server, this column represents the database name. In some products, it represents the server name of the database environment of the table.
Return Code Values

None

Result Sets
Column name | Data type | Description
TABLE_QUALIFIER | sysname | Name of the table qualifier. This field can be NULL.
TABLE_OWNER | sysname | Name of the table owner. This field always returns a value.
TABLE_NAME | sysname | Name of the table. In SQL Server, this column represents the table name as listed in the sysobjects table. This field always returns a value.
COLUMN_NAME | sysname | Name of the column, for each column of the TABLE_NAME returned. In SQL Server, this column represents the column name as listed in the syscolumns table. This field always returns a value.
KEY_SEQ | smallint | Sequence number of the column in a multicolumn primary key.
PK_NAME | sysname | Primary key identifier. Returns NULL if not applicable to the data source.

Remarks

sp_pkeys returns information about columns explicitly defined with a PRIMARY KEY constraint. Because not all systems support explicitly named primary keys, the gateway implementer determines what constitutes a primary key. Note that the term primary key refers to a logical primary key for a table. It is expected that every key listed as being a logical primary key has a unique index defined on it. This unique index is also returned in sp_statistics.

The sp_pkeys stored procedure is equivalent to SQLPrimaryKeys in ODBC. The results returned are ordered by TABLE_QUALIFIER, TABLE_OWNER, TABLE_NAME, and KEY_SEQ.

Permissions

Execute permissions default to the public role.


sp_primarykeys

Returns the primary key columns, one row per key column, for the specified remote table.

Syntax

sp_primarykeys [@table_server =] 'table_server'
[,[@table_name =] 'table_name']
[,[@table_schema =] 'table_schema']
[,[@table_catalog =] 'table_catalog']

Arguments
[@table_server =] 'table_server'
Is the name of the linked server from which to return primary key information. table_server is sysname, with no default.
[@table_name =] 'table_name'
Is the name of the table for which to provide primary key information. table_name is sysname, with a default of NULL.
[@table_schema =] 'table_schema'
Is the table schema. table_schema is sysname, with a default of NULL. In the Microsoft SQL Server environment, this corresponds to the table owner.
[@table_catalog =] 'table_catalog'
Is the name of the catalog in which the specified table_name resides. In the Microsoft SQL Server environment, this corresponds to the database name. table_catalog is sysname, with a default of NULL.
Return Code Values

None

Result Sets
Column name | Data type | Description
TABLE_CAT | sysname | Table catalog.
TABLE_SCHEM | sysname | Table schema.
TABLE_NAME | sysname | Name of the table.
COLUMN_NAME | sysname | Name of the column.
KEY_SEQ | int | Sequence number of the column in a multicolumn primary key.
PK_NAME | sysname | Primary key identifier. Returns NULL if not applicable to the data source.

Remarks

If table_name is NULL, sp_primarykeys returns information about all of the tables in the catalog.

sp_primarykeys is executed by querying the PRIMARY_KEYS rowset of the IDBSchemaRowset interface of the OLE DB provider corresponding to table_server. The table_name, table_schema, table_catalog, and column parameters are passed to this interface to restrict the rows returned.

sp_primarykeys returns an empty result set if the OLE DB provider of the specified linked server does not support the PRIMARY_KEYS rowset of the IDBSchemaRowset interface.

Permissions

Execute permissions default to the public role.

Examples

This example returns primary key columns from the LONDON1 server for the Customers table in the Northwind database.

USE master

EXEC sp_primarykeys @table_server = N'LONDON1',
    @table_name = N'Customers',
    @table_catalog = N'Northwind',
    @table_schema = N'dbo'

See Also
sp_catalogs | sp_linkedservers
sp_column_privileges | sp_tables_ex
sp_foreignkeys | sp_table_privileges
sp_indexes | System Stored Procedures


sp_post_msx_operation

Inserts operations (rows) into the sysdownloadlist system table for target servers to download and execute.

Syntax

sp_post_msx_operation [@operation =] 'operation'
[,[@object_type =] 'object']
{, [@job_id =] job_id }
[,[@specific_target_server =] 'target_server']
[,[@value =] value]

Arguments
[@operation =] 'operation'
Is the type of operation for the posted operation. operation is varchar(64), with no default. Valid operations depend upon object_type.

Object type Operation
JOB INSERT,
UPDATE,
DELETE,
START,
STOP
SERVER RE-ENLIST,
DEFECT,
SYNC-TIME,
SET-POLL

[@object_type =] 'object'
Is the type of object for which to post an operation. Valid types are JOB and SERVER. object is varchar(64), with a default of JOB.
[@job_id =] job_id
Is the job identification number of the job to which the operation applies. job_id is uniqueidentifier, with no default. 0x00 indicates ALL jobs. If object is SERVER, then job_id is not required.
[@specific_target_server =] 'target_server'
Is the name of the target server for which the specified operation applies. If job_id is specified, but target_server is not specified, the operations are posted for all job servers of the job. target_server is varchar(30), with a default of NULL.
[@value =] value
Is the polling interval, in seconds. value is int, with a default of NULL. Specify this parameter only if operation is SET-POLL.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

sp_post_msx_operation must be run from the msdb database.

sp_post_msx_operation can always be called safely because it first determines if the current server is a multiserver SQL Server Agent and, if so, whether object is a multiserver job.

After an operation has been posted, it appears in the sysdownloadlist table. After a job has been created and posted, subsequent changes to that job must also be communicated to the target servers (TSX). This is also accomplished using the download list.

It is highly recommended that the download list be managed by using the SQL Server Enterprise Manager.

Permissions

Only members of the db_owner fixed database role or the sysadmin fixed server role can execute this procedure.

See Also
sp_add_jobserver | sp_start_job
sp_delete_job | sp_stop_job
sp_delete_jobserver | sp_update_job
sp_delete_targetserver | sp_update_operator
sp_resync_targetserver | System Stored Procedures


sp_processmail

Uses extended stored procedures (xp_findnextmsg, xp_readmail, and xp_deletemail) to process incoming mail messages (expected to be only a single query) from the inbox for Microsoft® SQL Server™. It uses the xp_sendmail extended stored procedure to return the result set to the message sender.

Syntax

sp_processmail [[@subject =] 'subject']
[,[@filetype =] 'filetype']
[,[@separator =] 'separator']
[,[@set_user =] 'user']
[,[@dbuse =] 'dbname']

Arguments
[@subject =] 'subject'
Is the subject line of mail messages to interpret as queries for SQL Server. subject is varchar(255), with a default of NULL. When specified, sp_processmail processes only messages that have this subject. By default, SQL Server processes all mail messages as though they were queries.
[@filetype =] 'filetype'
Is the file extension to be used when sending the result set file back to the message sender. filetype is varchar(3), with a default of txt.
[@separator =] 'separator'
Is the column separator (field terminator) for each column of the result set. This information is passed to the xp_sendmail extended stored procedure to return the result set to the message sender. separator is varchar(3), with a default of tab, which is a special case for the tab character to be used between columns.
[@set_user =] 'user'
Is the security context in which the query should be run. user is sysname, with a default of guest (the guest user).
[@dbuse =] 'dbname'
Is the database context in which the query should be run. dbname is sysname, with a default of master.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

Incoming e-mail is expected to have a single valid SQL Server query as the message text. The results of the query are returned to the message sender and copied to any e-mail users on the CC: list of the original message. After messages are processed, they are deleted from the inbox. If e-mail is often sent to the server, sp_processmail should be run frequently. To set up regular e-mail processing, you can use SQL Server Agent to schedule an sp_processmail job. This processes mail at the specified frequency and records an informational message with the number of queries processed in the job history.

Results are sent as an attached file. The complete file name sent consists of Sql followed by a random string of numbers and then the specified extension (file type), for example, Sql356.txt.

Important To attach an appropriate icon to the mail message, make sure the file type is associated properly. To create a file association, double-click My Computer on your desktop and select Options from the View menu. On the File Types tab, in the Options dialog box, specify the application to use to open the file.

Errors received when the query is processed are returned to the message sender through the message text. When the result set is returned to the client, xp_sendmail is called with the @echo_error parameter set to true. The messages sent also include a rowcount (number of rows affected) by the query.

Different sp_processmail jobs can be set up for queries in different databases. For example, you could adopt the convention that queries to the pubs database must have a subject of SQL:pubs. Then, you could run sp_processmail with subject = SQL:pubs and dbname = pubs. Different database queries and groupings can have other formatting structures. For example, distribution tasks can have subject = SQL:distribution and dbname = distribution. Any of these can be scheduled jobs with the SQL Server Agent.

The sp_processmail system stored procedure can also be customized in many ways by retrieving the text of the procedure with the sp_helptext system stored procedure and then modifying the Transact-SQL code. Possible changes include:

  • Process only certain custom message types using the @type parameter with the xp_readmail extended stored procedure.
  • Mark the message as read but do not delete the message after processing (execute xp_readmail a second time with peek set to false).
  • Send the query results in the body of the e-mail message by calling xp_sendmail with attach_result set to false.
  • Set the security context to run the query in a user context based on the message sender. If the e-mail usernames are the same as your SQL Server usernames, this is as simple as changing the call to xp_sendmail to use set_user = @originator. If your mail usernames are not valid SQL Server usernames (if, for example, they contain embedded blanks), you could do a table lookup or character substitution to get the appropriate SQL Server username to pass to xp_sendmail.
Permissions

Only members of the sysadmin fixed server role or the db_owner fixed database role can execute this procedure.

Examples

This example processes all messages in the pubs database with result sets returned to the client in CSV (comma separated values) format.

sp_processmail @filetype = 'CSV', @separator = ',', @dbuse = 'pubs'

See Also
sp_addtask | xp_readmail
xp_deletemail | xp_sendmail
xp_findnextmsg | System Stored Procedures


sp_procoption

Sets or shows procedure options.

Syntax

sp_procoption [[@ProcName =] 'procedure']
[,[@OptionName =] 'option']
[,[@OptionValue =] 'value']

Arguments
[@ProcName =] 'procedure'
Is the name of the procedure for which to set or view an option. procedure is nvarchar(776), with a default of NULL.
[@OptionName =] 'option'
Is the option to set to true or false, or on or off, or the option about which to display information. Wildcard characters cannot be used. option is varchar(35), with a default of NULL. The only value for option is startup, which sets stored procedure for autoexecution. A stored procedure that is set to autoexection runs every time Microsoft® SQL Server™ is started.
[@OptionValue =] 'value'
Is whether to set the option on (true or on) or off (false or off). value is varchar(12), with a default of NULL.
Return Code Values

0 (success) or error number (failure)

Result Sets

Execute sp_procoption without procedure to display the list of available procedure options for all stored procedures.

Column name | Data type | Description
Option Status | int | Whether the option is on or off, or true or false
Procedure Name | sysname | Name of the procedure
Owner Name | nchar | Owner of the procedure
Proc Type | char(2) | Procedure type: P or X

Execute sp_procoption with option_name but without a value to display status for the procedure specified.

If no parameters are specified, sp_procoption returns this result set:

Available Proc Options              Change-ability

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

startup                             change-able

Permissions

Execute permissions default to members of the sysadmin and setupadmin fixed server roles. Startup procedures must be owned by the database owner in the master database.

See Also

System Stored Procedures


sp_publication_validation

Initiates an article validation request for each article in the specified publication.

Syntax

sp_publication_validation [@publication =] 'publication'
[,[@rowcount_only =] rowcount_only]
[,[@full_or_fast =] full_or_fast]
[,[@shutdown_agent =] shutdown_agent]

Arguments
[@publication =] 'publication'
Is the name of the publication. publication is sysname, with no default.
[@rowcount_only =] rowcount_only
Is whether to return only the rowcount for the table. rowcount_only is bit, with a default of 1. If 0, returns the rowcount and checksum. If 1, returns only the rowcount.
[@full_or_fast =] full_or_fast
Is the method used to calculate the rowcount. full_or_fast is tinyint, with a default of 2, and can be one of these values.

Value | Description
0 | Does full count using COUNT(*).
1 | Does fast count from sysindexes.rows. Counting rows in sysindexes is much faster than counting rows in the actual table. However, because sysindexes is lazily updated, the rowcount may not be accurate.
2 (default) | Does conditional fast counting by first trying the fast method. If fast method shows differences, reverts to full method. If expected_rowcount is NULL and the stored procedure is being used to get the value, a full COUNT(*) is always used.

[@shutdown_agent =] shutdown_agent
Is whether the Distribution Agent should shut down immediately upon completion of the validation. shutdown_agent is bit, with a default of 0. If 0, the replication agent does not shut down. If 1, the replication agent shuts down after the last article is validated.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_publication_validation is used in snapshot and transactional replication.

sp_publication_validation can be called at any time after the articles associated with the publication have been activated. The procedure can be run manually one time or as part of a regularly scheduled job that validates the data.

Permissions

Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_publication_validation.

See Also
sp_article_validation | System Stored Procedures
sp_table_validation |


sp_purgehistory

sp_purgehistory is provided for backward compatibility only.

Removes information from the history log.

Important For information about syntax used in earlier versions of SQL Server, see the Microsoft SQL Server Transact-SQL Reference for version 6.x.

Remarks

For task management, use SQL Server Enterprise Manager.

Permissions

Execute permissions default to the public role.

See Also
sp_addtask | System Stored Procedures
sp_helphistory |


sp_purge_jobhistory

Removes the history records for a job.

Syntax

sp_purge_jobhistory [@job_name =] 'job_name' | [@job_id =] job_id

Arguments
[@job_name =] 'job_name'
Is the name of the job for which to delete the history records. job_name is sysname, with a default of NULL. Either job_id or job_name must be specified, but both cannot be specified.
[@job_id =] job_id
Is the job identification number of the job for the records to be deleted. job_id is uniqueidentifier, with a default of NULL. Either job_id or job_name must be specified, but both cannot be specified.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Permissions

Execute permissions default to the public role. If no parameters are supplied, all history records are removed; however, only members of the sysadmin fixed server role have permission to do this.

Examples
A. Remove history for a specific job

This example removes the history for a job named Table Archives.

USE msdb

EXEC sp_purge_jobhistory @job_name = 'Table Archives'

B. Remove history for all jobs

This example executes the procedure with no parameters to remove all history records.

USE msdb

EXEC sp_purge_jobhistory

See Also
sp_help_job | System Stored Procedures
sp_help_jobhistory |


sp_reassigntask

This procedure is provided for backward compatibility only.

sp_reassigntask changes the owner of a job (formerly referred to as a task), or all jobs owned by a specified login. If a job was created by using sp_addtask, the job must be deleted by using sp_droptask.

Important For syntax information used in earlier versions of SQL Server, see the Microsoft® SQL Server™ version 6.x Transact-SQL Reference. For task management, use SQL Server Enterprise Manager.

See Also
sp_update_job System Stored Procedures


sp_recompile

Causes stored procedures and triggers to be recompiled the next time they are run.

Syntax

sp_recompile [@objname =] 'object'

Arguments
[@objname =] 'object'
Is the qualified or unqualified name of a stored procedure, trigger, table, or view in the current database. object is nvarchar(776), with no default. If object is the name of a stored procedure or trigger, the stored procedure or trigger will be recompiled the next time it is run. If object is the name of a table or view, all the stored procedures that reference the table or view will be recompiled the next time they are run.
Return Code Values

0 (success) or a nonzero number (failure)

Result Sets

None

Remarks

sp_recompile looks for an object in the current database only.

The queries used by stored procedures and triggers are optimized only when they are compiled. As indexes or other changes that affect statistics are made to the database, compiled stored procedures and triggers may lose efficiency. By recompiling stored procedures and triggers that act on a table, you can reoptimize the queries.

Note Microsoft® SQL Server™ automatically recompiles stored procedures and triggers when it is advantageous to do so.

Permissions

Execute permissions default to the public role. Users that are not members of the sysadmin fixed server role or the db_owner fixed database role can affect only their own tables.

Examples

This example causes the triggers and stored procedures that uses the titles table to be recompiled the next time they are run..

EXEC sp_recompile titles

See Also

System Stored Procedures


sp_refreshsubscriptions

Add subscriptions to new articles in a pull publication for all the existing Subscribers to the publication.

Syntax

sp_refreshsubscriptions [@publication =] 'publication'

Arguments
[@publication =] 'publication'
Is the publication to refresh subscriptions for. publication is sysname, with no default.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

sp_refreshsubscriptions is used in snapshot, transactional, and merge replication.

sp_refreshsubscriptions is called by sp_addarticle for an immediate-updating publication.

Permissions

Only members of the sysadmin fixed server role or the db_owner fixed database role can execute sp_refreshsubscriptions.

See Also
sp_addarticle System Stored Procedures


sp_refreshview

Refreshes the metadata for the specified view. Persistent metadata for a view can become outdated because of changes to the underlying objects upon which the view depends.

Syntax

sp_refreshview [@viewname =] 'viewname'

Arguments
[@viewname =] 'viewname'
Is the name of the view. viewname, which can be a multipart identifier, is nvarchar, with no default.
Return Code Values

0 (success) or a nonzero number (failure)

Result Sets

None

Permissions

Only members of the db_owner fixed database role can execute sp_refreshview.

Examples

This example refreshes the metadata for the view titleview.

exec sp_refreshview titleview

See Also
System Stored Procedures


sp_reinitmergepullsubscription

Marks a merge pull subscription for reinitialization the next time the Merge Agent runs.

Syntax

sp_reinitmergepullsubscription [[@publisher =] 'publisher']
[,[@publisher_db =] 'publisher_db'] [,[@publication =] 'publication']

Arguments
[@publisher =] 'publisher'
Is the name of the Publisher. publisher is sysname, with a default of all.
[@publisher_db =] 'publisher_db'
Is the name of the Publisher database. publisher_db is sysname, with a default of all.
[@publication =] 'publication'
Is the name of the publication. publication is sysname, with a default of all.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_reinitmergepullsubscription is used in merge replication.

sp_reinitmergepullsubscription can be called from the Subscriber.

Permissions

Only members of the sysadmin fixed server role or the db_owner fixed database role can execute sp_reinitmergepullsubscription.

See Also
System Stored Procedures


sp_reinitmergesubscription

Marks a merge subscription for reinitialization the next time the Merge Agent runs.

Syntax

sp_reinitmergesubscription [[@publication =] 'publication'
[,[@subscriber =] 'subscriber', [@subscriber_db =] 'subscriber_db'

Arguments
[@publication =] 'publication'
Is the name of the publication. publication is sysname, with a default of all.
[@subscriber =] 'subscriber'
Is the name of the Subscriber. subscriber is sysname, with a default of all.
[@subscriber_db =] 'subscriber_db'
Is the name of the Subscriber database. subscriber_db is sysname, with a default of all.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_reinitmergesubscription is used in merge replication.

sp_reinitmergesubscription can be called from the Publisher to reinitialize merge subscriptions. It is advisable to rerun the Snapshot Agent as well.

Permissions

Only members of the sysadmin fixed server role or the db_owner fixed database role can execute sp_reinitmergesubscription.

See Also
System Stored Procedures


sp_reinitpullsubscription

Marks a transactional pull or anonymous subscription for reinitialization the next time the Distribution Agent runs.

Syntax

sp_reinitpullsubscription [@publisher =] 'publisher',
[@publisher_db =] 'publisher_db', [@publication =] 'publication'

Arguments
[@publisher =] 'publisher'
Is the name of the Publisher. publisher is sysname, with no default.
[@publisher_db =] 'publisher_db'
Is the name of the Publisher database. publisher_db is sysname, with no default.
[@publication =] 'publication'
Is the name of the publication. publication is sysname, with a default of all (meaning all publications).
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_reinitpullsubscription is used in transactional replication.

sp_reinitpullsubscription can be called from the Subscriber to reinitialize the subscription, during the next run of the Distribution Agent. Note that the subscriptions of non_immediate_sync type publications cannot be reinitialized from the Subscriber.

You can reinitialize a pull subscription by either executing sp_reinitpullsubscription at the Subscriber or sp_reinitsubscription at the Publisher.

Permissions

Only members of the sysadmin fixed server role or the db_owner fixed database role can execute sp_reinitpullsubscription.

See Also
System Stored Procedures


sp_reinitsubscription

Resynchronizes the subscription.

Syntax

sp_reinitsubscription [[@publication =] 'publication'] [,[@article =] 'article'],
{[@subscriber =] 'subscriber'} [,[@destination_db =] 'destination_db']

Arguments
[@publication =] 'publication'
Is the name of the publication. publication is sysname, with a default of all.
[@article =] 'article'
Is the name of the article. article is sysname, with a default of all. For an immediate-updating publication, article must be all; otherwise, the stored procedure skips the publication and reports an error.
[@subscriber =] 'subscriber'
Is the name of the Subscriber. subscriber is sysname, with no default.
[@destination_db =] 'destination_db'
Is the name of the destination database. destination_db is sysname, with a default of all.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_reinitsubscription is used in transactional replication.

For auto_sync subscriptions on a publication that does not allow immediate-updating subscriptions, the Snapshot Agent must be run to prepare schema and bulk copy program files for the Distribution Agents to resynchronize the Subscribers after this stored procedure is executed.

For auto_sync subscriptions on a publication that allows immediate-updating subscriptions, the Distribution Agents resynchronize the Subscriber using the most up-to-date schema and bulk copy program files created by the Snapshot Agent before this stored procedure is executed. The Distribution Agent resynchronizes the Subscriber immediately after the user executes the stored procedure if the Distribution Agent is not busy; otherwise, it may happen after the message interval (specified by Distribution Agent command-prompt parameter: MessageInterval).

For no_sync subscriptions, it is up to the user to make sure that the destination tables at the Subscriber are in synchronization and there are no undelivered replication commands for the Subscriber pending before executing this stored procedure.

To resynchronize anonymous Subscribers on a publication, pass in all or NULL as subscriber.

Permissions

Only members of the sysadmin fixed server role, members of the db_owner fixed database role, or the creator of the subscription can execute sp_reinitsubscription.

See Also
System Stored Procedures


sp_remoteoption

Displays or changes options for a remote login defined on the local server running Microsoft® SQL Server™.

Syntax

sp_remoteoption [[@remoteserver =] 'remoteserver']
[,[@loginame =] 'loginame']
[,[@remotename =] 'remotename']
[,[@optname =] 'optname']
[,[@optvalue =] 'optvalue']

Arguments
[@remoteserver =] 'remoteserver'
Is the name of the remote server that the remote login applies to. remoteserver is sysname, with a default of NULL. The server must be known to the local server (added using sp_addserver). remoteserver is the server that initiates remote procedure calls to the local server.
[@loginame =] 'loginame'
Is the login ID of the user on the local SQL Server. login is sysname, with a default of NULL. login must already exist on the local SQL Server.
[@remotename =] 'remotename'
Is the login ID of the user on remoteserver. remote_name is sysname, with a default of NULL. remotename must exist on remoteserver.
[@optname =] 'optname'
Is the option to set or turn off. optname is varchar(35), with a default of NULL. trusted is the only option. When the option is set, the local server accepts remote logins from remote servers without verifying user access for the particular remote login. The default server behavior is untrusted (trusted set to FALSE), resulting in password verification of the remote login when connecting to the local SQL Server from the remote server.
[@optvalue =] 'optvalue'
Is the value for optname. optvalue is varchar(10), with a default of NULL. Set to TRUE to set optname, FALSE to turn it off.
Return Code Values

0 (success) or 1 (failure)

Result Sets
Column name | Data type | Description
remotelogin_option | sysname | Remote login option. Only trusted is valid.

Remarks

To display a list of the remote login options, execute sp_remoteoption with no parameters.

sp_remoteoption cannot be executed within a user-defined transaction.

Permissions

Only members of the sysadmin or securityadmin fixed server roles can execute sp_remoteoption.

Examples
A. List options

This example lists the remote login options.

EXEC sp_remoteoption

go

Settable remotelogin options.

remotelogin_option

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

trusted

B. Accept trusted logins

This example defines a remote login chris, mapped to the local login salesmgr, from the remote server ACCOUNTS to be trusted (the password is not checked).

EXEC sp_remoteoption 'ACCOUNTS', 'salesmgr', 'chris', 'trusted', 'TRUE'

C. Verify untrusted logins

This example defines a remote login chris, mapped to the local login salesmgr, from the remote server ACCOUNTS to be untrusted (the password is checked).

EXEC sp_remoteoption 'ACCOUNTS', 'salesmgr', 'chris', 'trusted', 'FALSE'

See Also
sp_addremotelogin | System Stored Procedures
sp_helpremotelogin |


sp_remove_job_from_targets

Removes the specified job from the given target servers or target server groups.

Syntax

sp_remove_job_from_targets [@job_id =] job_id | [@job_name =] 'job_name'
[, [@target_server_groups =] 'target_server_groups']
[, [@target_servers =] 'target_servers']

Arguments
[@job_id =] job_id
Is the job identification number of the job from which to remove the specified target servers or target server groups. Either job_id or job_name must be specified, but both cannot be specified. job_id is uniqueidentifier, with a default of NULL.
[@job_name =] 'job_name'
Is the name of the job from which to remove the specified target servers or target server groups. Either job_id or job_name must be specified, but both cannot be specified. job_name is sysname, with a default of NULL.
[@target_server_groups =] 'target_server_groups'
Is a comma-separated list of target server groups to be removed from the specified job. target_server_groups is nvarchar(1024), with a default of NULL.
[@target_servers =] 'target_servers'
Is a comma-separated list of target servers to be removed from the specified job. target_servers is nvarchar(1024), with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Permissions

Only members of the sysadmin fixed server role can execute sp_remove_job_from_targets.

Examples

This example removes the previously created Weekly Sales Data Backup job from the Sales Server target server group, and from the SEATTLE1 and SEATTLE2 servers.

USE msdb

EXEC sp_remove_job_from_targets @job_name = 'Weekly Sales Data Backup',
    @target_servers = 'Sales Servers',
    @target_server_groups = 'SEATTLE2,SEATTLE1'

See Also
sp_apply_job_to_targets | System Stored Procedures
sp_delete_jobserver |


sp_removedbreplication

Removes all replication objects from a database without updating data at the Distributor.

Syntax

sp_removedbreplication [@dbname =] 'dbname'

Arguments
[@dbname =] 'dbname'
Is the name of the database. dbname is sysname, with no default.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_removedbreplication is used in all types of replication.

sp_removedbreplication is useful when restoring a replicated database that has no replication objects needing to be restored.

Permissions

Only members of the sysadmin fixed server role can execute sp_removedbreplication.

See Also
System Stored Procedures


sp_rename

Changes the name of a user-created object (for example, table, column, or user-defined data type) in the current database.

Syntax

sp_rename [@objname =] 'object_name',
[@newname =] 'new_name'
[, [@objtype =] 'object_type']

Arguments
[@objname =] 'object_name'
Is the current name of the user object (table, view, column, stored procedure, trigger, default, database, object, or rule) or data type. If the object to be renamed is a column in a table, object_name must be in the form table.column. If the object to be renamed is an index, object_name must be in the form table.index. object_name is nvarchar(776), with no default.
[@newname =] 'new_name'
Is the new name for the specified object. new_name must be a one-part name and must follow the rules for identifiers. newname is sysname, with no default.
[@objtype =] 'object_type'
Is the type of object being renamed. object_type is varchar(13), with a default of NULL, and can be one of these values.

Value | Description
COLUMN | A column to be renamed.
DATABASE | A user-defined database. This option is required when renaming a database.
INDEX | A user-defined index.
OBJECT | An item of a type tracked in sysobjects. For example, OBJECT could be used to rename objects including constraints (CHECK, FOREIGN KEY, PRIMARY/UNIQUE KEY), user tables, views, stored procedures, triggers, and rules.
USERDATATYPE | A user-defined data type added by executing sp_addtype.

Return Code Values

0 (success) or a nonzero number (failure)

Result Sets

None

Remarks

You can change the name of an object or data type in the current database only. The names of most system data types and system objects cannot be changed.

When you rename a view, information about the view is updated in the sysobjects table. When you rename a stored procedure, information about the procedure is changed in the sysobjects table.

sp_rename automatically renames the associated index whenever a PRIMARY KEY or UNIQUE constraint is renamed. If a renamed index is tied to a PRIMARY KEY constraint, the primary key is also automatically renamed by sp_rename.

Important After renaming stored procedures and views, flush the procedure cache to ensure all dependent stored procedures and views are recompiled.

Stored procedures and views can be dropped and re-created quickly because neither object stores data. For best results renaming textual objects, drop and re-create the object by its new name.

Permissions

Members of the sysadmin fixed server role, the db_owner fixed database role, or the owner of the object can execute sp_rename.

Examples
A. Rename a table

This example renames the customers table to custs.

EXEC sp_rename 'customers', 'custs'

B. Rename a column

This example renames the contact title column in the customers table to title.

EXEC sp_rename 'customers.[contact title]', 'title', 'COLUMN'

See Also
ALTER TABLE | Data Types
CREATE DEFAULT | SETUSER
CREATE PROCEDURE | sp_addtype
CREATE RULE | sp_depends
CREATE TABLE | sp_renamedb
CREATE TRIGGER | System Stored Procedures
CREATE VIEW |


sp_renamedb

Changes the name of a database.

Syntax

sp_renamedb [@old_name =] 'old_name',
[@new_name =] 'new_name'

Arguments
[@old_name =] 'old_name'
Is the current name of the database. old_name is sysname, with no default.
[@new_name =] 'new_name'
Is the new name of the database. new_name must follow the rules for identifiers. new_name is sysname, with no default.
Return Code Values

0 (success) or a nonzero number (failure)

Result Sets

None

Remarks

Before a database is renamed, it must be put into single-user mode by using sp_dpoption, and then restored to multiuser mode afterward.

Permissions

Only members of the sysadmin fixed server role can execute sp_renamedb.

Examples

This example changes the name of the accounting database to financial.

EXEC sp_renamedb 'accounting', 'financial'

See Also
CREATE DATABASE | sp_helpdb
sp_changedbowner | sp_rename
sp_dboption | System Stored Procedures
sp_depends |


sp_replcmds

Treats the first client that runs sp_replcmds within a given database as the log reader. Returns the commands for transactions marked for replication.

Syntax

sp_replcmds [@maxtrans =] maxtrans

Arguments
[@maxtrans =] maxtrans
Is the number of transactions to return information about. maxtrans is int, with a default of 1, which specifies the next transaction waiting for distribution.
Result Sets

sp_replcmds is used by the log reader process. It returns information about the publication database from which it is executed. It allows you to view transactions that currently are not distributed (those transactions remaining in the transaction log that have not been sent to the Distributor) with their commands, and it returns article ID, partial_command (true or false), the command, page, row, and timestamp.

Remarks

sp_replcmds is used in transactional replication.

This procedure can generate commands for owner-qualified tables or not qualify the table name (the default). Adding qualified table names allows replication of data from tables owned by a specific user in one database to tables owned by the same user in another database.

Note Because the table name in the source database is qualified by the owner name, the owner of the table in the target database must be the same owner name.

Clients who attempt to run sp_replcmds within the same database receive error 18752 until the first client disconnects. After the first client disconnects, another client can run sp_replcmds, and becomes the new log reader.

Note The sp_replcmds procedure should be run only to troubleshoot problems with replication.

A warning message number 18759 is added to both the Microsoft® SQL Server™ error log and the Microsoft Windows NT® application log if sp_replcmds is unable to replicate a text command because the text pointer was not retrieved in the same transaction.

Permissions

Only members of the sysadmin fixed server role or the db_owner fixed database role can execute sp_replcmds.

See Also
sp_repldone | sp_repltrans
sp_replflush | System Stored Procedures


sp_replcounters

Returns replication statistics about latency, throughput, and transaction count for each published database.

Syntax

sp_replcounters

Result Sets
Column name | Data type | Description
Database | sysname | Name of the database
Replicated transactions | int | Number of transactions in the log awaiting delivery to the distribution database
Replication rate trans/sec | float | Average number of transactions per second delivered to the distribution database
Replication latency | float | Average time, in seconds, that transactions were in the log before being distributed
Replbeginlsn | binary(10) | Log sequence number of the current truncation point in the log
Replendlsn | binary(10) | Log sequence number of the next commit record awaiting delivery to the distribution database

Remarks

sp_replcounters is used in transactional replication.

Permissions

Members of the public role can execute sp_replcounters.

See Also
sp_replcmds | sp_replflush
sp_repldone | System Stored Procedures


sp_repldone

Updates the record that identifies the server’s last distributed transaction.

Syntax

sp_repldone [@xactid =] xactid, [@xact_seqno =] xact_seqno
[,[@numtrans =] numtrans] [,[@time =] time [,[@reset =] reset]

Arguments
[@xactid =] xactid
Is the log sequence number (LSN) of the first record for the last distributed transaction of the server. xactid is binary(10), with no default.
[@xact_seqno =] xact_seqno
Is the LSN of the last record for the last distributed transaction of the server. xact_seqno is binary(10), with no default.
[@numtrans =] numtrans
Is the number of transactions distributed. numtrans is int, with no default.
[@time =] time
Is the number of milliseconds, if provided, needed to distribute the last batch of transactions. time is int, with no default.
[@reset =] reset
Is the reset status. reset is int, with no default. If 1, all replicated transactions in the log are marked as distributed. If 0, the transaction log is reset to the first replicated transaction and no replicated transactions are marked as distributed. reset is valid only when both xactid and xact_seqno are NULL.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_repldone is used in transactional replication.

sp_repldone is used by the log reader process to track which transactions have been distributed.

Caution If you execute sp_repldone manually, you can invalidate the order and consistency of delivered transactions.

With sp_repldone, you can manually tell the server that a transaction has been replicated (sent to the Distributor). It also allows you to change the transaction marked as the next one awaiting replication. You can move forward or backward in the list of replicated transactions. (All transactions less than or equal to that transaction are marked as distributed.)

The required parameters xactid and xact_seqno can be obtained by using sp_repltrans or sp_replcmds.

Permissions

Members of the sysadmin fixed server role or the db_owner fixed database role can execute sp_repldone.

Examples

When xactid is NULL, xact_seqno is NULL, and reset is 1, all replicated transactions in the log are marked as distributed. This is useful when there are replicated transactions in the transaction log that are no longer valid and you want to truncate the log, for example:

EXEC sp_repldone @xactid = NULL, @xact_segno = NULL, @numtrans = 0,     @time = 0, @reset = 1

Caution This procedure can be used in emergency situations to allow truncation of the transaction log when transactions pending replication are present. Using this procedure prevents Microsoft® SQL Server™ from replicating the database until the database is unpublished and republished.

See Also
sp_replcmds | sp_repltrans
sp_replflush | System Stored Procedures


sp_replflush

Flushes the article cache.

Syntax

sp_replflush

Return Code Values

0 (success) or 1 (failure)

Remarks

sp_replflush is used in transactional replication.

Article definitions are stored in cache for efficiency. sp_seplflush is used by other replication stored procedures whenever an article definition is modified or dropped.

Only one client connection can have log reader access to a given database. If a client has log reader access to a database, executing sp_replflush causes the client to release its access. Other clients can then scan the transaction log using sp_replcmds or sp_replshowcmds.

You should not have to execute this procedure manually.

Permissions

Only members of the sysadmin fixed server role or the db_owner fixed database role can execute sp_replflush.

See Also
sp_replcmds | sp_repltrans
sp_repldone | System Stored Procedures


sp_replicationdboption

Sets a replication database option for the current database.

Syntax

sp_replicationdboption [@dbname =] 'db_name', [@optname =] 'optname',
[@value =] 'value' [,[@ignore_distributor =] ignore_distributor]

Arguments
[@dbname =] 'dbname'
Is the database to drop. db_name is sysname, with no default.
[@optname =] 'optname'
Is the option to create or drop. optname is sysname, and can be one of these values.

Value | Description
merge publish | Database can be used for merge publications.
publish | Database can be used for other types of publications.

[@value =] 'value'
Is whether to create or drop the given replication database option. value is sysname, and can be true or false. false also drops the merge subscriptions.
[@ignore_distributor =] ignore_distributor]
Indicates whether this stored procedure is executed without connecting to the Distributor. ignore_distributor is bit, with a default of 0, meaning the Distributor should be connected to and updated with the new status of the publishing database. The value 1 should be specified only if the Distributor is inaccessible and sp_replicationdboption is being used to disable publishing.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_replicationdboption is used in snapshot, transactional, and merge replication.

This procedure creates or drops specific replication system tables, security accounts, and so on, depending on the options given. Sets the corresponding category bit in the master..sysdatabases system table and creates the necessary system tables.

Permissions

Only members of the sysadmin fixed server role can execute sp_replicationdboption.

See Also
sysdatabases System Stored Procedures


sp_replication_agent_checkup

Checks each distribution database for replication agents that are running but have not logged history within the specified heartbeat interval.

Syntax

sp_replication_agent_checkup [[@heartbeat_interval =] heartbeat_interval]

Arguments
[@heartbeat_interval =] 'heartbeat_interval'
Is the maximum number of minutes that an agent can go without logging a progress message. heartbeat_interval is int, with a default of 10 minutes.
Return Code Values

sp_replication_agent_checkup raises error 14151 for each agent it detects as suspect. It also logs a failure history message about the agents.

Remarks

sp_replication_agent_checkup is used in snapshot, transactional, and merge replication.

Permissions

Only members of the sysadmin fixed server role can execute sp_replication_agent_checkup.

See Also
System Stored Procedures


sp_replsetoriginator

Used to invoke loopback detection and handling in transactional replication.

Syntax

sp_replsetoriginator [@server_name =] 'server_name'
 [@database_name = ] 'database_name'

Arguments
[@server_name =] 'server_name'
Is the name of the server where the transaction is being applied. originating_server is sysname, with no default.
[@database_name = ] 'database_name'
Is the name of the database where the transaction is being applied. originating_db is sysname, with no default.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_replsetoriginator is executed by the Distribution Agent to record the source of transactions applied by replication. This information is used to invoke loopback detection for transactional subscriptions that have the loopback property set. Immediate-updating subscriptions and bi-directional transactional replication are used to set the loopback detection property for a subscription.

Permissions

Members of the public role can execute sp_replsetoriginator.


sp_replshowcmds

Returns the commands for transactions marked for replication in readable format. sp_replshowcmds can be run only when client connections (including the current connection) are not reading replicated transactions from the log.

Syntax

sp_replshowcmds [@maxtrans =] maxtrans

Arguments
[@maxtrans =] maxtrans
Is the number of transactions about which to return information. maxtrans is int, with a default of 1, which specifies the maximum number of transactions pending replication for which sp_replshowcmds will return information.
Result Sets

sp_replshowcmds is a diagnostic procedure that returns information about the publication database from which it is executed.

Column name | Data type | Description
xact_seqno | binary(10) | Sequence number of the command
originator_id | int | ID of the command originator, always 0
publisher_database_id | int | ID of the Publisher database, always 0
article_id | int | ID of the article
type | int | Type of command
command | nvarchar(1024) | Transact-SQL command

Remarks

sp_replshowcmds is used in transactional replication.

Using sp_replshowcmds, you can view transactions that currently are not distributed (those transactions remaining in the transaction log that have not been sent to the Distributor).

Clients that run sp_replshowcmds and sp_replcmds within the same database receive error 18752.

To avoid this error, the first client must disconnect or the client’s role as log reader must be released by executing sp_replflush. After all clients have disconnected from the log reader, sp_replshowcmds can be run successfully.

Note sp_replshowcmds should be run only to troubleshoot problems with replication.

Permissions

Only members of the sysadmin fixed server role or the db_owner fixed database role can execute sp_replshowcmds.

See Also
sp_replcmds | sp_repltrans
sp_repldone | System Stored Procedures
sp_replflush |


sp_repltrans

Returns a result set of all the transactions in the publication database transaction log that are marked for replication but have not been marked as distributed.

Syntax

sp_repltrans

Result Sets

sp_repltrans returns information about the publication database from which it is executed, allowing you to view transactions currently not distributed (those transactions remaining in the transaction log that have not been sent to the Distributor). The result set displays the log sequence numbers of the first and last records for each transaction. sp_repltrans is similar to sp_replcmds but does not return the commands for the transactions.

Remarks

sp_repltrans is used in transactional replication.

Permissions

Only members of the sysadmin fixed server role or the db_owner fixed database role can execute sp_repltrans.

See Also
sp_replcmds | sp_repltrans
sp_repldone | System Stored Procedures
sp_replflush |


sp_resync_targetserver

Resynchronizes all multiserver jobs in the specified target server.

Syntax

sp_resync_targetserver [@server_name =] 'server'

Arguments
[@server_name =] 'server'
Is the name of the server to resynchronize. server is nvarchar(30), with no default. If ALL is specified, all target servers are resynchronized.
Return Code Values

0 (success) or 1 (failure)

Result Sets

Reports the result of sp_post_msx_operation actions.

Remarks

sp_resync_targetserver deletes the current set of instructions for the target server and posts a new set for the target server to download. The new set consists of an instruction to delete all multiserver jobs, followed by an insert for each job currently targeted at the server.

Permissions

Only members of the sysadmin fixed server role can execute sp_resync_targetserver.

Examples

This example resynchronizes the LONDON1 target server.

USE msdb

EXEC sp_resync_targetserver 'LONDON1'

See Also
sp_help_downloadlist | System Stored Procedures
sp_post_msx_operation |


sp_revoke_publication_access

Removes the login from a publications access list.

Syntax

sp_revoke_publication_access [@publication =] 'publication',
[@login =] 'login'

Arguments
[@publication =] 'publication'
Is the name of the publication to access. publication is sysname, with no default.
[@login =] 'login'
Is the login ID. login is sysname, with no default.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_revoke_publication_access is used in snapshot, transactional, and merge replication.

sp_revoke_publication_access can be called repeatedly.

Permissions

Only members of the sysadmin fixed server role or the db_owner fixed database role can execute sp_revoke_publication_access.

See Also
sp_grant_publication_access | System Stored Procedures
sp_help_publication_access |


sp_revokedbaccess

Removes a security account from the current database.

Syntax

sp_revokedbaccess [@name_in_db =] 'name'

Arguments
[@name_in_db =] 'name'
Is the name of the account to be removed. name is sysname with no default. name can be the name of a Microsoft® SQL Server™ user, or Microsoft Windows NT® user or group, and must exist in the current database. When specifying a Windows NT user or group, specify the name the Windows NT user or group is known by in the database (added using sp_grantdbaccess).
Return Code Values

0 (success) or 1 (failure)

Remarks

When the account is removed, the permissions and aliases that depend on the account are automatically removed.

You can only remove accounts in the current database using sp_revokedbaccess. To add an account in the database, use sp_grantdbaccess. To remove a SQL Server role, use sp_droprole. When removing an account that owns objects in the current database, you must either remove the object, or change the owner of the object using sp_changeobjectowner, before executing sp_revokedbaccess.

The sp_revokedbaccess stored procedure cannot remove:

  • The public role, or dbo or INFORMATION_SCHEMA users.
  • The fixed roles in the database.
  • The guest user account in the master and tempdb databases.
  • A Windows NT user from a Windows NT group.

sp_revokedbaccess cannot be executed from within a user-defined transaction.

Permissions

Only members of the db_accessadmin or db_owner fixed database roles can execute sp_revokedbaccess.

Examples

This example removes the account Corporate\GeorgeW from the current database.

EXEC sp_revokedbaccess 'Corporate\GeorgeW'

See Also
sp_grantdbaccess | sp_droprole
sp_changeobjectowner | System Stored Procedures


sp_revokelogin

Removes the login entries from Microsoft® SQL Server™ for a Microsoft Windows NT® user or group created with sp_grantlogin or sp_denylogin.

Syntax

sp_revokelogin [@loginame =] 'login'

Arguments
[@loginame =] 'login'
Is the name of the Windows NT user or group. login is sysname, with no default. login can be any existing Windows NT username or group in the form Domain\User.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_revokelogin does not explicitly prevent Windows NT users from connecting to SQL Server, but prevents Windows NT users from doing so through their Windows NT user accounts. However, Windows NT users can still connect if they are members of a Windows NT group that has been granted access to SQL Server using the sp_grantlogin stored procedure. For example, if Windows NT user REDMOND\john is a member of the Windows NT group REDMOND\Admins, and REDMOND\john is revoked access using:

sp_revokelogin [REDMOND\john]

REDMOND\john can still connect if REDMOND\Admins is granted access. Similarly, if REDMOND\Admins is revoked access but REDMOND\john is granted access, REDMOND\john can still connect.

Use sp_denylogin to explicitly prevent users from connecting with SQL Server, regardless of their Windows NT group memberships.

Use sp_droplogin to remove a SQL Server login added with sp_addlogin.

sp_revokelogin cannot be executed within a user-defined transaction.

Permissions

Only members of the sysadmin or securityadmin fixed server roles can execute sp_revokelogin.

Examples

This example removes the login entries for the Windows NT user Corporate\MollyA.

EXEC sp_revokelogin 'Corporate\MollyA'

Or

EXEC sp_revokelogin [Corporate\MollyA]

See Also
sp_denylogin | sp_grantlogin
sp_droplogin | System Stored Procedures


sp_runwebtask

Executes a previously defined Web job and generates the HTML document. The task to run is identified by the output file name, by the procedure name, or by both parameters.

Note All Web jobs are categorized as Web Assistant in the Job Categories dialog box in SQL Server Enterprise Manager.

Syntax

sp_runwebtask [[@procname =] 'procname']
[,[@outputfile =] 'outputfile'

Arguments
[@procname =] 'procname'
Is the name of the Web job procedure to run. The named procedure defines the query for the Web job. procname is nvarchar(128), with no default.
[@outputfile =] 'outputfile'
Is the name of the output file for the specified Web job. outputfile is nvarchar(255), with no default.
Retun Code Values

0 (success) or a nonzero number (failure)

Result Sets

None

Remarks

sp_runwebtask must be executed in the same database specified in dbname of sp_makewebtask.

System administrators should not use SETUSER to test sp_runwebtask. The extended procedure does not honor the security context of the new user. To test for proper security authentication, create a temporary user ID and password. Use this temporary account to log in and test sp_runwebtask. Remove the temporary account after testing is completed.

Output produced by sp_runwebtask is the actual HTML source. You can view the source document with most word processing application.

Important sp_dropwebtask, sp_makewebtask, and sp_runwebtask can be run only on Microsoft® SQL Server™ version 6.5 and later databases. Running these procedures on a database of an earlier version will return errors.

The SQL Server Agent must be running when a job is scheduled to run periodically. Otherwise, generation of the .htm page will not occur.

All Microsoft Windows® 95/98 Web Assistant users must have user accounts in the database being used. Use sp_adduser to add accounts to each database a user may access. When running the Windows 95/98 operating system, an on-demand task can be run only by the job owner or the system administrator.

Permissions

The user must have SELECT permissions to run the specified query used by the Web job.

Examples

This example runs a Web job by using the @outputfile of C:\Web\Myfile.html and an @procname of MYHTML.

sp_runwebtask @procname = 'MYHTML', @outputfile = 'C:\WEB\MYFILE.HTML'

See Also
sp_dropwebtask | System Stored Procedures
sp_makewebtask |


sp_script_synctran_commands

Generates a script that contains the sp_addsynctrigger calls to be applied at Subscribers for immediate-updating subscriptions. There is one sp_addsynctrigger call for each article in the publication.

Syntax

sp_script_synctran_commands [@publication =] 'publication'
[,[@article =] 'article']

Arguments
[@publication =] 'publication'
Is the name of the publication to be scripted. publication is sysname, with no default.
[@article =] 'article'
Is the name of the article to be scripted. article is sysname, with a default of all, which specifies all articles are scripted.
Return Code Values

0 (success) or 1 (failure)

Results Set

sp_script_synctran_commands returns a result set that consists of a single nvarchar(4000) column. The result set forms the complete script necessary to create the sp_addsynctrigger calls to be applied at Subscribers.

Remarks

sp_script_synctran_commands is used in snapshot and transactional replication.

Permissions

Execute permissions default to the public role.

See Also
sp_addsynctriggers System Stored Procedures


sp_scriptdelproc

Generates the CREATE PROCEDURE statement to create a custom stored procedure.

Syntax

sp_scriptdelproc [@artid =] artid

Arguments
[@artid =] artid
Is the article ID. artid is int, with no default.
Result Sets

Returns a result set that consists of a single nvarchar(4000) column. The result set forms the complete CREATE PROCEDURE statement necessary to create the custom stored procedure.

Remarks

sp_scriptdelproc is used in transactional replication.

Permissions

Members of the public role can execute sp_scriptdelproc.

Examples

This example creates an article (with artid set to 1) on the authors table in the pubs database and specifies the DELETE statement to be the custom procedure to execute.

'CALL audel'

The custom stored procedure to be executed by the Distribution Agent at the Subscriber is generated by running this stored procedure at the Publisher.

EXEC sp_MSdel_authors @artid = 1

The statement returns:

CREATE PROCEDURE [sp_MSdel_authors] @pkc1 varchar(11)

AS

DELETE [authors]

WHERE [au_id] = @pkc1

This stored procedure can be used to generate custom stored procedures for manually synchronized articles or for articles for which the automatic generation of custom stored procedures has been disabled.

See Also
sp_scriptinsproc | sp_scriptmappedupdproc
sp_scriptupdproc | System Stored Procedures


sp_scriptinsproc

Generates the CREATE PROCEDURE statement to create a custom stored procedure.

Syntax

sp_scriptinsproc [@artid =] artid

Arguments
[@artid =] artid
Is the article ID. artid is int, with no default.
Result Sets

Returns a result set that consists of a single nvarchar(4000) column. The result set forms the complete CREATE PROCEDURE statement necessary to create the custom stored procedure.

Remarks

sp_scriptinsproc is used in transactional replication.

Permissions

Members of the public role can execute sp_scriptinsproc.

Examples

This example creates an article (with artid set to 1) on the authors table in the pubs database and specifies the INSERT statement to be the custom procedure to execute.

'CALL auins'

The custom stored procedures to be executed by the Distribution Agent at the Subscriber are generated by running this stored procedure at the Publisher.

EXEC sp_scriptinsproc @artid = 1

This statement returns:

CREATE PROCEDURE [sp_insert_authors] @c1 varchar(11),@c2 varchar(40),
    @c3 varchar(20),@c4 char(12),@c5 varchar(40),@c6 varchar(20),
    @c7 char(2),@c8 char(5),@c9 bit

AS

INSERT INTO [authors] VALUES ( @c1,@c2,@c3,@c4,@c5,@c6,@c7,@c8,@c9 )

This stored procedure can be used to generate custom stored procedures for manually synchronized articles or for articles for which the automatic generation of custom stored procedures has been disabled.

See Also
sp_scriptdelproc | sp_scriptmappedupdproc
sp_scriptupdproc | System Stored Procedures


sp_scriptmappedupdproc

Generates the CREATE PROCEDURE statement to create a custom stored procedure.

Syntax

sp_scriptmappedupdproc [@artid =] artid

Arguments
[@artid =] artid
Is the article ID. artid is int, with no default.
Result Sets

Returns a result set that consists of a single nvarchar(4000) column. The result set forms the complete CREATE PROCEDURE statement necessary to create the custom stored procedure.

Remarks

sp_scriptmappedupdproc is used in transactional replication.

Permissions

Only members of the sysadmin fixed server role or the db_owner fixed database role can execute sp_scriptmappedupdproc.

Examples

This example creates an article (with artid set to 1) on the authors table in the pubs database and specifies the UPDATE statement to be the custom procedure to execute.

'MCALL sp_mupd_authors'

The custom stored procedures to be executed by the Distribution Agent at the Subscriber are generated by running this stored procedure at the Publisher.

EXEC sp_scriptmappedupdproc @artid = '1'

The statement returns:

CREATE PROCEDURE [sp_mupd_authors]

    @c1 varchar(11),@c2 varchar(40),@c3 varchar(20),@c4 char(12),
    @c5 varchar(40), @c6 varchar(20),@c7 char(2),@c8 char(5),@c9 bit,
    @pkc1 varchar(11),@bitmap binary(2)

AS

IF substring(@bitmap,1,1) & 1 = 1

PDATE [authors] SET

[au_id] = CASE substring(@bitmap,1,1) & 1 WHEN 1 THEN @c1
    ELSE [au_id] END

,[au_lname] = CASE substring(@bitmap,1,1) & 2 WHEN 2 THEN @c2
    ELSE [au_lname] END

,[au_fname] = CASE substring(@bitmap,1,1) & 4 WHEN 4 THEN @c3
    ELSE [au_fname] END

,[phone] = CASE substring(@bitmap,1,1) & 8 WHEN 8 THEN @c4
    ELSE [phone] END

,[address] = CASE substring(@bitmap,1,1) & 16 WHEN 16 THEN @c5
    ELSE [address] END

,[city] = CASE substring(@bitmap,1,1) & 32 WHEN 32 THEN @c6
    ELSE [city] END

,[state] = CASE substring(@bitmap,1,1) & 64 WHEN 64 THEN @c7
    ELSE [state] END

,[zip] = CASE substring(@bitmap,1,1) & 128 WHEN 128 THEN @c8
    ELSE [zip] END

,[contract] = CASE substring(@bitmap,2,1) & 1 WHEN 1 THEN @c9
    ELSE [contract] END

WHERE [au_id] = @pkc1

ELSE

UPDATE [authors] SET

[au_lname] = CASE substring(@bitmap,1,1) & 2 WHEN 2 THEN @c2
    ELSE [au_lname] END

,[au_fname] = CASE substring(@bitmap,1,1) & 4 WHEN 4 THEN @c3
    ELSE [au_fname] END

,[phone] = CASE substring(@bitmap,1,1) & 8 WHEN 8 THEN @c4
    ELSE [phone] END

,[address] = CASE substring(@bitmap,1,1) & 16 WHEN 16 THEN @c5
    ELSE [address] END

,[city] = CASE substring(@bitmap,1,1) & 32 WHEN 32 THEN @c6
    ELSE [city] END

,[state] = CASE substring(@bitmap,1,1) & 64 WHEN 64 THEN @c7
    ELSE [state] END

,[zip] = CASE substring(@bitmap,1,1) & 128 WHEN 128 THEN @c8
    ELSE [zip] END

,[contract] = CASE substring(@bitmap,2,1) & 1 WHEN 1 THEN @c9
    ELSE [contract] END

where [au_id] = @pkc1

After running this stored procedure, you can use the produced script to manually create the procedure at the Subscribers.

See Also
sp_scriptdelproc | sp_scriptinsproc
sp_scriptupdproc | System Stored Procedures


sp_scriptupdproc

Generates the CREATE PROCEDURE statement to create a custom stored procedure.

Syntax

sp_scriptupdproc [@artid =] artid

Arguments
[@artid =] artid
Is the article ID. artid is int, with no default.
Result Sets

Returns a result set that consists of a single nvarchar(4000) column. The result set forms the complete CREATE PROCEDURE statement necessary to create the custom stored procedure.

Remarks

sp_scriptupdproc is used in transactional replication.

Permissions

Members of the public role can execute sp_scriptupdproc.

Examples

This example creates an article (with artid set to 1) on the authors table in the pubs database and specifies the UPDATE statement to be the custom procedure to execute.

'CALL auupd'

The custom stored procedures to be executed by the Distribution Agent at the Subscriber are generated by running this stored procedure at the Publisher.

EXEC sp_upd_authors @artid = 1

The statement returns:

CREATE PROCEDURE [sp_upd_authors]

    @c1 varchar(11),@c2 varchar(40),@c3 varchar(20),@c4 char(12),
    @c5 varchar(40),@c6 varchar(20),@c7 char(2),@c8 char(5),
    @c9 bit,@pkc1 varchar(11)

AS

IF @c1 = @pkc1

UPDATE [authors] SET [au_lname] = @c2,[au_fname] = @c3,
    [phone] = @c4,[address] = @c5,[city] = @c6,[state] = @c7,
    [zip] = @c8,[contract] = @c9

WHERE [au_id] = @pkc1

ELSE

UPDATE [authors] SET [au_id] = @c1,[au_lname] = @c2,
    [au_fname] = @c3,[phone] = @c4,[address] = @c5,
    [city] = @c6,[state] = @c7,[zip] = @c8,[contract] = @c9

WHERE [au_id] = @pkc1

This stored procedure can be used to generate custom stored procedures for manually synchronized articles or for articles for which the automatic generation of custom stored procedures has been disabled.

See Also
sp_scriptdelproc | sp_scriptmappedupdproc
sp_scriptinsproc | System Stored Procedures


sp_server_info

Returns a list of attribute names and matching values for Microsoft® SQL Server™, the database gateway, or the underlying data source.

Syntax

sp_server_info [[@attribute_id =] 'attribute_id']

Arguments
[@attribute_id =] 'attribute_id'
Is the integer ID of the attribute. attribute_id is int, with a default of NULL.
Return Code Values

None

Result Sets
Column name | Data type | Description
ATTRIBUTE_ID | int | ID number of the attribute
ATTRIBUTE_NAME | varchar(60) | Attribute name
ATTRIBUTE_VALUE | varchar(255) | Current setting of the attribute

These are the attributes. Microsoft DB-Library and ODBC client libraries currently use attributes 1, 2, 18, 22, and 500 at connection time.

ATTRIBUTE_ID | ATTRIBUTE_NAME Description | ATTRIBUTE_VALUE
1 | DBMS_NAME | Microsoft SQL Server
2 | DBMS_VER | Microsoft SQL Server 7.00 - 7.00.xxx (Intel X86) Oct 17 1997 02:53:32 Copyright (c) 1988-1997 Microsoft Corporation
10 | OWNER_TERM | Owner
11 | TABLE_TERM | Table
12 | MAX_OWNER_NAME_ LENGTH | 128
13 | TABLE_LENGTH Specifies the maximum number of characters for a table name. | 128
14 | MAX_QUAL_LENGTH Specifies the maximum length of the name for a table qualifier (the first part of a three-part table name). | 128
15 | COLUMN_LENGTH Specifies the maximum number of characters for a column name. | 128
16 | IDENTIFIER_CASE Specifies the user-defined names (table names, column names, stored procedure names) in the database (the case of the objects in the system catalogs). | MIXED or SENSITIVE, depending upon whether SQL Server is set to case-sensitive or case-insensitive.
17 | TX_ISOLATION Specifies the initial transaction isolation level the server assumes, which corresponds to an isolation level defined in SQL-92. | 2
18 | COLLATION_SEQ Specifies the ordering of the character set for this server. | Charset ID
19 | SAVEPOINT_SUPPORT Specifies whether the underlying DBMS supports named savepoints. | Y
20 | MULTI_RESULT_SETS Specifies whether the underlying database or the gateway itself supports multiple result sets (multiple statements can be sent through the gateway with multiple result sets returned to the client). | Y
22 | ACCESSIBLE_TABLES Specifies whether in sp_tables, the gateway returns only tables, views, and so on, accessible by the current user (that is, the user who has at least SELECT permissions for the table). | Y
100 | USERID_LENGTH Specifies the maximum number of characters for a username. | 30
101 | QUALIFIER_TERM Specifies the DBMS vendor term for a table qualifier (the first part of a three-part name). | Database
102 | NAMED_TRANSACTIONS Specifies whether the underlying DBMS supports named transactions. | Y
103 | SPROC_AS_LANGUAGE Specifies whether stored procedures can be executed as language events. | Y
104 | ACCESSIBLE_SPROC Specifies whether in sp_stored_procedures, the gateway returns only stored procedures that are executable by the current user. | Y
105 | MAX_INDEX_COLS Specifies the maximum number of columns in an index for the DBMS. | 16
106 | RENAME_TABLE Specifies whether tables can be renamed. | Y
107 | RENAME_COLUMN Specifies whether columns can be renamed. | Y
108 | DROP_COLUMN Specifies whether columns can be dropped. | N
109 | INCREASE_COLUMN_ LENGTH Specifies whether column size can be increased. | N
110 | DDL_IN_TRANSACTION Specifies whether DDL statements can appear in transactions. | Returns Y, if SQL Server version 6.5 or later is running and N, for earlier releases.
111 | DESCENDING_INDEXES Specifies whether descending indexes are supported. | N
112 | SP_RENAME Specifies whether a stored procedure can be renamed. | Y
113 | REMOTE_SPROC Specifies whether stored procedures can be executed through the remote stored procedure functions in DB-Library. | Y
500 | SYS_SPROC_VERSION Specifies the version of the catalog stored procedures currently implemented. | Current version number

Remarks

sp_server_info returns a subset of the information provided by SQLGetInfo in ODBC.

Permissions

Execute permissions default to the public role.

See Also

System Stored Procedures


sp_serveroption

Sets server options for remote servers and linked servers. Also provides options for distributed queries that can be enabled or disabled on a per-linked-server basis.

Syntax

sp_serveroption [[@server =] 'server']
[,[@optname =] 'option_name']
[,[@optvalue =] 'option_value']

Arguments
[@server =] 'server'
Is the name of the server for which to set the option. server is sysname, with a default of NULL. If server is omitted, the options that can be set with this stored procedure are displayed.
[@optname =] 'option_name'
Is the option to set for the specified server. option_name is varchar(35), with a default of NULL. If server is specified but option_name is omitted, the options that are set are displayed.

Value | Description
collation compatible Affects Distributed Query execution against linked servers. If this option is set to true, Microsoft® SQL Server™ assumes that all characters in the linked server are compatible with the local server, with regard to character set and collation sequence (or sort order). This enables SQL Server to send comparisons on character columns to the provider. If this option is not set, SQL Server always evaluates comparisons on character columns locally.

This option should be set only if it is certain that the data source corresponding to the linked server has the same character set and sort order as the local server.
data access | Enables and disables a linked server for distributed query access. Can be used only for sysserver entries added through sp_addlinkedserver.
dist | Distributor.
dpub | Remote Publisher to this Distributor.
pub | Publisher.
rpc | Enables RPC from the given server.
rpc out | Enables RPC to the given server.
sub | Subscriber.
system | For internal use only.

[@optvalue =] 'option_value'
Is whether or not the specified option_name should be enabled (TRUE or on) or disabled (FALSE or off). option_value is varchar(10), with a default of NULL. If option_value is NULL, the current setting for the specified option is displayed.
Return Code Values

0 (success) or 1 (failure)

Result Sets

If no parameters are specified, this is the result set.

Column name | Data type | Description
server_option | nvarchar(35) | Lists server options that can be set on or off.

If server is specified, this is the result set.

Column name | Data type | Description
The following options are set: | nvarchar(35) | Lists server options that are currently enabled for server.

If server and option_name are specified, this is the result set.

Column name | Data type | Description
OptionName | nvarchar(35) | Lists specified option_name.
CurrentSetting | char(3) | Shows current setting for option_name, on or off.

If option_value is specified, sp_serveroption returns no result set.

Permissions

Execute permissions default to the public role; however, only members of the setupadmin server role can set server options.

Examples
A. Enable a Publisher/Subscriber server

This example sets the server as a combination Publisher/Subscriber server.

USE master

EXEC sp_serveroption 'ACCOUNTS', 'dpub', 'TRUE'

B.Disable a distribution server

This example turns off the dist option for the SEATTLE2 server.

USE master

EXEC sp_serveroption 'SEATTLE2', 'dist', 'off'

C.Enable a linked server to be collation compatible with a local SQL Server

This example configures a linked server corresponding to another SQL Server, SEATTLE3, to be collation compatible with the local SQL Server.

USE master

EXEC sp_serveroption 'SEATTLE3', 'collation compatible', 'true'

See Also
sp_addlinkedserver | sp_helpserver
sp_adddistpublisher | System Stored Procedures
sp_dropdistpublisher |


sp_setapprole

Activates the permissions associated with an application role in the current database.

Syntax

sp_setapprole [@rolename =] 'role' ,
[@password =] {Encrypt N 'password'} | 'password'
[,[@encrypt =] 'encrypt_style']

Argument
[@rolename =] 'role'
Is the name of the application role defined in the current database. role is sysname, with no default. role must exist in the current database.
[@password =] {Encrypt N 'password'} | 'password'
Is the password required to activate the application role. password is sysname, with no default. password can be encrypted using the ODBC canonical Encrypt function. When using the Encrypt function, the password must be converted to a Unicode string by preceding the password with N.
[@encrypt =] 'encrypt_style'
Specifies the encryption style used by password. encrypt_style is varchar(10), and can be one of these values.

Value | Description
none | The password is not encrypted and is passed to Microsoft® SQL Server™ as clear text. This is the default.
odbc | The password is encrypted using the ODBC canonical Encrypt function before being sent to SQL Server. This can only be specified when using either an ODBC client or the OLE DB Provider for SQL Server. DB-Library clients cannot use this option.

Return Code Values

0 (success) and 1 (failure)

Remarks

Application roles do not have members; therefore, the user does not have to be added to the application role. When an application role is not activated, sp_setapprole has no effect on a user’s membership in other roles or groups in the current database.

When an application role is activated, the permissions usually associated with the user’s connection that activated the application role are ignored. The user’s connection gains the permissions associated with the application role for the database in which the application role is defined. The user’s connection can gain access to another database only through permissions granted to the guest user account in that database. Therefore, if the guest user account does not exist in a database, the connection cannot gain access to that database.

After an application role is activated with sp_setapprole, the role cannot be deactivated in the current database until the user disconnects from SQL Server.

To protect your application role password, encrypt the password using the ODBC Encrypt function and specify odbc as the encryption method.

The sp_setapprole stored procedure can be executed only by direct Transact-SQL statements; it cannot be executed within another stored procedure or from within a user-defined transaction.

Permissions

Any user can execute sp_setapprole by providing the correct password for the role.

Examples
A. Activate an application role without encrypting the password

This example activates an application role named SalesAppRole, with the clear text password AsDeFXX, created with permissions specifically designed for the application being used by the current user.

EXEC sp_setapprole 'SalesApprole', 'AsDeFXX'

B. Activate an application role and encrypt the password

This example activates the Test application role with the password pswd, but encrypts the password before sending it to SQL Server.

EXEC sp_setapprole 'Test', {Encrypt N 'pswd'}, 'odbc'

See Also
sp_addapprole | System Stored Procedures
sp_dropapprole |


sp_setnetname

Sets the network names in sysservers to their actual network computer names for remote computers running Microsoft® SQL Server™. This procedure can be used to enable execution of remote stored procedure calls to computers that have network names containing invalid SQL Server identifiers.

Syntax

sp_setnetname @server = 'server',
@network_name = 'network_name'

Arguments
@server = 'server'
Is the name of the remote server as referenced in user-coded remote stored procedure call syntax. Exactly one row in sysservers must already exist to use this server. server is sysname, with no default.
@network_name = 'network_name'
Is the network name of the computer to which remote stored procedure calls are made. network_name is sysname, with no default.

This name must match the Microsoft Windows NT® computer name, and it can include characters that are not allowed in SQL Server identifiers.

If a DB-Library alias matching the network_name is defined on the SQL Server computer, the connection string information in that alias is used to connect to the remote SQL Server.

Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

Some remote stored procedure calls to Windows NT computers can encounter problems if the computer name contains invalid identifiers. Use this procedure to differentiate the values in sysservers.srvname versus sysservers.srvnetname.

Because linked servers and remote servers reside in the same namespace, they cannot have the same name. It is possible, however, to define both a linked server and a remote server against a given server by assigning different names and using sp_setnetname to set the network name of one of them to the underlying server's network name.

--Assume sqlserv2 is actual name of SQL Server
--database server

EXEC sp_addlinkedserver 'sqlserv2'

GO

EXEC sp_addserver 'rpcserv2'

GO

EXEC sp_setnetname 'rpcserv2', 'sqlserv2'

Note Using sp_setnetname to point a linked server back to the local server is not supported. Servers referenced in this manner cannot participate in a distributed transaction.

Permissions

Execute permissions are restricted to members of the setupadmin fixed server role.

Examples

This example shows a typical administrative sequence used on SQL Server to issue the remote stored procedure call.

USE master

EXEC sp_addserver 'Win_NT1'

EXEC sp_setnetname 'Win_NT1','Win-NT1'

EXEC Win_NT1.master.dbo.sp_who

See Also
sp_addserver System Stored Procedures


sp_spaceused

Displays the number of rows, disk space reserved, and disk space used by a table in the current database, or displays the disk space reserved and used by the entire database.

Syntax

sp_spaceused [[@objname =] 'objname']
[,[@updateusage =] 'updateusage']

Arguments
[@objname =] 'objname'
Is the name of the table for which space usage information (reserved and allocated space) is requested. objname is nvarchar(776), with a default of NULL.
[@updateusage =] 'updateusage'
Indicates whether or not DBCC UPDATEUSAGE should be run within the database (when no objname is specified) or on a specific object (when objname is specified). updateusage is varchar(5), with a default of FALSE.
Return Code Values

0 (success) or 1 (failure)

Result Sets

If objname is omitted, two result sets are returned.

Column name | Data type | Description
database_name | varchar(18) | Name of the current database.
database_size | varchar(18) | Size of the current database.
unallocated space | varchar(18) | Unallocated space for the database.

Column name | Data type | Description
reserved | varchar(18) | Total amount of reserved space.
data | varchar(18) | Total amount of space used by data.
index_size | varchar(18) | Space used by indexes.
unused | varchar(18) | Amount of unused space.

If parameters are specified, this is the result set.

Column name | Data type | Description
name | nvarchar(20) | Name of the table for which space usage information was requested.
rows | char(11) | Number of rows existing in the objname table.
reserved | varchar(18) | Amount of total reserved space for objname.
data | varchar(18) | Amount of space used by data in objname.
index_size | varchar(18) | Amount of space used by the index in objname.
unused | varchar(18) | Amount of unused space in objname.

Remarks

The result set returned when running sp_spaceused with no parameters or with only updateusage includes log space usage. To obtain specific log space information, use DBCC SQLPERF(LOGSPACE).

sp_spaceused computes the amount of disk space used for data and indexes, and the disk space used by a table in the current database. If objname is not given, sp_spaceused reports on the space used by the entire current database including log space.

When updateusage is specified, SQL Server scans the data pages in the database and makes any necessary corrections to the sysindexes table regarding the storage space used by each table. There are some situations, for example, after an index is dropped, when the sysindexes information for the table may not be current. This process can take some time to run on large tables or databases. Use it only when you suspect incorrect values are being returned and when the process will not have an adverse effect on other users or processes in the database. If preferred, DBCC UPDATEUSAGE can be run separately.

Permissions

Execute permissions default to the public role.

Examples
A. Space information about a table

This example reports the amount of space allocated (reserved) for the titles table, the amount used for data, the amount used for index(es), and the unused space reserved by database objects.

USE pubs

EXEC sp_spaceused 'titles'

B. Updated space information about a complete database

This example summarizes space used in the current database and uses the optional parameter @updateusage.

USE pubs

sp_spaceused @updateusage = 'TRUE'

Permissions

Execute permissions default to the public role.

See Also
CREATE INDEX | DROP TABLE
CREATE TABLE | sp_help
DBCC SQLPERF | sp_helpindex
DROP INDEX | System Stored Procedures


sp_special_columns

Returns the optimal set of columns that uniquely identify a row in the table. Also returns columns that are automatically updated when any value in the row is updated by a transaction.

Syntax

sp_special_columns [@name =] 'name'
[,[owner =] 'owner']
[,[@qualifier =] 'qualifier']
[,[@col_type =] 'col_type']
[,[@scope =] 'scope']
[,[@nullable =] 'nullable']
[,[@ODBCVer =] 'ODBCVer']

Arguments
[@name =] 'name'
Is the name of the table used to return catalog information. name is sysname, with no default. Wildcard pattern matching is not supported.
[owner =] 'owner'
Is the table owner of the table used to return catalog information. owner is sysname, with a default of NULL. Wildcard pattern matching is not supported. If owner is not specified, the default table visibility rules of the underlying DBMS apply.

In Microsoft® SQL Server™, if the current user owns a table with the specified name, the columns of that table are returned. If owner is not specified and the current user does not own a table of the specified name, this procedure looks for a table of the specified name owned by the owner of the database. If the table exists, its columns are returned.

[@qualifier =] 'qualifier'
Is the name of the table qualifier. qualifier is sysname, with a default of NULL. Various DBMS products support three-part naming for tables (qualifier.owner.name). In SQL Server, this column represents the database name. In some products, it represents the server name of the database environment of the table.
[@col_type =] 'col_type'
Is the column type. col_type is char(1), with a default of R. Type R returns the optimal column or set of columns that, by retrieving values from the column or columns, allows any row in the specified table to be uniquely identified. A column can be either a pseudocolumn specifically designed for this purpose, or the column or columns of any unique index for the table. Type V returns the column or columns in the specified table, if any, that are automatically updated by the data source when any value in the row is updated by any transaction.
[@scope =] 'scope'
Is the minimum required scope of the ROWID. scope is char(1), with a default of T. Scope C specifies that the ROWID is valid only when positioned on that row. Scope T specifies that the ROWID is valid for the transaction.
[@nullable =] 'nullable'
Is whether or not the special columns can accept a null value. nullable is char(1), with a default of U. O specifies special columns that do not allow null values. U specifies columns that are partially nullable.
[@ODBCVer =] 'ODBCVer'
Is the ODBC version being used. ODBCVer is int(4), with a default of 2, which indicates ODBC version 2.0. For more information about the difference between ODBC version 2.0 and ODBC version 3.0, see your ODBC SQLSpecialColumns specification for ODBC version 3.0.
Return Code Values

None

Result Sets
Column name | Data type | Description
SCOPE smallint Actual scope of the row ID. Can be 0, 1, or 2. SQL Server always returns 0. This field always returns a value.

0 = SQL_SCOPE_CURROW. The row ID is guaranteed to be valid only while positioned on that row. A later reselect using the row ID may not return a row if the row was updated or deleted by another transaction.

1 = SQL_SCOPE_TRANSACTION. The row ID is guaranteed to be valid for the duration of the current transaction.

2 = SQL_SCOPE_SESSION. The row ID is guaranteed to be valid for the duration of the session (across transaction boundaries).
COLUMN_NAME | sysname | Column name for each column of the table returned. This field always returns a value.
DATA_TYPE | smallint | ODBC SQL data type.
TYPE_NAME | sysname | Data source-dependent data type name; for example, char, varchar, money, or text.
PRECISION | int | Precision of the column on the data source. This field always returns a value.
LENGTH | int | Length, in bytes, required for the data type in its binary form in the data source, for example, 10 for char(10), 4 for integer, and 2 for smallint.
SCALE | smallint | Scale of the column on the data source. NULL is returned for data types for which scale is not applicable.
PSEUDO_COLUMN smallint Indicates whether the column is a pseudocolumn. SQL Server always returns 2:
0 = SQL_PC_UNKNOWN
1 = SQL_PC_PSEUDO
2 = SQL_PC_NOT_PSEUDO

Remarks

sp_special_columns is equivalent to SQLSpecialColumns in ODBC. The results returned are ordered by SCOPE.

Permissions

Execute permissions default to the public role.

See Also

System Stored Procedures


sp_sproc_columns

Returns column information for a single stored procedure in the current environment.

Syntax

sp_sproc_columns [[@procedure_name =] 'name']
[,[@procedure_owner =] 'owner']
[,[@procedure_qualifier =] 'qualifier']
[,[@column_name =] 'column_name']
[,[@ODBCVer =] 'ODBCVer']

Arguments
[@procedure_name =] 'name'
Is the name of the procedure used to return catalog information. name is nvarchar(390), with a default of %, which means all tables in the current database. Wildcard pattern matching is not supported.
[@procedure_owner =] 'owner'
Is the name of the owner of the procedure. owner is nvarchar(384), with a default of NULL. Wildcard pattern matching is not supported. If owner is not specified, the default procedure visibility rules of the underlying DBMS apply.

In Microsoft® SQL Server™, if the current user owns a procedure with the specified name, information about that procedure is returned. If owner is not specified and the current user does not own a procedure with the specified name, sp_sproc_columns looks for a procedure with the specified name that is owned by the database owner. If the procedure exists, information about its columns is returned.

[@procedure_qualifier =] 'qualifier'
Is the name of the procedure qualifier. qualifier is sysname, with a default of NULL. Various DBMS products support three-part naming for tables (qualifier.owner.name). In SQL Server, this parameter represents the database name. In some products, it represents the server name of the table’s database environment.
[@column_name =] 'column_name'
Is a single column and is used when only one column of catalog information is desired. column_name is nvarchar(384), with a default of NULL. If column_name is omitted, all columns are returned. The value specified can include wildcard characters using the wildcard matching patterns of the underlying DBMS. For maximum interoperability, the gateway client should assume only SQL-92-standard pattern matching (the % and _ wildcard characters).
[@ODBCVer =] 'ODBCVer'
Is the version of ODBC being used. ODBCVer is int, with a default of 2, which indicates ODBC version 2.0. For more information about the difference between ODBC version 2.0 and ODBC version 3.0, refer to the ODBC SQLProcedureColumns specification for ODBC version 3.0
Return Code Values

None

Result Sets
Column name | Data type |  | Description
PROCEDURE_QUALIFIER | sysname |  | Procedure qualifier name. This column can be NULL.
PROCEDURE_OWNER | sysname |  | Procedure owner name. This column always returns a value.
PROCEDURE_NAME | nvarchar(134) |  | Procedure name. This column always returns a value.
COLUMN_NAME | sysname |  | Column name for each column of the TABLE_NAME returned. This column always returns a value.
COLUMN_TYPE | smallint |  | This field always returns a value: 0 = SQL_PARAM_TYPE_ UNKNOWN 1 = SQL_PARAM_TYPE_INPUT 2 = SQL_PARAM_TYPE_ OUTPUT 3 = SQL_RESULT_COL 4 = SQL_PARAM_OUTPUT 5 = SQL_RETURN_VALUE
DATA_TYPE | smallint |  | Integer code for an ODBC data type. If this data type cannot be mapped to an SQL-92 type, the value is NULL. The native data type name is returned in the TYPE_NAME column.
TYPE_NAME | sysname |  | String representation of the data type. This is the data type name as presented by the underlying DBMS.
PRECISION | int |  | Number of significant digits. The return value for the PRECISION column is in base 10.
LENGTH | int |  | Transfer size of the data.
SCALE | smallint |  | Number of digits to the right of the decimal point.
RADIX | smallint |  | Is the base for numeric types.
NULLABLE | smallint |  | Specifies nullability: 1 = Data type can be created allowing null values 0 = Null values are not allowed
REMARKS | varchar(254) |  | Description of the procedure column. SQL Server does not return a value for this column.
COLUMN_DEF |  | nvarchar(4000) | Default value of the column.
SQL_DATA_TYPE |  | smallint | Value of the SQL data type as it appears in the TYPE field of the descriptor. This column is the same as the DATA_TYPE column, except for the datetime and SQL-92 interval data types. This column always returns a value.
SQL_DATETIME_SUB |  | smallint | The datetime SQL-92 interval subcode if the value of SQL_DATA_TYPE is SQL_DATETIME or SQL_INTERVAL. For data types other than datetime and SQL-92 interval, this field is NULL.
CHAR_OCTET_LENGTH |  | int | Maximum length in bytes of a character or binary data type column. For all other data types, this column returns a NULL.
ORDINAL_POSITION |  | int | Ordinal position of the column in the table. The first column in the table is 1. This column always returns a value.
IS_NULLABLE |  | varchar(254) | Nullability of the column in the table. ISO rules are followed to determine nullability. An ISO SQL-compliant DBMS cannot return an empty string. Displays YES if the column can include NULLS and NO if the column cannot include NULLS. This column returns a zero-length string if nullability is unknown. The value returned for this column is different from the value returned for the NULLABLE column.
SS_DATA_TYPE | tinyint |  | SQL Server data type used by Open Data Services extended stored procedures.

Remarks

The returned columns belong to the parameters or result set of a stored procedure. If the SP_NUM_PARAMETERS and SP_NUM_RESULT_SETS columns returned by sp_stored_procedures for a particular stored procedure are -1 (indeterminate), sp_sproc_columns returns no rows for that stored procedure. In SQL Server, only the column information about input and output parameters for the stored procedure are returned.

sp_sproc_columns is equivalent to SQLProcedureColumns in ODBC. The results returned are ordered by PROCEDURE_QUALIFIER, PROCEDURE_OWNER, PROCEDURE_NAME, and the order that the parameters appear in the procedure definition.

Permissions

Execute permissions default to the public role.

See Also

System Stored Procedures


sp_srvrolepermission

Returns the permissions applied to a fixed server role.

Syntax

sp_srvrolepermission [[@srvrolename =] 'role']

Arguments
[@srvrolename =] 'role'
Is the name of the fixed server role for which permissions are returned. role is sysname, with a default of NULL. If not specified, the permissions for all fixed server roles are returned. role can be one of these values.

Value | Description
sysadmin | System administrators
securityadmin | Security administrators
serveradmin | Server administrators
setupadmin | Setup administrators
processadmin | Process administrators
diskadmin | Disk administrators
dbcreator | Database creators

Return Code Values

0 (success) or 1 (failure)

Result Sets
Column name | Data type | Description
ServerRole | sysname | Name of a fixed server role
Permission | sysname | Permission associated with ServerRole

Remarks

The permissions applied to members of fixed server roles are managed internally and are not part of the security system used to manage the permissions for the other types of security accounts.

The permissions listed include the Transact-SQL statements that can be executed, as well as other special activities that can be performed by members of the fixed server role. To display a list of the fixed server roles, execute sp_helpsrvrole.

The sysadmin fixed server role has the permissions of all the other fixed server roles.

Permissions

Execute permissions default to the public role.

Examples

This example displays the permissions associated with the sysadmin fixed server role.

EXEC sp_srvrolepermission 'sysadmin'

See Also
sp_addsrvrolemember | sp_helpsrvrole
sp_dropsrvrolemember | System Stored Procedures


sp_start_job

Instructs SQL Server Agent to execute a job immediately.

Syntax

sp_start_job [@job_name =] 'job_name' | [@job_id =] job_id
[,[@error_flag =] error_flag]
[,[@server_name =] 'server_name']
[,[@step_name =] 'step_name']
[,[@output_flag =] output_flag]

Arguments
[@job_name =] 'job_name'
Is the name of the job to start. Either job_id or job_name must be specified, but both cannot be specified. job_name is sysname, with a default of NULL.
[@job_id =] job_id
Is the identification number of the job to start. Either job_id or job_name must be specified, but both cannot be specified. job_id is uniqueidentifier, with a default of NULL.
[@error_flag =] error_flag
Reserved.
[@server_name =] 'server_name'
Is the target server on which to start the job. server_name is nvarchar(30), with a default of NULL. server_name must be one of the target servers to which the job is currently targeted.
[@step_name =] 'step_name'
Is the name of the step at which to begin execution of the job. Applies only to local jobs. step_name is sysname, with a default of NULL
[@output_flag =] output_flag
Reserved.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Permissions

Execute permissions default to the public role.

Examples

This example starts a job named Nightly Backup.

USE msdb

EXEC sp_start_job @job_name = 'Nightly Backup'

See Also
sp_delete_job | sp_update_job
sp_help_job | System Stored Procedures
sp_stop_job |


sp_statistics

Returns a list of all indexes on a specified table.

Syntax

sp_statistics [@table_name =] 'table_name'
[,[@table_owner =] 'owner']
[,[@table_qualifier =] 'qualifier']
[,[@index_name =] 'index_name]
[,[@is_unique =] 'is_unique']
[,[@accuracy =] 'accuracy']

Arguments
[@table_name =] 'name'
Specifies the table used to return catalog information. table_name is sysname, with no default. Wildcard pattern matching is not supported.
[@table_owner =] 'owner'
Is the name of the table owner of the table used to return catalog information. table_owner is sysname, with a default of NULL. Wildcard pattern matching is not supported. If owner is not specified, the default table visibility rules of the underlying DBMS apply.

In Microsoft® SQL Server™, if the current user owns a table with the specified name, the indexes of that table are returned. If owner is not specified and the current user does not own a table with the specified name, this procedure looks for a table with the specified name owned by the database owner. If one exists, the indexes of that table are returned.

[@table_qualifier =] 'qualifier'
Is the name of the table qualifier. qualifier is sysname, with a default of NULL. Various DBMS products support three-part naming for tables (qualifier.owner.name). In SQL Server, this parameter represents the database name. In some products, it represents the server name of the table’s database environment.
[@index_name =] 'index_name
Is the index name. index_name is sysname, with a default of %.
[@is_unique =] 'is_unique'
Is whether only unique indexes (if Y) are to be returned. is_unique is char(1), with a default of N.
[@accuracy =] 'accuracy'
Is the level of cardinality and page accuracy for statistics. accuracy is char(1), with a default of Q. Specify E to ensure that statistics are updated so that cardinality and pages are accurate.
Result Sets
Column name | Data type | Description
TABLE_QUALIFIER | sysname | Table qualifier name. This field can be NULL.
TABLE_OWNER | sysname | Table owner name. This field always returns a value.
TABLE_NAME | sysname | Table name. This field always returns a value.
NON_UNIQUE | smallint | NOT NULL. 0 = Unique 1 = Not unique
INDEX_QUALIFIER | sysname | Index owner name. Some DBMS products allow users other than the table owner to create indexes. In SQL Server, this column is always the same as TABLE_NAME.
INDEX_NAME | sysname | Is the name of the index. This field always returns a value.
TYPE | smallint | This field always returns a value. SQL Server returns 0, 1, 2, or 3: 0 = Statistics for a table 1 = Clustered 2 = Hashed 3 = Other
SEQ_IN_INDEX | smallint | Position of the column within the index.
COLUMN_NAME | sysname | Column name for each column of the TABLE_NAME returned. This field always returns a value.
COLLATION | char(1) | Order used in collation. SQL Server always returns A. Can be: A = Ascending D = Descending NULL = Not applicable
CARDINALITY | int | Number of rows in the table or unique values in the index.
PAGES | int | Number of pages to store the index or table.
FILTER_CONDITION | varchar(128) | SQL Server does not return a value.

Return Code Values

None

Remarks

The indexes in the result set appear in ascending order by the columns NON_UNIQUE, TYPE, INDEX_NAME, and SEQ_IN_INDEX.

The index type clustered refers to an index in which table data is stored in the order of the index. This corresponds to SQL Server clustered indexes.

The index type hashed accepts exact match or range searches, but pattern matching searches do not use the index.

sp_statistics is equivalent to SQLStatistics in ODBC. The results returned are ordered by NON_UNIQUE, TYPE, INDEX_QUALIFIER, INDEX_NAME, and SEQ_IN_INDEX.

Permissions

Execute permissions default to the public role.


sp_stop_job

Instructs SQL Server Agent to stop the execution of a job.

Syntax

sp_stop_job [@job_name =] 'job_name' | [@job_id =] job_id | [@originating_server =] 'master_server' | [@server_name =] 'target_server'

Arguments
[@job_name =] 'job_name'
Is the name of the job to stop. job_name is sysname, with a default of NULL.
[@job_id =] job_id
Is the identification number of the job to stop. job_id is uniqueidentifier, with a default of NULL.
[@originating_server =] 'master_server'
Is the name of the master server. If specified, all multiserver jobs are stopped. master_server is nvarchar(30), with a default of NULL. Specify this parameter only when calling sp_stop_job at a target server.

Note Only one of the first three parameters can be specified.

[@server_name =] 'target_server'
Is the name of the specific target server on which to stop a multiserver job. target_server is nvarchar(30), with a default of NULL. Specify this parameter only when calling sp_stop_job at a master server for a multiserver job.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

If a job is currently executing a step of type CmdExec, the process being run (for example, MyProgram.exe) is forced to end prematurely. Premature ending can result in unpredictable behavior such as files in use by the process being held open. Consequently, sp_stop_job should be used only in extreme circumstances if the job contains steps of type CmdExec.

Permissions

Execute permissions default to the public role.

Examples

This example stops a job named Archive Tables.

USE msdb

EXEC sp_stop_job @job_name = 'Archive Tables'

See Also
sp_delete_job | sp_update_job
sp_help_job | System Stored Procedures
sp_start_job |


sp_stored_procedures

Returns a list of stored procedures in the current environment.

Syntax

sp_stored_procedures [[@sp_name =] 'name']
[,[@sp_owner =] 'owner']
[,[@sp_qualifier =] 'qualifier']

Arguments
[@sp_name =] 'name'
Is the name of the procedure used to return catalog information. name is nvarchar(390), with a default of NULL. Wildcard pattern matching is supported.
[@sp_owner =] 'owner']
Is the name of the owner of the procedure. owner is nvarchar(384), with a default of NULL. Wildcard pattern matching is supported. If owner is not specified, the default procedure visibility rules of the underlying DBMS apply.

In Microsoft® SQL Server™, if the current user owns a procedure with the specified name, that procedure is returned. If owner is not specified and the current user does not own a procedure with the specified name, this procedure looks for a procedure with the specified name owned by the database owner. If one exists, that procedure is returned.

[@qualifier =] 'qualifier'
Is the name of the procedure qualifier. qualifier is sysname, with a default of NULL. Various DBMS products support three-part naming for tables (qualifier.owner.name). In SQL Server, this column represents the database name. In some products, it represents the server name of the table’s database environment.
Return Code Values

None

Result Sets
Column name | Data type | Description
PROCEDURE_QUALIFIER | sysname | Procedure qualifier name. This field can be NULL.
PROCEDURE_OWNER | sysname | Procedure owner name. This field always returns a value.
PROCEDURE_NAME | nvarchar(134) | Procedure name. This field always returns a value.
NUM_INPUT_PARAMS | int | Reserved for future use.
NUM_OUTPUT_PARAMS | int | Reserved for future use.
NUM_RESULT_SETS | int | Reserved for future use.
REMARKS | varchar(254) | Description of the procedure. SQL Server does not return a value for this column.
PROCEDURE_TYPE | smallint | Procedure type. SQL Server always returns 2.0. Can be: 0 = SQL_PT_UNKNOWN 1 = SQL_PT_PROCEDURE 2 = SQL_PT_FUNCTION

Remarks

For maximum interoperability, the gateway client should assume only SQL-92-standard pattern matching (the % and _ wildcards).

The privilege information about the current user’s execute access to a specific stored procedure is not necessarily checked, so access is not guaranteed. Note that only three-part naming is used, so that only local stored procedures, not remote stored procedures (which need four-part naming), are returned when implemented against SQL Server. If the server attribute ACCESSIBLE_SPROC is Y in the result set for sp_server_info, only stored procedures that can be executed by the current user are returned.

sp_stored_procedures is equivalent to SQLProcedures in ODBC. The results returned are ordered by PROCEDURE_QUALIFIER, PROCEDURE_OWNER, and PROCEDURE_NAME.

Permissions

Execute permissions default to the public role.

See Also

System Stored Procedures


sp_subscription_cleanup

Removes metadata when a subscription is dropped at a Subscriber. For a normal subscription, the metadata includes an entry in the system table MSreplication_subscriptions. For a synchronizing transaction subscription, it also includes synctran triggers.

Syntax

sp_subscription_cleanup [@publisher =] 'publisher',
[@publisher_db =] 'publisher_db'
[,[@publication =] 'publication']

Arguments
[@publisher =] 'publisher'
Is the name of the Publisher. publisher is sysname, with no default.
[@publisher_db =] 'publisher_db'
Is the name of the Publisher database. publisher_db is sysname, with no default.
[@publication =] 'publication'
Is the name of the publication. publication is sysname, with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_subscription_cleanup is used in all types of replication.

Permissions

Only members of the sysadmin fixed server role or the db_owner fixed database role can execute sp_subscription_cleanup.

See Also
System Stored Procedures


sp_table_privileges

Returns a list of table permissions (such as INSERT, DELETE, UPDATE, SELECT, REFERENCES) for the specified table(s).

Syntax

sp_table_privileges [@table_name_pattern =] 'table_name_pattern'
[,[@table_owner_pattern =] 'table_owner_pattern']
[,[@table_qualifier =] 'table_qualifier']

Arguments
[@table_name_pattern =] 'table_name_pattern'
Is the table used to return catalog information. table_name_pattern is nvarchar(384), with no default. Wildcard pattern matching is supported.
[@table_owner_pattern =] 'table_owner_pattern'
Is the table owner of the table used to return catalog information. table_owner_pattern is nvarchar(384), with a default of NULL. Wildcard pattern matching is supported. If the owner is not specified, the default table visibility rules of the underlying DBMS apply.

In Microsoft® SQL Server™, if the current user owns a table with the specified name, the columns of that table are returned. If owner is not specified and the current user does not own a table with the specified name, this procedure looks for a table with the specified table_name_pattern owned by the database owner. If one exists, the columns of that table are returned.

[@table_qualifier =] 'table_qualifier'
Is the name of the table qualifier. table_qualifier is sysname, with a default of NULL. Various DBMS products support three-part naming for tables (qualifier.owner.name). In SQL Server, this column represents the database name. In some products, it represents the server name of the table’s database environment.
Return Code Values

None

Result Sets
Column name | Data type | Description
TABLE_QUALIFIER | sysname | Table qualifier name. In SQL Server, this column represents the database name. This field can be NULL.
TABLE_OWNER | sysname | Table owner name. This field always returns a value.
TABLE_NAME | sysname | Table name. This field always returns a value.
GRANTOR | sysname | Database username that has granted permissions on this TABLE_NAME to the listed GRANTEE. In SQL Server, this column is always the same as the TABLE_OWNER. This field always returns a value. Also, the GRANTOR column may be either the database owner (TABLE_OWNER) or a user to whom the database owner granted permission by using the WITH GRANT OPTION clause in the GRANT statement.
GRANTEE | sysname | Database username that has been granted permissions on this TABLE_NAME by the listed GRANTOR. In SQL Server, this column always includes a database user from the sysusers table. This field always returns a value.
PRIVILEGE | sysname | One of the available table permissions. Table permissions can be one of the following values (or other values supported by the data source when implementation is defined): SELECT = GRANTEE can retrieve data for one or more of the columns. INSERT = GRANTEE can provide data for new rows for one or more of the columns. UPDATE = GRANTEE can modify existing data for one or more of the columns. DELETE = GRANTEE can remove rows from the table. REFERENCES = GRANTEE can reference a column in a foreign table in a primary key/foreign key relationship. In SQL Server, primary key/foreign key relationships are defined with table constraints. The scope of action given to the GRANTEE by a given table privilege is data source-dependent. For example, the UPDATE privilege may permit the GRANTEE to update all columns in a table on one data source and only those columns for which the GRANTOR has UPDATE privilege on another data source.
IS_GRANTABLE | sysname | Indicates whether or not the GRANTEE is permitted to grant permissions to other users (often referred to as “grant with grant” permission). Can be YES, NO, or NULL. An unknown (or NULL) value refers to a data source for which “grant with grant” is not applicable.

Remarks

The sp_table_privileges stored procedure is equivalent to SQLTablePrivileges in ODBC. The results returned are ordered by TABLE_QUALIFIER, TABLE_OWNER, TABLE_NAME, and PRIVILEGE.

Permissions

Execute permission default to public role.

Examples

This example returns privilege information about all tables with names beginning with the word sales, owned by a user with an owner name beginning with janet, from all servers with names beginning with the word LONDON.

USE master

EXEC sp_table_privileges 'LONDON%', 'janet%', 'sales%'

See Also

System Stored Procedures


sp_table_privileges_ex

Returns privilege information about the specified table from the specified linked server.

Syntax

sp_table_privileges_ex [@table_server =] 'table_server'
[,[@table_name =] 'table_name']
[,[@table_schema =] 'table_schema'
[,[@table_catalog =] 'table_catalog']

Arguments
[@table_server =] 'table_server'
Is the name of the linked server for which to return information. table_server is sysname, with no default.
[@table_name =] 'table_name']
Is the name of the table for which to provide table privilege information. table_name is sysname, with a default of NULL.
[@table_schema =] 'table_schema'
Is the table schema, which in some DBMS environments is the table owner.. table_schema is sysname, with a default of NULL.
[@table_catalog =] 'table_catalog'
Is the name of the database in which the specified table_name resides. table_catalog is sysname, with a default of NULL.
Return Code Values

None

Result Sets
Column name | Data type | Description
TABLE_CAT | sysname | Table qualifier name. Various DBMS products support three-part naming for tables (qualifier.owner.name). In SQL Server, this column represents the database name. In some products, it represents the server name of the table’s database environment. This field can be NULL.
TABLE_SCHEM | sysname | Table owner name. In SQL Server, this column represents the name of the database user who created the table. This field always returns a value.
TABLE_NAME | sysname | Table name. This field always returns a value.
GRANTOR | sysname | Database username that has granted permissions on this TABLE_NAME to the listed GRANTEE. In SQL Server, this column is always the same as the TABLE_OWNER. This field always returns a value. Also, the GRANTOR column may be either the database owner (TABLE_OWNER) or a user to whom the database owner granted permission by using the WITH GRANT OPTION clause in the GRANT statement.
GRANTEE | sysname | Database username that has been granted permissions on this TABLE_NAME by the listed GRANTOR. This field always returns a value.
PRIVILEGE | varchar(32) | One of the available table permissions. Table permissions can be one of the following values (or other values supported by the data source when implementation is defined): SELECT = GRANTEE can retrieve data for one or more of the columns. INSERT = GRANTEE can provide data for new rows for one or more of the columns. UPDATE = GRANTEE can modify existing data for one or more of the columns. DELETE = GRANTEE can remove rows from the table. REFERENCES = GRANTEE can reference a column in a foreign table in a primary key/foreign key relationship. In SQL Server, primary key/foreign key relationships are defined with table constraints. The scope of action given to the GRANTEE by a given table privilege is data source-dependent. For example, the UPDATE privilege may permit the GRANTEE to update all columns in a table on one data source and only those columns for which the GRANTOR has UPDATE privilege on another data source.
IS_GRANTABLE | varchar(3) | Indicates whether or not the GRANTEE is permitted to grant permissions to other users (often referred to as “grant with grant” permission). Can be YES, NO, or NULL. An unknown (or NULL) value refers to a data source in which “grant with grant” is not applicable.

Remarks

The results returned are ordered by TABLE_QUALIFIER, TABLE_OWNER, TABLE_NAME, and PRIVILEGE.

Permissions

Execute permission default to public role.

Examples

This example returns privilege information about the Customers table, owned by the dbo, in the Northwind database from the specified linked server (SQL Server is assumed as the linked server).

EXEC sp_table_privileges_ex London1, Customers, dbo, Northwind

See Also

sp_column_privileges_ex


sp_table_validation

Either returns rowcount or checksum information on a table or compares the provided rowcount or checksum information with the specified table.

Syntax

sp_table_validation [@table =] 'table'
[,[@expected_rowcount =] expected_rowcount]
[,[@expected_checksum =] expected_checksum]
[,[@rowcount_only =] rowcount_only]
[,[@owner =] 'owner']
[,[@full_or_fast =] full_or_fast]
[,[@shutdown_agent =] shutdown_agent]
[,[@table_name =] shutdown_agent]

Arguments
[@table =] 'table'
Is the name of the table. table is sysname, with no default.
[@expected_rowcount =] expected_rowcount
Is whether to return the expected number of rows in the table. expected_rowcount is int, with a default of NULL. If NULL, the actual rowcount is returned as an output parameter. If a value is provided, that value is checked against the actual rowcount to identify any differences.
[@expected_checksum =] expected_checksum
Is whether to return the expected checksum for the table. expected_checksum is numeric, with a default of NULL. If NULL, the actual checksum is returned as an output parameter. If a value is provided, that value is checked against the actual checksum to identify any differences.
[@rowcount_only =] rowcount_only
Is whether to return only the rowcount for the table. rowcount_only is bit, with a default of 1.
[@owner =] 'owner'
Is the name of the owner of the table. owner is sysname, with a default of NULL.
[@full_or_fast =] full_or_fast
Is the method used to calculate the rowcount. full_or_fast is tinyint, with a default of 2, and can be one of these values.

Value | Description
0 | Does full count using COUNT(*).
1 | Does fast count from sysindexes.rows. Counting rows in sysindexes is much faster than counting rows in the actual table. However, because sysindexes is lazily updated, the rowcount may not be accurate.
2 (default) | Does conditional fast counting by first trying the fast method. If fast method shows differences, reverts to full method. If expected_rowcount is NULL and the stored procedure is being used to get the value, a full COUNT(*) is always used.

[@shutdown_agent =] shutdown_agent
If the Distribution Agent is executing sp_table_validation, is whether the Distribution Agent should shut down immediately upon completion of the validation. shutdown_agent is bit, with a default of 0. If 0, the replication agent does not shut down. If 1, error 20578 is raised and the replication agent is signaled to shut down.
[@table_name =] table_name
Is the table name of the view used for output messages. table_name is sysname, with a default of table.
Return Code Values

If performing a checksum validation and the expected checksum equals the checksum in the table, sp_table_validation returns a message that the table passed checksum validation. Otherwise, it returns a message that the table may be out of synchronization and reports the difference between the expected and the actual number of rows.

If performing a rowcount validation and the expected number of rows equals the number in the table, sp_table_validation returns a message that the table passed rowcount validation. Otherwise, it returns a message that the table may be out of synchronization and reports the difference between the expected and the actual number of rows.

Remarks

sp_table_validation is used in all types of replication

Permissions

Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_table_validation.

See Also
sp_article_validation | System Stored Procedures
sp_publication_validation |


sp_tableoption

Sets option values for user-defined tables.

Syntax

sp_tableoption [@TableNamePattern =] 'table'
[,[@OptionName =] 'option_name']
[,[@OptionValue =] 'value']

Arguments
[@TableNamePattern =] 'table'
Is the qualified or nonqualified name of a user-defined database table. If a fully qualified table name, including a database name, is provided, the database name must be the name of the current database. Table options for multiple tables can no longer be set at the same time. table_pattern is nvarchar(776), with no default.
[@OptionName =] 'option_name'
Is a table option name. option_name is varchar(35), with a default of NULL, which lists all available table options and the corresponding default values assigned to new tables (0 = false or off, 1 = true or on). option_name can have these values.

Value | Description
pintable | When disabled (the default), it marks the table as no longer RAM-resident. When enabled, marks the table as RAM-resident.
table lock on bulk load | When disabled (the default), it causes the bulk load process on user-defined tables to obtain row locks. When enabled, it causes the bulk load processes on user-defined tables to obtain a bulk update lock.
insert row lock | For Microsoft® SQL Server™ version 6.5, enabled or disabled Insert Row Locking (IRL) operations on the specified table. Row-level locking is enabled by default in SQL Server version 7.0. The locking strategy of SQL Server is row locking with possible promotion to page or table locking. This option does not alter the locking behavior of SQL Server (it has no effect) and is included only for compatibility of existing scripts and procedures. In a future version of SQL Server, this option may not be supported.

[@OptionValue =] 'value'
Is whether the option_name is enabled (true or on) or disabled (false or off). value is varchar(12), with a default of NULL, which lists the current settings for all matching tables.
Return Code Values

0 (success) or error number (failure)

Result Sets
Column name | Data type | Description
Available Table Options | nvarchar(35) | List of available table options
Default Value | int | Default values of the associated with the table option

Permissions

Only members of the sysadmin fixed server role can modify the pintable table option.

Members of the sysadmin fixed server role or the db_owner fixed database role can modify the insert row lock option for any user-defined table. Other users can modify options only for tables they own.

Any user can run sp_tableoption to generate a report listing table option values for all user-defined tables.

Examples
A. Display the available table options for the sales table and their default values

USE pubs

EXEC sp_tableoption 'sales'

B. Display the option value for the specified option

USE pubs

EXEC sp_tableoption 'sales', 'pintable'

C. Disable the pintable option for the sales table

USE pubs

EXEC sp_tableoption 'sales', 'pintable', 'false'

See Also
DBCC PINTABLE | System Stored Procedures
DBCC UNPINTABLE |


sp_tables

Returns a list of objects that can be queried in the current environment (any object that can appear in a FROM clause).

Syntax

sp_tables [[@name =] 'name']
[,[@owner =] 'owner']
[,[@qualifier =] 'qualifier']
[,[@type =] "type"]

Arguments
[@name =] 'name'
Is the table used to return catalog information. name is nvarchar(384), with a default of NULL. Wildcard pattern matching is supported.
[@owner =] 'owner'
Is the table owner of the table used to return catalog information. owner is nvarchar(384), with a default of NULL. Wildcard pattern matching is supported. If the owner is not specified, the default table visibility rules of the underlying DBMS apply.

In Microsoft® SQL Server™, if the current user owns a table with the specified name, the columns of that table are returned. If the owner is not specified and the current user does not own a table with the specified name, this procedure looks for a table with the specified name owned by the database owner. If one exists, the columns of that table are returned.

[@qualifier =] 'qualifier'
Is the name of the table qualifier. qualifier is sysname, with a default of NULL. Various DBMS products support three-part naming for tables (qualifier.owner.name). In SQL Server, this column represents the database name. In some products, it represents the server name of the table’s database environment.
[,[@type =] "'type'"]
Is a list of values, separated by commas, that gives information about all tables of the table type(s) specified, including TABLE, SYSTEM TABLE, and VIEW. type is varchar(100), with a default of NULL.

Note Single quotation marks must surround each table type, and double quotation marks must enclose the entire parameter. Table types must be uppercase. If SET QUOTED_IDENTIFIER is ON, each single quotation mark must be doubled and the entire parameter must be surrounded by single quotation marks.

Return Code Values

None

Result Sets
Column name | Data type | Description
TABLE_QUALIFIER | sysname | Table qualifier name. In SQL Server, this column represents the database name. This field can be NULL.
TABLE_OWNER | sysname | Table owner name. In SQL Server, this column represents the name of the database user who created the table. This field always returns a value.
TABLE_NAME | sysname | Table name. This field always returns a value.
TABLE_TYPE | varchar(32) | Table, system table, or view.
REMARKS | varchar(254) | SQL Server does not return a value for this column.

Remarks

For maximum interoperability, the gateway client should assume only SQL-92-standard SQL pattern matching (the % and _ wildcards).

Privilege information about the current user’s read or write access to a specific table is not always checked, so access is not guaranteed. This result set includes not only tables and views, but also synonyms and aliases for gateways to DBMS products that support those types. If the server attribute ACCESSIBLE_TABLES is Y in the result set for sp_server_info, only tables that are accessible by the current user are returned.

sp_tables is equivalent to SQLTables in ODBC. The results returned are ordered by TABLE_TYPE, TABLE_QUALIFIER, TABLE_OWNER, and TABLE_NAME.

Permissions

Execute permission default to public role.

Examples

A. Return a list of objects that can be queried in the current environment

EXEC sp_tables

B. Return information about the syscolumns table in the Company database

EXEC sp_tables syscolumns, dbo, Company, "'SYSTEM TABLE'"


sp_tables_ex

Returns table information on the tables from the specified linked server.

Syntax

sp_tables_ex [@table_server =] 'table_server'
[,[@table_name =] 'table_name']
[,[@table_schema =] 'table_schema']
[,[@table_catalog =] 'table_catalog']
[,[@table_type =] 'table_type']

Arguments
[@table_server =] 'table_server'
Is the name of the linked server for which to return table information. table_server is sysname, with no default.
[,[@table_name =] 'table_name']
Is the name of the table for which to return data type information. table_name is sysname, with a default of NULL.
[@table_schema =] 'table_schema']
Is the table schema. table_schema is sysname, with a default of NULL.
[@table_catalog =] 'table_catalog'
Is the name of the database in which the specified table_name resides. table_catalog is sysname, with a default of NULL.
[@table_type =] 'table_type'
Is the type of the table to return. table_type is sysname, with a default of NULL, and can have one of these values.

Value | Description
ALIAS | Name of an alias
GLOBAL TEMPORARY | Name of a temporary table available system wide
LOCAL TEMPORARY | Name of a temporary table available only to the current job
SYNONYM | Name of a synonym
SYSTEM TABLE | Name of a system table
TABLE | Name of a user table
VIEW | Name of a view

Return Code Values

None

Result Sets
Column name | Data type | Description
TABLE_CAT | sysname | Table qualifier name. Various DBMS products support three-part naming for tables (qualifier.owner.name). In SQL Server, this column represents the database name. In some products, it represents the server name of the table’s database environment. This field can be NULL.
TABLE_SCHEM | sysname | Table owner name. In SQL Server, this column represents the name of the database user who created the table. This field always returns a value.
TABLE_NAME | sysname | Table name. This field always returns a value.
TABLE_TYPE | varchar(32) | Table, system table, or view.
REMARKS | varchar(254) | SQL Server does not return a value for this column.

Remarks

sp_tables_ex is executed by querying the TABLES rowset of the IDBSchemaRowset interface of the OLE DB provider corresponding to table_server. The table_name, table_schema, table_catalog, and column parameters are passed to this interface to restrict the rows returned.

sp_tables_ex returns an empty result set if the OLE DB provider of the specified linked server does not support the TABLES rowset of the IDBSchemaRowset interface.

Permissions

Execute permission default to the public role.

Examples

This example returns table information about the titles table in the pubs database, on the LONDON2 linked server.

USE master

EXEC sp_tables_ex 'LONDON2', 'titles', 'dbo', 'pubs', NULL

See Also
sp_catalogs | sp_indexes
sp_columns_ex | sp_linkedservers
sp_column_privileges | sp_table_privileges
sp_foreignkeys | System Stored Procedures


sp_unbindefault

Unbinds (removes) a default from a column or from a user-defined data type in the current database.

Syntax

sp_unbindefault [@objname =] 'object_name'
[, [@futureonly =] 'futureonly_flag']

Arguments
[@objname =] 'object_name'
Is the name of the table and column or the user-defined data type from which the default is to be unbound. object_name is nvarchar(776), with no default. If the parameter is not of the form table.column, object_name is assumed to be a user-defined data type. When unbinding a default from a user-defined data type, any columns of that data type that have the same default are also unbound. Columns of that data type with defaults bound directly to them are unaffected.
[@futureonly =] 'futureonly_flag'
Is used only when unbinding a default from a user-defined data type. futureonly_flag is varchar(15), with a default of NULL. When futureonly_flag is futureonly, existing columns of the data type do not lose the specified default.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

To display the text of a default, execute sp_helptext with the name of the default as the parameter.

When a default is bound to a column, the information about binding is removed from the syscolumns table. When a default is bound to a user-defined data type, the information is removed from the systypes table.

Permissions

Execute permissions default to the owner of the specified object.

Examples
A. Unbind a default from a column

This example unbinds the default from the hiredate column of an employees table.

EXEC sp_unbindefault 'employees.hiredate'

B. Unbind a default from a user-defined data type

This example unbinds the default from the user-defined data type ssn. It unbinds existing and future columns of that type.

EXEC sp_unbindefault 'ssn'

C. Use the futureonly_flag

This example unbinds future uses of the user-defined data type ssn without affecting existing ssn columns.

EXEC sp_unbindefault 'ssn', 'futureonly'

D. Use delimited identifiers

This example shows the use of delimited identifiers in object_name.

CREATE TABLE [t.3] (c1 int) -- Notice the period as part of the table

-- name.

CREATE DEFAULT default2 AS 0

GO

EXEC sp_bindefault 'default2', '[t.3].c1'

-- The object contains two periods;

-- the first is part of the table name and the second

-- distinguishes the table name from the column name.

EXEC sp_unbindefault '[t.3].c1'

See Also
CREATE DEFAULT | sp_helptext
DROP DEFAULT | System Stored Procedures
sp_bindefault |


sp_unbindrule

Unbinds a rule from a column or a user-defined data type in the current database.

Syntax

sp_unbindrule [@objname =] 'object_name'
[, [@futureonly =] 'futureonly_flag']

Arguments
[@objname =] 'object_name'
Is the name of the table and column or the user-defined data type from which the rule is unbound. object_name is nvarchar(776), with no default. If the parameter is not of the form table.column, object_name is assumed to be a user-defined data type. When unbinding a rule from a user-defined data type, any columns of the data type that have the same rule are also unbound. Columns of that data type with rules bound directly to them are unaffected.
[@futureonly =] 'futureonly_flag'
Is used only when unbinding a rule from a user-defined data type. futureonly_flag is varchar(15), with a default of NULL. When futureonly_flag is futureonly, existing columns of that data type do not lose the specified rule.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

To display the text of a rule, execute sp_helptext with the rule name as the parameter.

When a rule is unbound, the information about the binding is removed from the syscolumns table if the rule was bound to a column, and from the systypes table if the rule was bound to a user-defined data type.

When a rule is unbound from a user-defined data type, it is also unbound from any columns having that user-defined data type. The rule may also still be bound to columns whose data types were later changed by the ALTER COLUMN clause of an ALTER TABLE statement, you must specifically unbind the rule from these columns using sp_unbindrule and specifying the column name.

Permissions

Execute permissions default to the object owner.

Examples
A. Unbind a rule from a column

This example unbinds the rule from the startdate column of an employees table.

EXEC sp_unbindrule 'employees.startdate'

B. Unbind a rule from a user-defined data type

This example unbinds the rule from the user-defined data type ssn. It unbinds the rule from existing and future columns of that type.

EXEC sp_unbindrule ssn

C. Use the future_only flag

This example unbinds the rule from the user-defined data type ssn without affecting existing ssn columns.

EXEC sp_unbindrule 'ssn', 'futureonly'

D. Use delimited identifiers

This example shows the use of delimited identifiers in the object_name.

CREATE TABLE [t.4] (c1 int) -- Notice the period as part of the table

-- name.

GO

CREATE RULE rule2 AS @value > 100

GO

EXEC sp_bindrule rule2, '[t.4].c1' -- The object contains two

-- periods; the first is part of the table name and the second

-- distinguishes the table name from the column name.

GO

EXEC sp_unbindrule '[t.4].c1'

See Also
CREATE RULE | sp_helptext
DROP RULE | System Stored Procedures
sp_bindrule |


sp_update_agent_profile

Updates the profile for a type of replication agent.

Syntax

sp_update_agent_profile [@agent_type =] agent_type,
[@agent_id = ] agent_id, [@profile_id = ] profile_id

Arguments
[@agent_type =] 'agent_type'
Is the type of agent. agent_type is int, with no default, and can be one of these values.

Value | Description
1 | Snapshot Agent
2 | Log Reader Agent
3 | Distribution Agent
4 | Merge Agent

[@agent_id = ] agent_id
Is the ID of the agent. agent_id is int, with no default.
[@profile_id = ] profile_id
Is the ID of the default configuration for the type of agent. profile_id is int, with no default.
Return Code Values

0 (success) or 1 (failure)

Remarks

sp_update_agent_profile is used in all types of replication.

Permissions

Only members of the sysadmin fixed server role can execute sp_update_agent_profile.

See Also
sp_add_agent_profile | sp_help_agent_profile
sp_change_agent_profile | System Stored Procedures
sp_drop_agent_profile |


sp_update_alert

Updates the settings of an existing alert.

Syntax

sp_updatealert [@name =] 'name'
[, [@new_name =] 'new_name']
[, [@enabled =] enabled]
[, [@message_id =] message_id]
[, [@severity =] severity]
[, [@delay_between_responses =] delay_between_responses]
[, [@notification_message =] 'notification_message']
[, [@include_event_description_in =] include_event_description_in]
[, [@database_name =] 'database_name']
[, [@event_description_keyword =] 'event_description_keyword']
[, [@job_id =] job_id | [@job_name =] 'job_name']
[, [@occurrence_count = ] occurrence_count]
[, [@count_reset_date =] count_reset_date]
[, [@count_reset_time =] count_reset_time]
[, [@last_occurrence_date =] last_occurrence_date]
[, [@last_occurrence_time =] last_occurrence_time]
[, [@last_response_date =] last_response_date]
[, [@last_response_time =] last_response _time]
[, [@raise_snmp_trap =] raise_snmp_trap]
[, [@performance_condition =] 'performance_condition']
[, [@category_name =] 'category']

Arguments
[@name =] 'name'
Is the name of the alert that is to be updated. name is sysname, with no default.
[@new_name =] 'new_name'
Is a new name for the alert. The name must be unique. new_name is sysname, with a default of NULL.
[@enabled =] enabled
Specifies whether the alert is enabled (1) or not enabled (0). enabled is tinyint, with a default of NULL. An alert must be enabled to fire.
[@message_id =] message_id
Is a new message or error number for the alert definition. Typically, message_id corresponds to an error number in the sysmessages table. message_id is int, with a default of NULL. A message ID can be used only if the severity level setting for the alert is 0.
[@severity =] severity
Is a new severity level (1 through 25) for the alert definition. Any Microsoft® SQL Server™ message sent to the Windows NT application log with the specified severity will activate the alert. severity is int, with a default of NULL. A severity level can be used only if the message ID setting for the alert is 0.
[@delay_between_responses =] delay_between_responses
Is the new waiting period, in seconds, between responses to the alert. delay_between_responses is int, with a default of NULL.
[@notification_message =] 'notification_message'
Is the revised text of an additional message that is sent to the operator as part of the e-mail, net send, or pager notification. notification_message is nvarchar(512), with a default of NULL.
[@include_event_description_in =] include_event_description_in
Is whether the description of the SQL Server error from the Windows NT application log should be included in the notification message. include_event_description_in is tinyint, with a default of NULL, and can be one or more of these values.

Value | Description
0 | None
1 | E-mail
2 | Pager
4 | net send

[@database_name =] 'database_name'
Is the name of the database in which the error must occur for the alert to fire. database_name is sysname, with a default of NULL.
[@event_description_keyword =] 'event_description_keyword'
Is a sequence of characters that must be found in the description of the error in the error message log. Transact-SQL LIKE expression pattern-matching characters can be used. event_description_keyword is nvarchar(100), with a default of NULL. This parameter is useful for filtering object names (for example, %customer_table%).
[@job_id =] job_id
Is the job identification number. job_id is uniqueidentifier, with a default of NULL. If job_id is specified, job_name must be omitted.
[@job_name =] 'job_name'
Is the name of the job that executes in response to this alert. job_name is sysname, with a default of NULL. If job_name is specified, job_id must be omitted.
[@occurrence_count = ] occurrence_count
Resets the number of times the alert has occurred. occurrence_count is int, with a default of NULL, and can be set only to 0.
[@count_reset_date =] count_reset_date
Resets the date the occurrence count was last reset. count_reset_date is int, with a default of NULL.
[@count_reset_time =] count_reset_time
Resets the time the occurrence count was last reset. count_reset_time is int, with a default of NULL.
[@last_occurrence_date =] last_occurrence_date
Resets the date the alert last occurred. last_occurrence_date is int, with a default of NULL, and can be set only to 0.
[@last_occurrence_time =] last_occurrence_time
Resets the time the alert last occurred. last_occurrence_time is int, with a default of NULL, and can be set only to 0.
[@last_response_date =] last_response_date
Resets the date the alert was last responded to by the SQL Server Agent service. last_response_date is int, with a default of NULL, and can be set only to 0.
[@last_response_time =] last_response_time
Resets the time the alert was last responded to by the SQL Server Agent service. last_response_time is int, with a default of NULL, and can be set only to 0.
[@raise_snmp_trap =] raise_snmp_trap
Reserved.
[@performance_condition =] 'performance_condition'
Is a value expressed in the format ‘item comparator value’. performance_condition is nvarchar(512), with a default of NULL, and consists of these elements.

Format element | Description
item | A performance object, performance counter, or named instance of the counter
comparator | One of these operators: >, <, =
value | Numeric value of the counter

[@category_name =] 'category'
The name of the alert category. category is sysname with a default of NULL
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

sp_update_alert must be run from the msdb database.

Only sysmessages written to the Microsoft® Windows NT® application log can fire an alert.

sp_update_alert changes only those alert settings for which parameter values are supplied. If a parameter is omitted, the current setting is retained.

Permissions

Only members of the sysadmin fixed server role can execute sp_update_alert.

Examples

This example changes the enabled setting of Test Alert to 0.

sp_updatealert @name = 'Test Alert', @enabled = 0

See Also
sp_add_alert | System Stored Procedures
sp_help_alert |


sp_update_category

Changes the name of a category.

Syntax

sp_update_category [@class =] 'class',
[@name =] 'old_name',
[@new_name =] 'new_name'

Arguments
[@class =] 'class'
Is the class of the category to update. class is varchar(8), with no default, and can be one of these values.

Value | Description
ALERT | Updates an alert category.
JOB | Updates a job category.
OPERATOR | Updates an operator category.

[@name =] 'old_name'
Is the current name of the category. old_name is sysname, with no default.
[@new_name =] 'new_name'
Is the new name for the category. new_name is sysname, with no default.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

sp_update_category must be run from the msdb database.

Permissions

Only members of the sysadmin fixed server role or db_owner fixed database role can execute sp_update_category.

Examples

This example renames a job category from Table Archixes to Table Archives.

USE msdb

EXEC sp_update_category 'JOB', 'Table Archixes', 'Table Archives'

See Also
sp_add_category | sp_help_category
sp_delete_category | System Stored Procedures


sp_update_job

Changes the attributes of a job.

Syntax

sp_update_job [@job_id =] job_id | [@job_name =] 'job_name'
[, [@new_name =] 'new_name']
[, [@enabled =] enabled]
[, [@description =] 'description']
[, [@start_step_id =] step_id]
[, [@category_name =] 'category']
[, [@owner_login_name =] 'login']
[, [@notify_level_eventlog =] eventlog_level]
[, [@notify_level_email =] email_level]
[, [@notify_level_netsend =] netsend_level]
[, [@notify_level_page =] page_level]
[, [@notify_email_operator_name =] 'email_name']
[, [@notify_netsend_operator_name =] 'netsend_operator']
[, [@notify_page_operator_name =] 'page_operator']
[, [@delete_level =] delete_level]
[, [@automatic_post =] automatic_post]

Arguments
[@job_id =] job_id
Is the identification number of the job to be updated. job_id is uniqueidentifier, with a default of NULL.
[@job_name =] 'job_name'
Is the name of the job. job_name is sysname, with a default of NULL.

Note Either job_id or job_name must be specified, but both cannot be specified.

[@new_name =] 'new_name'
Is the new name for the job. new_name is sysname, with a default of NULL.
[@enabled =] enabled
Specifies whether the job is enabled (1) or not abled (0). enabled is tinyint, with a default of NULL.
[@description =] 'description'
Is the description of the job. description is nvarchar(512), with a default of NULL.
[@start_step_id =] step_id
Is the identification number of the first step to execute for the job. step_id is int, with a default of NULL.
[@category_name =] 'category'
Is the category of the job. category is sysname, with a default of NULL.
[@owner_login_name =] 'login'
Is the name of the login that owns the job. login is sysname, with a default of NULL. Only members of the sysadmin fixed server role can change job ownership.
[@notify_level_eventlog =] eventlog_level
Specifies when to place an entry in the Microsoft® Windows NT® application log for this job. eventlog_level is int, with a default of NULL, and can be one of these values.

Value | Description (action)
0 | Never
1 | On success
2 | On failure
3 | Always

[@notify_level_email =] email_level
Specifies when to send an e-mail upon the completion of this job. email_level is int, with a default of NULL. email_level uses the same values as eventlog_level.
[@notify_level_netsend =] netsend_level
Specifies when to send a network message upon the completion of this job. netsend_level is int, with a default of NULL. netsend_level uses the same values as eventlog_level.
[@notify_level_page =] page_level
Specifies when to send a page upon the completion of this job. page_level is int, with a default of NULL. page_level uses the same values as eventlog_level.
[@notify_email_operator_name =] 'email_name'
Is the e-mail name of the person to whom the e-mail is sent when email_level is reached. email_name is sysname, with a default of NULL.
[@notify_netsend_operator_name =] 'netsend_operator'
Is the name of the operator to whom the network message is sent. netsend_operator is sysname, with a default of NULL.
[@notify_page_operator_name =] 'page_operator'
Is the name of the operator to whom a page is sent. page_operator is sysname, with a default of NULL.
[@delete_level =] delete_level
Specifies when to delete the job. delete_value is int, with a default of NULL. delete_level uses the same values as eventlog_level.
[@automatic_post =] automatic_post
Reserved.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

sp_update_job must be run from the msdb database.

sp_update_job changes only those settings for which parameter values are supplied. If a parameter is omitted, the current setting is retained.

Permissions

Execute permissions default to the public role.

Examples

This example changes the name and description, and disables the job Archive Tables.

USE msdb

EXEC sp_update_job @job_name  = 'Archive Tables',

    @new_name = 'Archive Tables - Disabled'

    @description = 'Job disabled until end of project'

    @enabled = 0

See Also
sp_add_job | sp_help_job
sp_delete_job | System Stored Procedures


sp_update_jobschedule

Changes the schedule settings for the specified job.

Syntax

sp_update_jobschedule [@job_id =] job_id, | [@job_name =] 'job_name',
[@name =] 'name'
[, [@new_name =] 'new_name']
[, [@enabled =] enabled]
[, [@freq_type =] freq_type]
[, [@freq_interval =] freq_interval]
[, [@freq_subday_type =] freq_subday_type]
[, [@freq_subday_interval =] freq_subday_interval]
[, [@freq_relative_interval =] freq_relative_interval]
[, [@freq_recurrence_factor =] freq_recurrence_factor]
[, [@active_start_date =] active_start_date]
[, [@active_end_date =] active_end_date]
[, [@active_start_time =] active_start_time]
[, [@active_end_time =] active_end_time]

Arguments
[@job_id =] job_id
Is the identification number of the job to which the schedule belongs. job_id is uniqueidentifier, with a default of NULL.
[@job_name =] 'job_name'
Is the name of the job to which the schedule belongs. Each job name must be unique. job_name is sysname, with a default of NULL.

Note Either job_id or job_name must be specified, but both cannot be specified.

[@name =] 'name'
Is the name of the schedule to modify. name is sysname, with no default.
[@new_name =] 'new_name'
Is a new name for the schedule. new_name is sysname, with a default of NULL.
[@enabled =] enabled
Specifies whether the schedule is enabled (1) or not enabled (0). enabled is tinyint, with a default of NULL.
[@freq_type =] freq_type
Specifies how often the job is run. freq_type is int, with a default of NULL, and can be one of these values.

Value | Description
1 | Once.
4 | Daily.
8 | Weekly.
16 | Monthly.
32 | Monthly, relative to the freq interval.
64 | Run when SQL Server Agent starts.
128 | Run when the computer is idle.

[@freq_interval =] freq_interval
Specifies the days that the job is run. freq_interval is int, with a default of NULL. The value of freq_interval depends on the value of freq_type.

Value of freq_type | Effect on freq_interval
1 (once) | freq_interval is unused.
4 (daily) | Every freq_interval days.
8 (weekly) freq_interval is one or more of the following (ORed together):
1 = Sunday
2 = Monday
4 = Tuesday
8 = Wednesday
16 = Thursday
32 = Friday
64 = Saturday
16 (monthly) | On the freq_interval day of the month.
32 (monthly relative) freq_interval can be one of these values:
1 = Sunday
2 = Monday
3 = Tuesday
4 = Wednesday
5 = Thursday
6 = Friday
7 = Saturday
8 = Day
9 = Weekday
10 = Weekend day
64 (when SQL Server Agent starts) | freq_interval is unused.

[@freq_subday_type =] freq_subday_type
Specifies the units for freq_subday_interval. freq_subday_type is int, with a default of NULL, and can be one of these values.

Value | Description (unit)
0x1 | At the specified time
0x4 | Minutes
0x8 | Hours

[@freq_subday_interval =] freq_subday_interval
Specifies the number of freq_subday_type periods to occur between each execution of the job. freq_subday_interval is int, with a default of NULL.
[@freq_relative_interval =] freq_relative_interval
Specifies the scheduled job’s occurrence of the freq_interval in each month, if freq_interval is 32 (monthly relative). freq_relative_interval is int, with a default of NULL, and can be one of these values.

Value | Description (unit)
1 | First
2 | Second
4 | Third
8 | Fourth
16 | Last

[@freq_recurrence_factor =] freq_recurrence_factor
Specifies the number of months between the scheduled execution of the job. freq_recurrence_factor is used only if freq_type is 8, 16, or 32. freq_recurrence_factor is int, with a default of NULL.
[@active_start_date =] active_start_date
Is the date on which execution of the job can begin. active_start_date is int, with a default of NULL. Values must be formatted as YYYYMMDD. If active_start_date is not NULL, the date must be greater than or equal to 19900101.
[@active_end_date =] active_end_date
Is the date on which execution of the job can stop. active_end_date is int, with a default of NULL. Values must be formatted as YYYYMMDD.
[@active_start_time =] active_start_time
Is the time on any day between active_start_date and active_end_date to begin execution of the job. active_start_time is int, with a default of NULL. Values must be entered using the form HHMMSS.
[@active_end_time =] active_end_time
Is the time on any day between active_start_date and active_end_date to end execution of the job. active_end_time is int, with a default of NULL. Values must be entered using the form HHMMSS.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

sp_update_jobschedule must be run from the msdb database.

Updating a job schedule increments the job’s version number.

Permissions

Execute permissions default to the public role.

Examples

This example disables and changes the name of the Monday Archive schedule of the Archive Tables job.

USE msdb

EXEC sp_update_jobschedule @job_name = 'Archive Tables',

    @name = 'Monday Archive',

    @newname = 'Monday Archive - DEACTIVATED',

    @enabled = 0

See Also
sp_add_jobschedule | sp_help_jobschedule
sp_delete_jobschedule | System Stored Procedures


sp_update_jobstep

Changes the setting for a step in a job that is used to perform automated activities.

Syntax

sp_update_jobstep [@job_id =] job_id, | [@job_name =] 'job_name',
[@step_id =] step_id
[, [@step_name =] 'step_name']
[, [@subsystem =] 'subsystem']
[, [@command =] 'command']
[, [@additional_parameters =] 'parameters']
[, [@cmdexec_success_code =] success_code]
[, [@on_success_action =] success_action]
[, [@on_success_step_id =] success_step_id]
[, [@on_fail_action =] fail_action]
[, [@on_fail_step_id =] fail_step_id]
[, [@server =] 'server']
[, [@database_name =] 'database']
[, [@database_user_name =] 'user']
[, [@retry_attempts =] retry_attempts]
[, [@retry_interval =] retry_interval]
[, [@os_run_priority =] run_priority]
[, [@output_file_name =] 'file_name']
[, [@flags =] flags]

Arguments
[@job_id =] job_id
Is the identification number of the job to which the step belongs. job_id is uniqueidentifier, with a default of NULL.
[@job_name =] 'job_name'
Is the name of the job to which the step belongs. job_name is sysname, with a default of NULL.

Note Either job_id or job_name must be specified, but both cannot be specified.

[@step_id =] step_id
Is the identification number for the job step to be modified. This number cannot be changed. step_id is int, with no default.
[@step_name =] 'step_name'
Is a new name for the step. step_name is sysname, with a default of NULL.
[@subsystem =] 'subsystem'
Is the subsystem used by SQL Server Agent to execute command. subsystem is nvarchar(40), with a default of NULL.
[@command =] 'command'
Is the command(s) to be executed through subsystem. command is nvarchar(3200), with a default of NULL.
[@additional_parameters =] 'parameters'
Reserved.
[@cmdexec_success_code =] success_code
Is the value returned by a CmdExec subsystem command to indicate that command executed successfully. success_code is int, with a default of NULL.
[@on_success_action =] success_action
Is the action to perform if the step succeeds. success_action is tinyint, with a default of NULL, and can be one of these values.

Value | Description (action)
1 | Quit with success.
2 | Quit with failure.
3 | Go to next step.
4 | Go to step success_step_id.

[@on_success_step_id =] success_step_id
Is the identification number of the step in this job to execute if step succeeds and success_action is 4. success_step_id is int, with a default of NULL.
[@on_fail_action =] fail_action
Is the action to perform if the step fails. fail_action is tinyint, with a default of NULL and can have one of these values.

Value | Description (action)
1 | Quit with success.
2 | Quit with failure.
3 | Go to next step.
4 | Go to step fail_step_id.

[@on_fail_step_id =] fail_step_id
Is the identification number of the step in this job to execute if the step fails and fail_action is 4. fail_step_id is int, with a default of NULL.
[@server =] 'server'
Reserved. server is nvarchar(30), with a default of NULL.
[@database_name =] 'database'
Is the name of the database in which to execute a TSQL step. database is sysname, with a default of NULL.
[@database_user_name =] 'user'
Is the name of the user account to use when executing a TSQL step. user is sysname, with a default of NULL.
[@retry_attempts =] retry_attempts
Is the number of retry attempts to use if this step fails. retry_attempts is int, with a default of NULL.
[@retry_interval =] retry_interval
Is the amount of time in minutes between retry attempts. retry_interval is int, with a default of NULL.
[@os_run_priority =] run_priority
Reserved.
[@output_file_name =] 'file_name'
Is the name of the file in which the output of this step is saved. file_name is nvarchar(200), with a default of NULL. This parameter is only valid with commands running in TSQL or CmdExec subsystems.
[@flags =] flag
Is an option that controls behavior. flags is int, and can be one of these values.

Value | Description
2 | Append to output file.
4 | Overwrite output file.
0 (default) | No options set.

Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

sp_update_jobstep must be run from the msdb database.

Updating a job step increments the job's version number.

Permissions

Execute permissions default to the public role.

Examples

This example changes the name of step 4 of the Archive Tables job to Sales Detail.

USE msdb

EXEC sp_update_jobstep @job_name = 'Archive Tables', @step_id = 4,

    @step_name = 'Sales Detail'

See Also
sp_delete_jobstep | System Stored Procedures
sp_help_jobstep |


sp_update_notification

Updates the notification method of an alert notification.

Syntax

sp_update_notification [@alert_name =] 'alert',
[@operator_name =] 'operator',
[@notification_method =] notification

Arguments
[@alert_name =] 'alert'
Is the name of the alert associated with this notification. alert is sysname, with no default.
[@operator_name =] 'operator'
Is the operator who will be notified when the alert occurs. operator is sysname, with no default.
[@notification_method =] notification
Is the method by which the operator is notified. notification is tinyint, with no default, and can be one or more of these values.

Value | Description
1 | E-mail
2 | Pager
4 | net send

Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

sp_update_notification must be run from the msdb database.

You can update a notification for an operator who does not have the necessary address information using the specified notification_method. If a failure occurs when sending an e-mail message or pager notification, the failure is reported in the SQL Server Agent error log.

Permissions

Only members of the sysadmin fixed server role can execute sp_update_notification.

Examples

This example modifies the notification method for notifications sent to stevenb for the alert Test Alert.

USE msdb

EXEC sp_update_notification 'Test Alert', 'stevenb', 7

See Also
sp_add_notification | sp_help_notification
sp_delete_notification | System Stored Procedures


sp_update_operator

Updates information about an operator (notification recipient) for use with alerts and jobs.

Syntax

sp_updateoperator [@name =] 'name'
[, [@new_name =] 'new_name']
[, [@enable =] enabled]
[, [@email_address =] 'email_address']
[, [@pager_address =] 'pager_number']
[, [@weekday_pager_start_time =] weekday_pager_start_time]
[, [@weekday_pager_end_time =] weekday_pager_end_time]
[, [@saturday_pager_start_time =] saturday_pager_start_time]
[, [@saturday_pager_end_time =] saturday_pager_end_time]
[, [@sunday_pager_start_time =] sunday_pager_start_time]
[, [@sunday_pager_end_time =] sunday_pager_end_time]
[, [@pager_days =] pager_days]
[, [@netsend_address =] 'netsend_address']
[, [@category_name =] 'category']

Arguments
[@name =] 'name'
Is the name of the operator to modify. name is sysname, with no default.
[@new_name =] 'new_name'
Is the new name for the operator. This name must be unique. new_name is sysname, with a default of NULL.
[@enable =] enabled
Is a number indicating the operator’s current status (1 if currently enabled, 0 if not). enabled is tinyint, with a default of NULL. If not enabled, an operator will not receive alert notifications.
[@email_address =] 'email_address'
Is the e-mail address of the operator. This string is passed directly to the e-mail system. email_address is nvarchar(100), with a default of NULL.
[@pager_address =] 'pager_number'
Is the pager address of the operator. This string is passed directly to the e-mail system. pager_number is nvarchar(100), with a default of NULL.
[@weekday_pager_start_time =] weekday_pager_start_time
Specifies the time after which a pager notification can be sent to this operator, Monday through Friday. weekday_pager_start_time is int, with a default of NULL, and must be entered in the form HHMMSS for use with a 24-hour clock.
[@weekday_pager_end_time =] weekday_pager_end_time
Specifies the time after which a pager notification cannot be sent to the specified operator, Monday through Friday. weekday_pager_end_time is int, with a default of NULL, and must be entered in the form HHMMSS for use with a 24-hour clock.
[@saturday_pager_start_time =] saturday_pager_start_time
Specifies the time after which a pager notification can be sent to the specified operator on Saturdays. saturday_pager_start_time is int, with a default of NULL, and must be entered in the form HHMMSS for use with a 24-hour clock.
[@saturday_pager_end_time =] saturday_pager_end_time
Specifies the time after which a pager notification cannot be sent to the specified operator on Saturdays. saturday_pager_end_time is int, with a default of NULL, and must be entered in the form HHMMSS for use with a 24-hour clock.
[@sunday_pager_start_time =] sunday_pager_start_time
Specifies the time after which a pager notification can be sent to the specified operator on Sundays. sunday_pager_start_time is int, with a default of NULL, and must be entered in the form HHMMSS for use with a 24-hour clock.
[@sunday_pager_end_time =] sunday_pager_end_time
Specifies the time after which a pager notification cannot be sent to the specified operator on Sundays. sunday_pager_end_time is int, with a default of NULL, and must be entered in the form HHMMSS for use with a 24-hour clock.
[@pager_days =] pager_days
Specifies the days that the operator is available to receive pages (subject to the specified start/end times). pager_days is tinyint, with a default of NULL, and must be a value from 0 through 127. pager_days is calculated by adding the individual values for the required days. For example, Monday through Friday is 2+4+8+16+32 = 62.

Value | Description
1 | Sunday
2 | Monday
4 | Tuesday
8 | Wednesday
16 | Thursday
32 | Friday
64 | Saturday

[@netsend_address =] 'netsend_address'
Is the network address of the operator to whom the network message is sent. netsend_address is nvarchar(100), with a default of NULL.
[@category_name =] 'category'
Is the name of the category for this alert. category is sysname, with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

sp_updateoperator must be run from the msdb database.

Permissions

Only members of the sysadmin fixed server role can execute sp_update_operator.

Examples

This example updates the operator status to enabled, and sets the days (Monday through Friday, 8 A.M. through 5 P.M.) when he can be paged.

USE msdb

EXEC sp_updateoperator @name = 'Steven Buchanan', @enabled = 1,
    @email_address = 'stevenb',
    @pager_address = '5673218@mypagerco.com',
    @weekday_pager_start_time = 080000,
    @weekday_pager_end-time = 170000,
    @pager_days = 62

See Also
sp_add_operator | sp_help_operator
sp_delete_operator | System Stored Procedures


sp_updatestats

Runs UPDATE STATISTICS against all user-defined tables in the current database.

Syntax

sp_updatestats

Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Remarks

sp_updatestats displays messages indicating its progress. When the update is completed, it reports that statistics have been updated for all tables.

Permissions

Only members of the sysadmin fixed server role and db_owner fixed database role can execute sp_updatestats.

Examples

This example updates the statistics for tables in the pubs database.

USE pubs

EXEC sp_updatestats

See Also
CREATE INDEX | sp_createstats
CREATE STATISTICS | sp_dboption
DBCC SHOW_STATISTICS | UPDATE STATISTICS
DROP STATISTICS | System Stored Procedures
sp_autostats |


sp_update_targetservergroup

Changes the name of the specified target server group.

Syntax

sp_update_targetservergroup [@name =] 'current_name'
[, [@new_name =] 'new_name']

Arguments
[@name =] 'current_name'
Is the name of the target server group. current_name is sysname, with no default.
[@new_name =] 'new_name'
Is the new name for the target server group. new_name is sysname, with no default.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Permissions

Only members of the sysadmin fixed server role can execute sp_update_targetservergroup.

Remarks

sp_update_targetservergroup must be run from the msdb database.

Examples

This example updates the target server group of Weekly Bakups to Weekly Backups.

USE msdb

EXEC sp_update_targetservergroup 'Weekly Bakups', 'Weekly Backups'

See Also
sp_add_targetservergroup | sp_delete_targetservergroup
sp_help_targetservergroup | System Stored Procedures


sp_updatetask

sp_updatetask is provided for backward compatibility only.

Updates information about a task.

Important For information about syntax used in earlier versions of SQL Server, see the Microsoft SQL Server Transact-SQL Reference for version 6.x.

Remarks

For task management, use SQL Server Enterprise Manager.

Permissions

Execute permissions default to the public role.

See Also
sp_addtask | System Stored Procedures
sp_droptask |


sp_validname

Checks for valid Microsoft® SQL Server™ identifier names. All nonbinary and nonzero data, including Unicode data that can be stored by using the nchar, nvarchar, or ntext data types, are accepted as valid characters for identifier names.

Syntax

sp_validname [@name =] 'name'
[, [@raise_error =] raise_error]

Arguments
[@name =] 'name'
Is the name of the identifier for which to check validity. name is sysname, with no default. name cannot be NULL, cannot be an empty string, and cannot contain a binary-zero character.
[@raise_error =] raise_error
Specifies whether to raise an error. raise_error is bit, with a default of 1, which means that errors should appear. 0 causes no error messages to appear.
Return Code Values

0 (success) or 1 (failure)

Result Sets

None

Permissions

Execute permissions default to the public role.

See Also
Data Types | nchar and nvarchar
NCHAR | System Stored Procedures
ntext, text, and image |


sp_validatelogins

Reports information about orphaned Microsoft® Windows NT® users and groups that no longer exist in the Windows NT environment but still have entries in the Microsoft SQL Server™ system tables.

Syntax

sp_validatelogins

Return Code Values

0 (success) or 1 (failure)

Result Sets
Column name | Data type | Description
SID | varbinary(85) | Windows NT security identifier of the Windows NT user or group
NT Login | sysname | Name of the Windows NT user or group

Remarks

The entries in the system tables for the orphaned Windows NT users and groups can only be removed by using sp_revokelogin. If the Windows NT user or group has a user account in a database, the user account can be removed using sp_revokedbaccess. The user account in the database must be removed before the login can be revoked access to connect to SQL Server.

If the Windows NT user or group owns objects in a database, these objects must be removed, or their ownership must be given to another user using sp_changeobjectowner.

Permissions

Only members of the sysadmin or securityadmin fixed server roles can execute sp_validatelogins.

Examples

This example displays the Windows NT users and groups that no longer exist but are still granted access to connect to SQL Server.

EXEC sp_validatelogins

GO

SID                                                        NT Login

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

0x0105000000000005150000007961275C521FE65395177650FC030000 dom\andrew

0x0105000000000005150000007961275C521FE65395177650FA030000 dom\joe

0x0105000000000005150000007961275C521FE65395177650FB030000 dom\margaret

0x0105000000000005150000007961275C521FE65395177650F3030000 dom\mike

See Also
sp_changeobjectowner | sp_revokelogin
sp_revokedbaccess | System Stored Procedures


sp_who

Provides information about current Microsoft® SQL Server™ users and processes. The information returned can be filtered to return only those processes that are not idle.

Syntax

sp_who [[@login_name =] 'login']

Arguments
[@login_name =] 'login'
Is a user login name on SQL Server. login is sysname, with a default of NULL. If no name is specified, the procedure reports all active users of SQL Server. login can also be a specific process identification number (SPID). To return information on active processes, specify ACTIVE. ACTIVE excludes from the report processes that are waiting for the next command from the user.
Return Code Values

0 (success) or 1 (failure)

Result Sets
Column | Data type | Description
spid | smallint | The system process ID.
status | nchar(30) | The process status.
loginame | nchar(128) | The login name associated with the particular process.
hostname | nchar(128) | The host or computer name for each process.
blk | char(5) | The system process ID for the blocking process, if one exists. Otherwise, this column is zero.
dbname | nchar(128) | The database used by the process.
cmd | nchar(16) | The SQL Server command (Transact-SQL statement, SQL Server internal engine process, and so on) executing for the process.

Remarks

A blocking process (which may have an exclusive lock) is one that is holding resources that another process needs.

Permissions

Execute permissions default to the public role.

Examples
A. List all current processes

This example uses sp_who without parameters to report all current users. In this example, process ID 11 (a SELECT on a table) is blocked by process ID 10 (an uncommitted transaction).

USE master

EXEC sp_who

Here is the result set:

spid   status    loginame hostname  blk   dbname     cmd
----- ---------  -------- --------- ----- ---------- ----------------
1     sleeping   sa                 0     master     MIRROR HANDLER
2     sleeping   sa                 0     master     LAZY WRITER
3     sleeping   sa                 0     master     CHECKPOINT SLEEP
4     sleeping   sa                 0     master     RA MANAGER
10    sleeping   janetl   SEATTLE1  0     pubs       AWAITING COMMAND
11    runnable   stevenb  LONDON2   10    pubs       SELECT

B. List a specific user’s process

This example shows how to view information about a single current user by login name.

USE master

EXEC sp_who 'janetl'

C. Display all active processes

USE master

EXEC sp_who 'active'

D. Display a specific process with process ID

USE master

EXEC sp_who '10' --specifies the process_id

See Also
KILL | System Stored Procedures
sp_lock |


xp_cmdshell

Executes a given command string as an operating-system command shell and returns any output as rows of text. Grants nonadministrative users permissions to execute xp_cmdshell.

Note When executing xp_cmdshell with the Microsoft® Windows® 95/98 operating system, the return code from xp_cmdshell will not be set to the process exit code of the invoked executable. The return code will always be 0.

Syntax

xp_cmdshell {'command_string'} [, no_output]

Arguments
'command_string'
Is the command string to execute at the operating-system command shell. command_string is varchar(255) or nvarchar(4000), with no default.
no_output
Is an optional parameter executing the given command_string, and does not return any output to the client.
Return Code Values

0 (success) or 1 (failure)

Result Sets

Executing this xp_cmdshell statement returns a directory listing of the current directory.

xp_cmdshell 'dir *.exe'

The rows are returned in an nvarchar(255) column.

Executing this xp_cmdshell statement returns the following result set:

xp_cmdshell 'dir *.exe', NO_OUTPUT

Here is the result:

The command(s) completed successfully.

Remarks

xp_cmdshell operates synchronously, control is not returned until the command shell command completes.

When you grant execute permissions to users, the users can execute any operating-system command at the Microsoft Windows NT® command shell that the account running Microsoft SQL Server™ (usually a local system account) has privilege to execute.

To restrict xp_cmdshell access to users who have administrator permissions on the Windows NT-based computer on which SQL Server is running, use SQL Setup or SQL Server Enterprise Manager to set the server options, changing the xp_cmdshell - Impersonates Client option. With this option selected, only users who are connected to SQL Server through a trusted connection and who are members of the local Administrators group on that computer are allowed to use xp_cmdshell. The commands run by xp_cmdshell continue to execute in the security context of the server.

Usually, xp_cmdshell executes Windows NT commands in SQL Server’s security context, which by default is a user account with local administrator authority. When a nonsystem administrator executes xp_cmdshell with the new configuration option set, the requested command runs in the SQLAgentCmdExec user account, which is the same account used by SQL Server Agent for scheduled tasks entered by nonsystem administrators.

To restrict xp_cmdshell access to users who have administrator permissions on the Windows NT-based computer on which SQL Server is running, configure the server at the SQL Server Properties dialog box, click the Security tab, and check Non-administrators use SQLAgentCmdExec account when executing commands via xp_cmdshell.

Note If you select the Non-administrators use SQLAgentCmdExec account when executing commands via xp_cmdshell box and the client logs on to SQL Server as a member of the sysadmin fixed server role, the command is executed under SQL Server’s security context instead of the SQLAgentCmdExec security context.

Permissions

Execute permissions for xp_cmdshell default to members of the sysadmin fixed server role but can be granted to other users.

Important If you choose not to use a local administrator account for the MSSQLServer service, users who are not members of the sysadmin fixed server role cannot execute xp_cmdshell.

Examples
A. Return a list of executable files

This example shows the xp_cmdshell extended stored procedure executing a directory command.

EXEC master..xp_cmdshell 'dir *.exe'

B. Use Windows NT net commands

This example shows the use of xp_cmdshell in a stored procedure. This example notifies users (with net send) that SQL Server is about to be shut down, pauses the server (with net pause), and then shuts the server down (with net stop).

CREATE PROC shutdown10

AS

EXEC xp_cmdshell 'net send /domain:SQL_USERS ''SQL Server shutting down
    in 10 minutes. No more connections allowed.', no_output

EXEC xp_cmdshell 'net pause sqlserver'

WAITFOR DELAY '00:05:00'

EXEC xp_cmdshell 'net send /domain: SQL_USERS ''SQL Server shutting down
    in 5 minutes.', no_output

WAITFOR DELAY '00:04:00'

EXEC xp_cmdshell 'net send /domain:SQL_USERS ''SQL Server shutting down
    in 1 minute. Log off now.', no_output

WAITFOR DELAY '00:01:00'

EXEC xp_cmdshell 'net stop sqlserver', no_output

C. Return no output

This example uses xp_cmdshell to execute a command string without returning the output to the client.

USE master

EXEC xp_cmdshell 'copy c:\sqldumps\pubs.dmp \\server2\backups\sqldumps',
    NO_OUTPUT

D. Use return status

In this example, the xp_cmdshell extended stored procedure also suggests return status. The return code value is stored in the variable @result.

DECLARE @result int

EXEC @result = xp_cmdshell 'dir *.exe'

IF (@result = 0)

    PRINT 'Success'

ELSE

    PRINT 'Failure'

E. Write variable contents out to file

This example writes the contents of the current directory to a file named dir_out.txt in the current server directory.

DECLARE @cmd sysname, @var sysname

SET @var = 'dir /p'

SET @cmd = 'echo ' + @var + ' > dir_out.txt'

EXEC master..xp_cmdshell @cmd

See Also
CREATE PROCEDURE | System Stored Procedures (General Extended Procedures)
EXECUTE |


xp_deletemail

Deletes a message from the Microsoft® SQL Server™ inbox. xp_deletemail is used by sp_processmail to process mail in the SQL Server inbox.

Syntax

xp_deletemail {'message_number'}

Arguments
'message_number'
Is the number (assigned by xp_findnextmsg) of the mail message in the inbox that should be deleted. message_number is varchar(255), with no default.
Return Code Values

0 (success) or 1 (failure)

Result Sets

xp_deletemail returns this result set when passed a valid message ID.

The command(s) completed successfully.

Remarks

Any failure except an invalid parameter is logged to the Microsoft Windows NT® application log.

Permissions

Execute permissions for xp_deletemail default to members of the sysadmin fixed server role but can granted to other users.

Examples

This example deletes the message ID supplied from xp_findnextmsg. The value from xp_findnextmsg is placed in the local variable @message_id.

DECLARE @message_id varchar(255)

SET @message_id = 'XA17' -- Setting to a value would go here.

USE master

EXEC xp_deletemail @message_id

See Also
sp_processmail | xp_startmail
xp_findnextmsg | xp_stopmail
xp_readmail | System Stored Procedures (SQL Mail Extended Procedures
xp_sendmail |


xp_enumgroups

Provides a list of local Microsoft® Windows NT® groups or a list of global groups defined in a specified Windows NT domain.

Syntax

xp_enumgroups ['domain_name']

Arguments
'domain_name'
Is the name of the Windows NT domain for which to enumerate a list of global groups. domain_name is sysname, with a default of NULL.
Return Code Values

0 (success) or 1 (failure)

Result Sets
Column name | Data type | Description
group | sysname | Name of the Windows NT group
comment | sysname | Description of the Windows NT group provided by Windows NT

Remarks

If domain_name is the name of the Windows NT-based computer that Microsoft SQL Server™ is running on, or no domain name is specified, xp_enumgroups enumerates the local groups from the computer running SQL Server.

xp_enumgroups cannot be used when SQL Server is running on Windows® 95/98.

Permissions

Execute permissions for xp_enumgroups default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example lists the groups in the sales domain.

EXEC xp_enumgroups 'sales'

See Also
sp_grantlogin | xp_logininfo
sp_revokelogin | System Stored Procedures(General Extended Procedures)
xp_loginconfig |


xp_findnextmsg

Accepts a message ID for input and returns the message ID for output. xp_findnextmsg is used with sp_processmail in order to process mail in the Microsoft® SQL Server™ inbox.

Syntax

xp_findnextmsg [[@msg_id =] 'message_number' [OUTPUT]]
[,[@type =] type]
[,[@unread_only =] 'unread_value'])

Arguments
[@msg_id =] 'message_number'
Is an input and output parameter that specifies the string of the message on input and the string of the next message on output.
OUTPUT
When specified, message_number is placed in the output parameter. When not specified, message_number is returned as a single-column, single-row result set.
[@type =] type
Is the input message type based on the MAPI mail definition:

IP[M | C].Vendorname.subclass

If type is NULL, message types beginning with IPM appear in the inbox of the mail client and are found or read by xp_findnextmsg. Message types beginning with IPC do not appear in the inbox of the mail client and must be found or read by setting the type parameter. The default is NULL.

[@unread_only =] 'unread_value'
Is whether only unread (true) messages are considered. The default is FALSE, which means all messages are considered.
Return Code Values

0 (success) or 1 (failure)

Result Sets

xp_findnextmsg returns this result set when passed a valid message ID:

The command(s) completed successfully.

Remarks

Any failure except an invalid parameter is logged to the Microsoft Windows NT® application log.

Permissions

Execute permissions for xp_findnextmsg default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example retrieves the status when searching for the next message ID (for only unread messages). The value from xp_findnextmsg is placed in the local variable @message_id.

DECLARE @status int, @message_id varchar(255)

-- SET @status = value would be here.

-- SET @message_id = value would be here.

EXEC @status = xp_findnextmsg @msg_id = @message_id OUTPUT

See Also
sp_processmail | xp_startmail
xp_deletemail | xp_stopmail
xp_readmail | System Stored Procedures(SQL Mail Extended Procedures)
xp_sendmail |


xp_grantlogin

Grants a Microsoft® Windows NT® group or user access to Microsoft SQL Server™. xp_grantlogin is provided for backward compatibility. Use sp_grantlogin.

Syntax

xp_grantlogin {[@loginame =] 'login'} [,[@logintype =] 'logintype']

Arguments
[@loginame =] 'login'
Is the name of the Windows NT user or group to be added. The Windows NT user or group must be qualified with a Windows NT domain name in the form Domain\User. login is sysname, with no default.
[@logintype =] 'logintype'
Is the security level of the login being granted access. logintype is varchar(5), with a default of NULL. Only admin can be specified. If admin is specified, login is granted access to SQL Server, and added as a member of the sysadmin fixed server role.
Return Code Values

0 (success) or 1 (failure)

Remarks

xp_grantlogin is now a system stored procedure rather than an extended stored procedure and calls sp_grantlogin to grant a Windows NT-based group or user access to SQL Server.

See Also
sp_denylogin | xp_loginconfig
sp_grantlogin | xp_logininfo
sp_revokelogin | System Stored Procedures(General Extended Procedures)
xp_enumgroups |


xp_logevent

Logs a user-defined message in the Microsoft® SQL Server™ log file and in the Microsoft Windows NT® Event Viewer. xp_logevent can be used to send an alert without sending a message to the client.

Syntax

xp_logevent {error_number, 'message'} [, 'severity']

Arguments
error_number
Is a user-defined error number greater than 50,000. The maximum value is 1073741823 (230 - 1).
'message'
Is a character string of less than 8,000 characters.
'severity'
Is one of three character strings: INFORMATIONAL, WARNING, or ERROR. severity is optional, with a default of INFORMATIONAL.
Return Code Values

0 (success) or 1 (failure)

Result Sets

xp_logevent returns this error message for the included code example:

The command(s) completed successfully.

Remarks

When sending messages from Transact-SQL procedures, triggers, batches, and so on, use the RAISERROR statement instead of xp_logevent. xp_logevent does not call a client’s message handler or set @@ERROR. To write messages to the Windows NT Event Viewer and to the SQL Server error log file within SQL Server, execute the RAISERROR statement.

Permissions

Execute permissions for xp_logevent default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example logs the message (with variables passed to the message) in the Windows NT Event Viewer.

DECLARE @@TABNAME varchar(30)

DECLARE @@USERNAME varchar(30)

DECLARE @@MESSAGE varchar(255)

SET @@TABNAME = 'customers'

SET @@USERNAME = USER_NAME()

SELECT @@MESSAGE = 'The table ' + @@TABNAME + ' is not owned by the user
    ' + @@USERNAME + '.'

USE master

EXEC xp_logevent 60000, @@MESSAGE, informational

See Also
PRINT | System Stored Procedures (General Extended Procedures)
RAISERROR |


xp_loginconfig

Reports the login security configuration of Microsoft® SQL Server™ when running on Microsoft Windows NT®.

Syntax

xp_loginconfig ['config_name']

Arguments
'config_name'
Is the configuration value to be displayed. If config_name is not specified, all configuration values are reported. config_name is sysname, with a default of NULL, and can be one of these values.

Value | Description
login mode | Login security mode. Possible values are Mixed and Windows NT Authentication.
default login | Name of the default SQL Server login ID for authorized users of trusted connections (for users without matching login name). The default login is guest. Provided for backward compatibility.
default domain | Name of the default Windows NT domain for network users of trusted connections. The default domain is the domain that the Windows NT computer running SQL Server is a member of. Provided for backward compatibility.
audit level | Audit level. Possible values are none, success, failure, and all. Audits are written to the error log and to the Windows NT Event Viewer.
set hostname | Indicates whether the hostname from the client login record is replaced with the Windows NT network username. Possible values are true or false. If this is set, the network username appears in output from sp_who.
map _ | Reports what special Windows NT characters are mapped to the valid SQL Server character _ (underscore). Possible values are domain separator (default), space, null, or any single character. Provided for backward compatibility.
map $ | Reports what special Windows NT characters are mapped to the valid SQL Server character $ (dollar sign). Possible values are domain separator, space, null, or any single character. The default is space. Provided for backward compatibility.
map # | Reports what special Windows NT characters are mapped to the valid SQL Server character # (number sign). Possible values are domain separator, space, null, or any single character. Default is the hyphen. Provided for backward compatibility.

Return Code Values

0 (success) or 1 (failure)

Result Sets
Column name | Data type | Description
name | sysname | Configuration value
config value | sysname | Configuration value setting

Remarks

xp_loginconfig cannot be used to set configuration values.

Use SQL Server Enterprise Manager to set the login mode and audit level.

Permissions

Execute permissions for xp_loginconfig default to members of the sysadmin fixed server role but can be granted to other users.

Examples
A. Report all configuration values

This example shows all of the currently configured settings.

EXEC xp_loginconfig

name | config_value
---------------- | -------------------------
login mode | mixed
default login | guest
default domain | REDMOND
audit level | none
set hostname | false
map _ | domain separator
map $ | space
map # | -

B. Report login mode configuration value

This example shows the setting for only the login mode.

EXEC xp_loginconfig 'login mode'

name | config_value
---------------- | -------------------------
login mode | mixed

See Also
sp_denylogin | xp_logininfo
sp_grantlogin | System Stored Procedures(General Extended Procedures)
sp_revokelogin |


xp_logininfo

Reports the account, the type of account, the privilege level of the account, the mapped login name of the account, and the permission path by which an account has access to Microsoft® SQL Server™.

Syntax

xp_logininfo [[@acctname =] 'account_name'] [,[@option =] 'all' | 'members']
[,[@privelege =] variable_name OUTPUT]

Arguments
[@acctname =] 'account_name'
Is the name of a Microsoft Windows NT® user or group granted access to SQL Server. account_name is sysname, with a default of NULL. If account_name is not given, all groups and users that have been explicitly granted login permission are reported. The Windows NT user or group must be qualified by the Windows NT domain or computer name to which the account belongs.
'all' | 'members'
Specifies whether to report information on all permission paths for the account, or to report information on the members of the Windows NT group. @option is varchar(10), with a default of NULL. Unless all is specified, only the first permission path is displayed.
[@privelege =] variable_name
Is an output parameter that returns the privilege level of the specified Windows NT account. variable_name is varchar(10), with a default of ‘Not wanted’. The privilege level returned is user, admin, or null.
OUTPUT
When specified, places variable_name in the output parameter.
Return Code Values

0 (success) or 1 (failure)

Result Sets
Column name | Data type | Description
account name | nchar(128) | Fully qualified Windows NT account name.
type | char(8) | Type of Windows NT account. Valid values are user or group.
privelege | char(9) | Access privilege for SQL Server. Valid values are admin, user, or null.
mapped login name | nchar(128) | For user accounts with user privilege, mapped login name shows the mapped login name that SQL Server tries to use when logging in with this account, using the mapped rules with the domain name added before it.
permission path | nchar(128) | Group membership that allowed the account access.

Remarks

If account_name is specified as the first parameter, xp_logininfo reports the highest privilege level access for that account. If a user has access as a system administrator and as a user, only the system administrator level (highest privilege) entry is reported. If the user is a member of multiple groups that have the same privilege level, only the first group that matches is reported (the order of the groups is the order that the groups were granted access to SQL Server), and a maximum of one result row is returned.

If account_name is a valid Windows NT account but that account does not have permission to access SQL Server, an empty result set is returned. If account_name cannot be identified as a valid Windows NT account, an error message is returned.

If account_name and all are specified, all permission paths for that account are listed. If account_name is a member of multiple groups, all of which have been granted access to SQL Server, multiple rows are returned. The admin privilege rows are reported before the user privilege rows, and within a privilege level the row order is the order in which the accounts were granted access to SQL Server. account_name applies to both individual users and groups.

If account_name and members is specified, a list of the next-level members of the group is returned. If account_name is a local group, the listing can include local users, domain users, and global groups. If account_name is a global account, the list consists of domain users. If account_name is a user account, an error message is returned.

Permissions

Execute permissions for xp_logininfo default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example displays information about the BUILTIN\Administrators Windows NT group.

EXEC xp_logininfo 'BUILTIN\Administrators'

See Also
sp_denylogin | xp_loginconfig
sp_grantlogin | System Stored Procedures(General Extended Procedures)
sp_revokelogin |


xp_msver

Returns and allows to be queried Microsoft® SQL Server™ version information. In addition to version information regarding the actual build number of the server, various environment information is also returned. This information can be used within Transact-SQL statements, batches, stored procedures, and so on, to enhance logic for platform-independent code.

Syntax

xp_msver [optname]

Arguments
optname
Is the name of an option, and can be one of the following.

Option/Column name | Description
ProductName | Product name; for example, Microsoft SQL Server.
ProductVersion | Product version; for example, 7.00.419 where 7.00 is the version and 419 is the Microsoft internal build number.
Language | The language version of SQL Server.
Platform | Operating-system name, manufacturer name, and chip family name for the computer running SQL Server. For example, NT INTEL X86 indicates Microsoft Windows NT® as the operating system, Intel as the chip manufacturer, and a 486 or higher processor.
Comments | Miscellaneous information about SQL Server.
CompanyName | Company name that produces SQL Server; for example, Microsoft Corporation.
FileDescription | The operating system.
FileVersion | Version of the SQL Server executable. For example, 1998.02.01 indicates a file version of February 1, 1998, on the Sqlservr.exe file.
InternalName | Microsoft internal name for SQL Server; for example, SQLSERVR.
LegalCopyright | Legal copyright information required for SQL Server; for example, Copyright© Microsoft Corp. 1998.
LegalTrademarks | Legal trademark information required for SQL Server. For example, Microsoft® is a registered trademark of Microsoft Corporation.
OriginalFilename | File name executed at SQL Server startup; for example, Sqlservr.exe.
PrivateBuild | Reserved.
SpecialBuild | Reserved.
WindowsVersion | Microsoft Windows version installed on the computer running SQL Server. For example, 4.0 indicates version 4.0 of Microsoft Windows NT, and 1381 indicates the internal build number.
ProcessorCount | The number of processors in the computer running SQL Server.
ProcessorActiveMask | Indicates what processors installed in the computer running SQL Server are activated and usable by Microsoft Windows NT.
ProcessorType | Processor type. Similar to Platform.
PhysicalMemory | Amount in megabytes (MB) of RAM installed on the computer running SQL Server. For example, 32 indicates 32 MB of RAM.
Product ID | Product ID (PID) number, which is specified during installation. This number is located on a sticker on the original SQL Server compact disc case.

Return Code Values

0 (success) or 1 (failure)

Result Sets

xp_msver, without any parameters, returns this four-column result set (values may vary):

Index  Name                     Internal_Value Character_Value

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

1      ProductName              NULL           Microsoft SQL

                                             Server

2      ProductVersion           458752         7.00.498

3      Language                 1033           English (United

                                             States)

4      Platform                 NULL           NT INTEL X86

5      Comments                 NULL           NT INTEL X86

6      CompanyName              NULL           Microsoft

                                             Corporation

7      FileDescription          NULL             SQL Server

                                             Windows NT

8      FileVersion              NULL           1998.05.25

9      InternalName             NULL           SQLSERVR

10     LegalCopyright           NULL             Copyright ©

                                             Microsoft Corp. 1998

11     LegalTrademarks          NULL           Microsoft® is a

                                             registered trademark of                                                  Microsoft Corporation.                                                  Windows(TM) is a                                                          trademark of Microsoft                                                  Corporation

12     OriginalFilename         NULL           SQLSERVR.EXE

13     PrivateBuild             NULL           NULL

14     SpecialBuild             262242         NULL

15     WindowsVersion           90505220       4.0 (1381)

16     ProcessorCount           1              1

17     ProcessorActiveMask      1              00000001

18     ProcessorType            586            PROCESSOR_INTEL_PENTIUM

19     PhysicalMemory           63             63 (66510848)

20     Product ID               NULL           NULL

(20 row(s) affected)

xp_msver, for any option, returns the four-column headings with values for that option. For example, this result set is returned when xp_msver is executed with the FileDescription option.

xp_msver FileDescription

Index  Name                      Internal_Value Character_Value

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

7      FileDescription           NULL           SQL Server Windows NT

(1 row(s) affected)

Permissions

Execute permissions default to the public role.

See Also
@@VERSION | System Stored Procedures (General Extended Procedures)
System Functions |


xp_readmail

Reads a mail message from the Microsoft® SQL Server™ mail inbox. This procedure is used by sp_processmail to process all mail in the SQL Server inbox.

Syntax

xp_readmail [[@msg_id =] 'message_number'] [, [@type =] 'type' [OUTPUT]]
[,[@peek =] 'peek']
[,[@suppress_attach =] 'suppress_attach']
[,[@originator =] 'sender' OUTPUT]
[,[@subject =] 'subject' OUTPUT]
[,[@message =] 'message' OUTPUT]
[,[@recipients =] 'recipients [;…n]' OUTPUT]
[,[@cc_list =] 'copy_recipients [;…n]' OUTPUT]
[,[@bcc_list =] 'blind_copy_recipients [;…n]' OUTPUT]
[,[@date_received =] 'date' OUTPUT]
[,[@unread =] 'unread_value' OUTPUT]
[,[@attachments =] 'attachments [;…n]' OUTPUT])
[,[@skip_bytes =] bytes_to_skip OUTPUT]
[,[@msg_length =] length_in_bytes OUTPUT]
[,[@originator_address =] 'sender_address' OUTPUT]]

Arguments
[@msg_id =] 'message_number'
Is the number of the message to read. message_number is varchar(255), with no default.
'type'
Is the message type to return based on the MAPI mail definition:

IP[M | C].Vendorname.subclass

If used on input, this must define the type for a specific message; type is ignored on input if the message_number is NULL. type is varchar(255), with a default of NULL.

OUTPUT
When specified, places the value of the specified parameter in the output parameter.
[@peek =] 'peek'
Is whether SQL Server returns the message of the mail without changing the mail status to read. peek is varchar(5), with a default of FALSE. If set to false, the mail is treated as though it has been read. If set to true, the mail is treated as though it has not been read.
[@suppress_attach =] 'suppress_attach'
Is whether mail attachments are suppressed. suppress_attach is varchar(255), with a default of TRUE (do not create temporary files). If set to true, SQL Server prevents the creation of temporary files when xp_readmail reads a message with attachments. If set to false, there is no prevention of temporary files when messages with attachments are read.
[@originator =] 'sender'
Is the returned mail address of the sender. sender is varchar(255), with no default.
[@subject =] 'subject'
Is the returned the subject of the mail message. subject is varchar(255), with no default.
[@message =] 'message'
Is the returned message (body) (the actual text) of the mail message. message is varchar(8000), with no default.
[@recipients =] 'recipients [;…n]'
Is the semicolon-separated list of the recipients for the mail message to be returned. Recipients’ names are separated by a semicolon (;). recipient_list is varchar(255), with no default.
[@cc_list =] 'copy_recipients [;…n]'
Is the semicolon-separated list of the copied recipients (cc:’ed) for the mail message to be returned. Recipients’ names are separated by a semicolon (;). cc_list is varchar(255), with no default.
[@bcc_list =] 'blind_copy_recipients [;…n]'
Is the semicolon-separated list for the blind copy recipients (bcc:’ed) of the mail message to be returned. Recipients’ names are separated by a semicolon (;). bcc_list is varchar(255), with no default.
[@date_received =] 'date'
Is the returned date of the mail message. date is varchar(255), with no default.
[@unread =] 'unread_value'
Is whether a message has been previously unread (true) or not (false). unread_value is varchar(5), with a default of TRUE.
[@attachments =] 'attachments [;…n]'
Is the semicolon separated list of returned temporary paths of the mail attachments for the message. Temporary paths are separated by a semicolon (;). attachments is varchar(255), with no default.
[@skip_bytes =] bytes_to_skip OUTPUT
If a value other than 0 is passed for input, this parameter specifies the number of bytes to skip before reading the next 255 bytes (max) of the message into the body of message output parameter. When bytes_to_skip is used, body_of_message includes the next portion of the message and bytes_to_skip returns with the next starting point within the message (the previous bytes_to_skip plus the length of message). bytes_to_skip is int, with a default of 0.
[@msg_length =] length_in_bytes OUTPUT
Is the total length of the message, in bytes. When used with bytes_to_skip in a stored procedure, this parameter allows messages to be read in chunks of 255 bytes. length_in_bytes is int, with a default of 255 (bytes).
[@originator_address =] 'sender_address'
Is the resolved mail address of the originator of the mail message. sender_address is varchar(255), with no default.
Return Code Values

0 (success) or 1 (failure)

Result Sets

xp_readmail returns a result set with these columns (older messages appear first).

Column name | Description
Originator | Sender of e-mail message
Date Received | Date the e-mail message was received
Recipients | The people to whom the message was sent
CC List | The people on the CC’d line of the e-mail message
BCC List | The people on the BCC’d line of the e-mail message
Subject | Subject line of the e-mail message
Message | Message body (text)
Unread | Whether this message is unread
Attachments | Any attachments for the message
Message ID | Message ID
Type | Message type

Remarks

Any failure except an invalid parameter is logged to the Microsoft Windows NT® application log.

There are two ways to use xp_readmail:

  1. Return the contents of the Inbox as a result set to the client.
  2. Read a single message from the Inbox.

To return the contents of the Inbox as a result set to the client either set message_number to NULL or do not include message_number. In this situation, type can be used to read specific messages. You can specify peek and suppress_attach as input parameters to control the way the message is read.

To read a single message from the Inbox, supply a valid message_number returned by xp_findnextmsg as an input parameter to xp_readmail. You can specify peek and suppress_attach as input parameters to control the way the message is read. When using peek and suppress_attach with this method, all other parameters are optional output parameters containing specific information from the message to be read.

You can view an example of using xp_findnextmsg as an input parameter to xp_readmail by executing the following command:

sp_helptext 'sp_processmail'

When used to read a single message, xp_readmail can read message text of longer than 255 bytes in sections. Use length_in_bytes and length_in_bytes to read message text of longer than 255 bytes in sections. Using length_in_bytes as both an input and output parameter allows coding of a loop to process the entire message text. The following code shows an example of such a loop, assuming message_number is set to a valid message identifier returned by xp_findnextmsg.

USE master

WHILE (1 = 1)

BEGIN

EXEC @status = xp_readmail @msg_id = @msg_id,
    @message = @message OUTPUT,
    @skip_bytes = @skip_bytes OUTPUT,

    @msg_length = @msg_length OUTPUT

IF @status <> 0 BREAK

SELECT 'msg_id' = @msg_id, 'msg_part' = @message

IF @skip_bytes = @msg_length BREAK

END

Permissions

Execute permissions for xp_readmail default to the members of the sysadmin fixed server role but can be granted to other users.

Examples

This example returns the status when reading a message. In this example, the value of a message ID from xp_findnextmsg is placed in the local variable @message_id and passed to xp_readmail.

USE master

EXEC @status = xp_readmail @msg_id = @message_id,

    @originator = @originator OUTPUT,

    @cc_list = @cc_list OUTPUT,

    @subject = @msgsubject OUTPUT,

    @message = @query OUTPUT,

    @peek = 'TRUE',

    @suppress_attach = 'TRUE'

See Also
sp_processmail | xp_startmail
xp_deletemail | xp_stopmail
xp_findnextmsg | System Stored Procedures (SQL Mail Extended Procedures)
xp_sendmail |


xp_revokelogin

Revokes access from a Microsoft® Windows NT® group or user to Microsoft SQL Server™. xp_revokelogin is provided for backward compatibility. Use sp_revokelogin.

Syntax

xp_revokelogin {[@loginame =] 'login'}

Arguments
[@loginame =] 'login'
Is the name of the Windows NT user or group to be revoked access. The Windows NT user or group must be qualified with a Windows NT domain name. login is sysname, with no default.
Return Code Values

0 (success) or 1 (failure)

Remarks

xp_revokelogin is now a system stored procedure rather than an extended stored procedure and calls sp_revokelogin to revoke access to SQL Server for a Windows NT group or user .

See Also
sp_denylogin | xp_loginconfig
sp_grantlogin | xp_logininfo
sp_revokelogin | System Stored Procedures (General Extended Procedures)


xp_sendmail

Sends a message and a query result set attachment to the specified recipients.

Syntax

xp_sendmail {[@recipients =] 'recipients [;…n]'}
[,[@message =] 'message']
[,[@query =] 'query']
[,[@attachments =] attachments]
[,[@copy_recipients =] 'copy_recipients [;…n]'
[,[@blind_copy_recipients =] 'blind_copy_recipients [;…n]'
[,[@subject =] 'subject']
[,[@type =] 'type']
[,[@attach_results =] 'attach_value']
[,[@no_output =] 'output_value']
[,[@no_header =] 'header_value']
[,[@width =] width]
[,[@separator =] 'separator']
[,[@echo_error =] 'echo_value']
[,[@set_user =] 'user']
[,[@dbuse =] 'database']

Arguments
[@recipients =] 'recipients [;…n]'
Is the semicolon-separated list of the recipients of the mail.
n
Is a placeholder indicating that more than one recipient, copy_recipient, or blind_copy_recipient can be specified.
[@message =] 'message'
Is the message to be sent. message can be up to 8,000 bytes.
[@query =] 'query'
Is a valid Microsoft® SQL Server™ query, the result of which is sent in mail. xp_sendmail uses a bound connection for the query parameter. The query connection made by SQL Mail is not blocked by locks held by the client that issues the xp_sendmail request. This makes xp_sendmail easier to use from within triggers. The query statement, however, cannot refer to the logical inserted and deleted tables that are only available within a trigger. query can be up to 8,000 bytes.
[@attachments =] attachments
Is a file to attach to the mail.
[@copy_recipients =] 'copy_recipients [;…n]'
Is the semicolon-separated list identifying the recipients of a copy of the mail (cc:’ing).
[@blind_copy_recipients =] 'blind_copy_recipients [;…n]'
Is an optional semicolon-separated list identifying recipients of a blind copy of the mail (bcc:’ing).
[@subject =] 'subject'
Is an optional parameter specifying the subject of the mail. If subject is not specified, SQL Server Message is the default.
[@type =] 'type'
Is the input message type based on the MAPI mail definition:

IP[M | C].Vendorname.subclass

If type is NULL, message types beginning with IPM appear in the inbox of the mail client and are found or read by xp_findnextmsg. Message types beginning with IPC do not appear in the inbox of the mail client and must be found or read by setting the type parameter. The default is NULL.

For more information about using custom message types, see the Microsoft Windows NT Resource Kit or the Microsoft Mail Technical Reference, available separately.

[@attach_results =] 'attach_value'
Is an optional parameter specifying the result set of a query should be sent in mail as an attached file instead of being appended to the mail. If attachments is not NULL and attach_results is true, the first file name in attachments is used as the file name for the results. If attachments is NULL, a file name is generated with a .txt extension. The default is FALSE, which means that the result set is appended to the message.
[@no_output =] 'output_value'
Is an optional parameter that sends the mail but does not return any output to the client session that sent the mail. The default is FALSE, which means that the client session of SQL Server receives output.
[@no_header =] 'header_value'
Is an optional parameter that sends the query results in mail but does not send column header information with the query results. The default is FALSE, which means that column header information is sent with the query results.
[@width =] width
Is an optional parameter setting the line width of the output text for a query. This parameter is identical to the /w parameter in the isql utility. For queries producing long output rows, use width with attach_results to send the output without line breaks in the middle of output lines. The default width is 80 characters.
[@separator =] 'separator'
Is the column separator (field terminator) for each column of the result set. This allows the files to be accessible by spreadsheet applications for formatting, and so on. This parameter is identical to the /s parameter in isql. For example, use separator with attach_results to send files with comma-separated values.
[@echo_error =] 'echo_value'
When true, causes SQL Mail to capture any server messages or DB-Library errors encountered while running the query and append them to the mail message rather than writing them to the error log. Also, a count of rows returned/rows affected is appended to the mail message.

Note When echo_error is true, xp_sendmail returns a status of 0 (success) if the mail is successfully sent, even if DB-Library errors or messages are encountered or the query returns no results.

[@set_user =] 'user'
Is the security context in which the query should be run. The default is guest.
[@dbuse =] 'database'
Is the database context in which the query should be run. The default is NULL, which means the user is placed in the default database.
Return Code Values

0 (success) or 1 (failure)

Result Sets

xp_sendmail returns this message:

Mail sent.

Remarks

The SQLMail session must be started prior to executing xp_sendmail. Sessions can be started either automatically or with xp_startmail. One SQLMail session supports all users on the SQL Server, but only one user at a time can send a message. Other users sending mail messages automatically wait their turns until the first user’s message is sent.

If query is specified, xp_sendmail logs in to SQL Server as a client and executes the specified query. SQLMail makes a separate connection to SQL Server; it does not share the same connection as the original client connection issuing xp_sendmail.

Note query can be blocked by a lock held by the client connection issued xp_sendmail. For example, if you are updating a table within a transaction and you create a trigger for update that attempts to select the same updated row information as the query parameter, the SQLMail connection is blocked by the exclusive lock held on row by the initial client connection.

xp_sendmail runs in SQL Server’s security context, which is a local administrator account by default. A valid user of xp_sendmail can access files for attachment to a mail message in an administrator’s security context. If nonsystem administrator users must access xp_sendmail and you want to guard against unsecured access to attachment files, the system administrator can create a stored procedure that calls xp_sendmail and provides the needed functionality but does not expose the attachments parameter. This stored procedure must be defined in the master database. The system administrator then grants execute permission on the stored procedure to the necessary users without granting permission to the underlying xp_sendmail procedure.

xp_sendmail sends a message and a query result set or an attachment to specified recipients, and uses a bound connection for the query parameter. The query connection made by SQLMail is not blocked by locks held by the client that issues the xp_sendmail request. This makes xp_sendmail easier to use from within triggers. The query statement, however, cannot refer to the logical inserted and deleted tables that are only available within a trigger.

Note An access violation can result from an attempt to execute xp_sendmail when the post office and address book are on a file share that the MSSQLServer service cannot access due to inadequate permissions.

Permissions

Execute permissions for xp_sendmail default to the member of the sysadmin fixed server role but can be granted to other users.

Examples
A. Use xp_sendmail with no variables

This example sends a message to user Robert King (e-mail is robertk) that the master database is full.

EXEC xp_sendmail 'robertk', 'The master database is full.'

B. Use xp_sendmail with variables

This example sends the message to users Robert King and Laura Callahan (e-mail is laurac), with copies sent to Anne Dodsworth (e-mail is anned) and Michael Suyama (e-mail is michaels). It also specifies a subject line for the message.

EXEC xp_sendmail @recipients = 'robertk;laurac',

@message = 'The master database is full.',
    @copy_recipients = 'anned;michaels',
    @subject = 'Master Database Status'

C. Send results

This example sends the results of the sp_configure to Robert King.

EXEC xp_sendmail 'robertk', @query = 'sp_configure'

D. Send results as an attached file

This example sends the results of the query SELECT * FROM INFORMATION_SCHEMA.TABLES as a text file attachment to Robert King. It includes a subject line for the mail and a message that will appear before the attachment. The @width parameter is used to prevent line breaks in the output lines.

EXEC xp_sendmail @recipients = 'robertk',

    @query = 'SELECT * FROM INFORMATION_SCHEMA.TABLES',
    @subject = 'SQL Server Report',
    @message = 'The contents of INFORMATION_SCHEMA.TABLES:',
    @attach_results = 'TRUE', @width = 250

E. Send messages longer than 8000 characters

This example shows how to send a message longer than 8000 characters. Because message is limited to the length of a varchar (as are all stored procedure parameters), this example writes the long message into a global temporary table consisting of a single text column. The contents of this temporary table are then sent in mail using the @query parameter.

CREATE TABLE ##texttab (c1 text)
INSERT ##texttab values ('Put your long message here.')
DECLARE @cmd varchar(56)
SET @cmd = 'SELECT c1 FROM ##texttab'
EXEC master.dbo.xp_sendmail 'robertk',
    @query = @cmd, @no_header= 'TRUE'
DROP TABLE ##texttab

See Also
sp_processmail | xp_startmail
xp_deletemail | xp_stopmail
xp_findnextmsg | System Stored Procedures (SQL Mail Extended Procedures)
xp_readmail |


xp_sprintf

Formats and stores a series of characters and values in the string output parameter. Each format argument is replaced with the corresponding argument.

Syntax

xp_sprintf {string OUTPUT, format}
[, argument [,…n]]

Arguments
string
Is a varchar variable that receives the output.
OUTPUT
When specified, places the value of the variable in the output parameter.
format
Is a format character string with placeholders for argument values, similar to that supported by the C-language sprintf function. Currently, only the %s format argument is supported.
argument
Is a character string representing the value of the corresponding format argument.
n
Is a placeholder indicating that a maximum of 50 arguments can be specified.
Return Code Values

0 (success) or 1 (failure)

Result Sets

xp_sprintf returns this message:

The command(s) completed successfully.

Permissions

Execute permissions default to the public role.

Examples

This example uses parameter to create an INSERT statement.

DECLARE @ret_string varchar (255)

EXEC xp_sprintf @ret_string OUTPUT, 'INSERT INTO %s VALUES (%s, %s)', 'table1', '1', '2'

PRINT @ret_string

Here is the result set:

INSERT INTO table1 VALUES (1, 2)

See Also
xp_sscanf System Stored Procedures (General Extended Procedures)


xp_sqlinventory

Captures Microsoft® SQL Server™ configuration and inventory information asynchronously on the computer running SQL Server and stores it in the specified database and table.

Syntax

xp_sqlinventory {'database', 'table', {interval | STOP}}

Arguments
'database'
Is the database in which to store inventory information. The database specified must already exist and must have enough free space to hold the retrieved inventory data. database is varchar(30), with no default.
'table'
Is the name of the table in which to store the inventory information. The specified table is created if it does not already exist, and stores configuration information only for servers that are in the same Microsoft Windows NT® domain as the SQL Server running xp_sqlinventory. table is varchar(30), with no default.
interval
Is the time (in seconds) to wait between checks for inventory messages. interval is int, and can be a value between 1 (once per second) and 3600 (once per hour).
STOP
Specifies that all in-progress inventory actions are stopped.
Return Code Values

0 (success) or 1 (failure)

Result Sets

xp_sqlinventory returns this message (values may vary):

Server: Msg 2, Level 1, State 1

[Microsoft][ODBC SQL Server Driver][SQL Server]SQL Server Inventory Running. SQL Server Information Is Being Captured By '' To Database 'master' Table 'xp_sqlinv' Every 2 Seconds.

When stop is issued, xp_sqlinventory returns this message (values may vary):

Server: Msg 2, Level 1, State 1

[Microsoft][ODBC SQL Server Driver][SQL Server]SQL Server Inventory Stopped. SQL Server Information Captured By '' In Database 'master' Table 'xp_sqlinv' Interval 2 Seconds.

Remarks

Before executing xp_sqlinventory, start SQL Server.

xp_sqlinventory captures SQL Server configuration and inventory information for all SQL Servers on the domain and stores the information in the specified database and table. Any SQL Server running the LocalSystem account is not included.

Caution By default, SQL Server is installed as a service in the Windows NT LocalSystem account, and the SQL Server registration and configuration information cannot be sent over the network. For xp_sqlinventory to work, you must configure SQL Server to run in a valid domain user account through the Startup dialog box located in Services on Control Panel.

Inventory errors are written to the Windows NT application log.

Note xp_sqlinventory does not support named parameters.

This inventory information is captured for each inventoried SQL Server.

Column name | Description
ReceiveDate | Date and time the message was received by SQL Server.
ServerName | SQL Server computer name.
ProductName | Product name of SQL Server.
SQLRegisteredOwner | Registered owner name typed during SQL Server Setup.
DomainName | Windows NT domain name of SQL Server.
MajorVersion | Major version number for the SQL Server version. For example, the 6 in SQL Server version 6.0 is the SQLMajorVersion.
MinorVersion | Minor version number for the SQL Server version. For example, the 50 in SQL Server version 6.50 is the SQLMinorVersion.
BuildNumber | Internal build number for the SQL Server version.
ServerLogins | Total number of configured user logins obtained from the master.dbo.syslogins system table.
MaxConnections | Maximum number of people that can be simultaneously connected to SQL Server.
DBCount | Total number of databases on the server, including master, tempdb, and model databases.
TotalDeviceSize | Size in megabytes of all devices allocated for SQL Server data. This number does not include dump devices.
SortOrder | Sort order and code page chosen at SQL Server Setup. For more information about the selected code page, see master.dbo.syscharsets where id = SortOrder.
SecurityMode | SQL Server security mode: 0 = Mixed Mode 1 = Windows NT Authentication Mode
ProcedureCache | Percentage of memory allocated to SQL Server’s procedure cache. Values may range from 1 to 99.
SMPStatus | Indicates how aggressively SQL Server uses multiple microprocessors. The default value is 0.
ConfiguredMemory | Total amount of memory in megabytes allocated to SQL Server.
PriorityBoost | Indicates whether SQL Server has been configured to run at a higher Windows NT process priority level. For more information about priority boost, see sp_configure.
WorkingSet | Directs Windows NT to reserve physical memory space for SQL Server equal to the sum of the memory setting and the size of tempdb. Default is 0 (no working set) and 1 (working set).
Publisher | Number of publications configured for SQL Server.
Subscriber | Number of publications subscribed to for SQL Server.
Distribution | Indicates whether SQL Server is configured as a Distributor: 0 = Not a Distributor 1 = A Distributor
NamedPipe | Indicates whether SQL Server can accept client connections by using the named pipe Net-Library: 0 = No 1 = Yes
MultiProtocol | Indicates whether SQL Server can accept client connections by using the Multiprotocol Net-Library: 0 = No 1 = Yes
SPX | Indicates whether SQL Server can accept client connections by using the Novell IPX/SPX Net-Library: 0 = No 1 = Yes
WinSocket | Indicates whether SQL Server can accept client connections by using a WinSocket application programming interface Net-Library: 0 = No 1 = Yes
Appletalk | Indicates whether SQL Server can accept client connections by using an Appletalk Net-Library: 0 = No 1 = Yes
VINES | Indicates whether SQL Server can accept client connections by using a Banyan® VINES® Net-Library: 0 = No 1 = Yes
CPUBrand | Brand of the microprocessor for SQL Server. Possible values can be Intel, or Alpha.
CPUModel | Microprocessor model, such as Pentium or Alpha for SQL Server.
CPUStepLevel | Processor stepping version.
CPUCount | The number of microprocessors for the SQL Server.
ServerTotalMemory | Total amount of physical memory in megabytes on SQL Server.
ServerAvailable Memory | Available amount of physical memory in megabytes on SQL Server.
OperatingSystem | Operating system for SQL Server; for example, Microsoft Windows NT.
OperatingSystem Build | Internal operating-system build version number for SQL Server; for example, 1057 for the 1057 build of Windows NT 3.51 or later.
TotalPhysicalDisk | Total amount of physical disk space in megabytes on nonremovable storage media.
AvailablePhysical Disk | Amount of free disk space available in megabytes on SQL Server.

Examples

This example checks every two seconds for SQL Server inventory messages. The information is loaded into the xp_sqlinv table in the master database.

USE pubs

GO

DECLARE @db varchar(30), @table varchar(30), @interval int

SET @db = 'master'

SET @table = 'xp_sqlinv'

SET @interval = 2

EXEC master..xp_sqlinventory @db, @table, @interval

-- Time passes...

EXEC master..xp_sqlinventory stop

See Also
System Stored Procedures (General Extended Procedures)


xp_sqlmaint

Calls the sqlmaint utility with a string containing sqlmaint switches. The sqlmaint utility performs a set of maintenance operations on one or more databases.

Syntax

xp_sqlmaint 'switch_string'

Arguments
'switch_string'
Is a string containing the sqlmaint utility switches. The switches and their values must be separated by a space.

The -? switch is not valid for xp_sqlmaint.

Return Code Values

None. Returns an error if the sqlmaint utility fails.

Remarks

If this procedure is called by a user logged on with SQL Server Authentication, the -U “login_id” and -P “password” switches are prepended to switch_string before execution. If the user is logged on with Windows NT Authentication, switch_string is passed without change to sqlmaint.

Permissions

Execute permissions are restricted to members of the sysadmin fixed server role.

Examples

In this example, xp_sqlmaint calls sqlmaint to perform integrity checks, create a report file, and update msdb.dbo.sysdbmaintplan_history.

EXEC xp_sqlmaint '-PlanID 02A52657-D546-11D1-9D8A-00A0C9054212
    -Rpt "C:\MSSQL7\LOG\DBMaintPlan2.txt" -WriteHistory  -CkDB -CkAl'

Here is the result:

The command(s) executed successfully.

See Also
System Stored Procedures


xp_sqltrace

Allows database administrators and application developers to monitor and record database activity.

Note xp_sqltrace has been replaced by xp_trace_addnewqueue as well as several other supporting extended procedures in the current version of Microsoft® SQL Server™. xp_sqltrace is documented here for backward compatibility only and may not be supported in future versions.

Syntax

xp_sqltrace [[@Function =] function] [, [@EventFilter =] eventfilter]
[,[@LangFilter =] 'langfilter'] [,[@RPCFilter =] 'rpcfilter']
[,[@UserFilter =] 'userfilter'] [,[@AppFilter =] appfilter]
[,[@HostFilter =] hostfilter] [,[@BufSize =] bufsize]
[,[@TimeOut =] timeout] [,[@TraceId =] traceid]
[,[@FullText =] fulltext] [,[@FullFilePath =] 'outputfilename']
[,[@IntegerEvents =] integerevents]

Arguments
[@Function =] function
Is a string that describes what action xp_sqltrace performs. These are the possible values.

Value | Description
audit | Logs all database activity requested by the specified filters to a file specified by outputfilename. Returns program control immediately. If traceid, bufsize, or timeout are specified, they are ignored. If audit is used without any parameters, a result set is generated displaying the current audit settings for xp_sqltrace. Only one instance of audit can be executed at any time. A permanent connection is not necessary to execute an audit. For example, the system administrator can be connected, start the audit, and then disconnect. You can use audit in automatically started procedures.
control | Changes the settings for a running instance from a separate connection. You must run xp_sqltrace without parameters to obtain a trace ID before starting a trace session. traceid is required.
remove | Unloads all event handlers. Stops all data from being sent to trace sessions until trace handlers are loaded again. Using remove does not stop currently executing trace sessions. Starting or stopping a trace session also loads or unloads relevant handlers. You can use remove to temporarily pause all trace sessions. No other parameters are required.
stop | Stops either a single trace session or all trace sessions for the current server. It is recommended that you execute xp_sqltrace stop, @traceid = <traceid> to stop a specific trace session. Using xp_sqltrace stop is useful if the server is under heavy load and the system administrator must stop all trace activities.
trace | Captures all database activity requested by the specified filters and generates a log file or a result set. traceid has no effect.

[@EventFilter =] eventfilter
Is the server activity to monitor. eventfilter is int, and can be any of these values.

Value | Description
0 | PAUSE. Temporarily pauses the trace session. Must be the only eventfilter specified.
1 | CONNECT. Trace connect events to SQL Server.
2 | DISCONNECT. Trace disconnect events from SQL Server.
4 | POST_LANGUAGE. Trace completed language events on SQL Server (for example, INSERT, SELECT).
8 | POST_RPC. Trace completed remote procedure call (RPC) events on SQL Server.
16 | ATTENTION. Trace attention events on SQL Server.
32 | PRE_LANGUAGE. Trace language batches immediately prior to execution. Not currently used by Sqltrace.exe.
64 | PRE_RPC. Trace RPC events immediately before execution. Not currently used by Sqltrace.exe.

To specify more than one event, add the eventfilter values. For example, @EventFilter = 31 means that xp_sqltrace should monitor CONNECT, DISCONNECT, POST_LANGUAGE, POST_RPC, and ATTENTION events.

[@LangFilter =] 'langfilter'
Is a string specifying a batch pattern of language statements to be monitored. Use the % wildcard character to indicate any sequence of characters. Delimit multiple filter strings with a semicolon (;) for the OR condition (%INSERT%;%SELECT%).
[@RPCFilter =] 'rpcfilter'
Is a string pattern of remote stored procedure calls for which to monitor events. Delimit multiple filter strings with a semicolon (;) for the OR condition. Use the % wildcard character to indicate any sequence of characters. Delimit multiple filter strings with a semicolon (;) for the OR condition (%sp_cursors%;sp_run%).
[@UserFilter =] 'userfilter'
Is the login name(s) of users for whom to monitor events as a string. Delimit multiple filter strings with a semicolon (;) for the OR condition. Use the % wildcard character to indicate any sequence of characters. For example, specify Chan% as the login name to find login names Chan and Channing.
[@AppFilter =] appfilter
Is the application name(s) for which to monitor events as a string. Delimit multiple filter strings with a semicolon (;) for the OR condition. Use the % wildcard character to indicate any sequence of characters. For example, specify the application name Acc% to find the application Access.
[@HostFilter =] hostfilter
Is the host(s) for which to monitor events as a string. Delimit multiple filter strings with a semicolon (;) for the OR condition. Use the % wildcard character to indicate any sequence of characters. For example, specify the hostname air% to find the host airedale.
[@BufSize =] bufsize
Is the number of rows of data the server buffers when the client is busy. bufsize is int, with a default of 1,000. bufsize can be a value from 1 to 20000.
[@TimeOut =] timeout
Is the amount of time in seconds the server waits, when bufsize is full, before terminating the trace session. timeout is int, with a default of 5 seconds. timeout can be 1 to 10 seconds.
[@TraceId =] traceid
Each traceid value is static for a connection as long as you retain your current connection. traceid is int.
[@FullText =] fulltext
Is whether the language or RPC strings should be returned as varchar(255) (0) or as text (1). fulltext is int, with a default of 0.
[@FullFilePath =] 'outputfilename'
Is the file to send the output to as a string (for example, C:\Selects.log). This parameter uses the standard SQL Server Profiler log format for output. For more information about the SQL Server Profiler log format, see SQL Server Profiler Help.
[@IntegerEvents =] integerevents
Is whether the event column should be text (0) or integer (1). integerevents is int, with a default of 0.
Return Code Values

0 (success) or > 1 (failure)

Result Sets

xp_sqltrace returns this result set (values may vary).

Column name | Description
TraceId | Trace identification number used for the trace session
Version | Version and build number that initiates the trace

Remarks

When using xp_sqltrace, an @Function = trace does not return program control until explicitly stopped. No other commands should be issued before the call to xp_sqltrace in an isql utility or SQL Server Query Analyzer batch. After you choose the stop button in SQL Server Query Analyzer, another output row must be received for the trace to stop. This is a limitation of the SQL Server Query Analyzer interface.

Data can be captured to a table by using the INSERT statement’s EXECute clause. Using the INSERT statement this way places xp_sqltrace within a transaction. If xp_sqltrace is used in a transaction, the transaction will not complete until the application stops xp_sqltrace. If the trace is not terminated before the server is stopped or if the database fills completely during a transaction, all changes are rolled back.

These are the events specific to trace session output.

Event | Description
PAUSE (0) | Indicates the trace session was paused temporarily.
START (254) | Indicates a start trace event.
ACTIVE (255) | Indicates an active connection event. A row appears in the output for every user that meets the criteria specified in the xp_sqltrace command line. For example, if the system administrator already has three connections, three ACTIVE rows appear in the output. The trace session reports an ACTIVE row for preexisting connections.

Permissions

Execute permissions for xp_sqltrace default to the members of the sysadmin fixed server role but can be granted to other users.

Examples
A. Trace SELECT statements for user

This example begins a trace session displaying the event, the username, the application, the data or language statement, and other columns. All SELECT statements executed by the user sa are included in the trace. Events included in the trace are ATTENTION, CONNECT, DISCONNECT, POST-LANGUAGE, and POST-RPC events.

EXEC xp_sqltrace trace, @eventfilter = 31, @userfilter = 'sa',
    @langfilter = '%select%'

These are the columns generated in the result set.

Column name | Data type | Description
Event | varchar(12) or int | Event (for example start, pause, active, connect, disconnect, SQL, attention) as varchar(12) unless @IntegerEvents = 1.
UserName | char(30) NULL | Username of the user that generated the event.
ID | int | Unique, increasing identifier for connections.
SPID | int | Microsoft SQL Server process identification number.
StartTime | datetime NULL | Time the language statement or remote stored procedure call started executing. For connect and disconnect events, specifies the time the user logged in.
EndTime | datetime NULL | Time the language statement or remote stored procedure call stopped executing. For disconnect events, specifies the disconnect time.
Application | char(30) NULL | Application that generated the event.
Data | varchar(255) NULL or text NULL | Language statement or remote stored procedure call as varchar(255) unless @FullText = 1.
Duration | int NULL | Amount of time in milliseconds the language statement or remote stored procedure call took to execute. For disconnect events, specifies the elapsed time in seconds since the user logged in.
CPU | int NULL | Amount of CPU time used in milliseconds.
Reads | int NULL | Number of disk reads.
Writes | int NULL | Number of synchronous disk writes.
NT_Domain | char(30) NULL | Microsoft Windows NT® domain name of the user that generated the event.
NT_User | char(30) NULL | Windows NT username of the user who generated the event.
HostName | char(30) NULL | Name of the host that generated the event.
HostProcess | int | Host process ID number for the host that generated the event.

B. Audit SELECT statements to a text file

This example audits batches that contain SELECT statements executed by the user sa and places the output in a file called C:\SELECTS.LOG.

EXEC xp_sqltrace audit, @eventfilter = 31, @userfilter = 'sa',
    @langfilter = '%select%', @FullFilePath = 'C:\SELECTS.LOG'

C. Obtain and use a specific trace identification number

This example starts a trace session for the first connection, and it allows the second connection to control the same trace session by using the trace identification number obtained and passed by the first connection.

Connection one Connection two
-- Obtain a traceid.
EXEC xp_sqltrace
-- Start the trace.
EXEC xp_sqltrace trace,
@eventfilter = 31
-- Pause the trace session.
EXEC xp_sqltrace control,
@TraceId = <TraceId>
-- Begin trace session.
EXEC xp_sqltrace control
@TraceId = <TraceId>,
@EventFilter = 4,
@LangFilter = '%select%'
-- Stop the trace session.
EXEC xp_sqltrace stop,
@traceid = <traceid>

D. Stop all current trace sessions

The first two xp_sqltrace command examples stop all trace sessions executing on the current server, and the third example stops only the specified trace session.

-- Stops all trace sessions.

EXEC xp_sqltrace stop, @traceid = 0

-- OR

EXEC xp_sqltrace stop

-- Recommended way to stop a single trace session.

EXEC xp_sqltrace stop @TraceId = <TraceId>

E. Configure SQL Server to automatically audit all sessions at disconnect

This example creates a stored procedure to automatically start an audit session that audits disconnections.

PRINT 'Creating auditing stored procedure'

-- Create stored procedure to enable xp_sqltrace run at startup.

GO

USE master

GO

IF EXISTS (SELECT * FROM sysobjects WHERE type = 'P' AND name = 'sp_sqlaudit')

    DROP PROCEDURE sp_sqlaudit

GO

CREATE PROCEDURE sp_sqlaudit AS

BEGIN

-- @FullFilePath can be any file that SQL Server has write
-- permissions.

EXEC master.dbo.xp_sqltrace audit, 2, @FullFilePath =

    'C:\MSSQL7\LOG\AUDIT.LOG'

END

GO

EXEC sp_procoption 'sp_sqlaudit', 'startup', true

GO

F. Capture server activity to table

This example uses EXECUTE (or EXEC) to capture all of the server activity to a table named sqltrace in the pubs database. Note the transaction is not committed until xp_sqltrace STOP is executed from another connection.

USE pubs

GO

IF EXISTS (SELECT * FROM sysobjects WHERE name = 'SQLTrace' AND type =

    'U')

BEGIN

    DROP TABLE SQLTrace

END

GO

CREATE TABLE SQLTrace

(

    Event         CHAR(12) NOT NULL,

    UserName     CHAR(30) NOT NULL,

    ID int         NOT NULL,

    SPID int     NOT NULL,

    StartTime     DATETIME NULL,

    EndTime         DATETIME NULL,

    Application     CHAR(30) NOT NULL,

    Data         VARCHAR(255) NULL,

    Duration     INT NULL,

    CPU             INT NULL,

    Reads         INT NULL,

    Writes         INT NULL,

    NT_Domain     VARCHAR(30) NULL,

    NT_User       VARCHAR(30) NULL,

    HostName      VARCHAR(30) NULL,

    HostProcess     INT NULL

)

GO

EXEC master..xp_sqltrace

GO

INSERT INTO SQLTrace EXEC master..xp_sqltrace TRACE, @eventfilter = 31

From another connection, execute:

EXEC master..xp_sqltrace STOP, 1358560

/* where 1358560 is the trace session returned from xp_sqltrace */

G. Load a trace activity log with the bcp utility

This example loads an activity log into SQL Server using the bcp utility. First, create a log and capture the server activity to an activity log file. Next, create a table with this structure:

IF EXISTS (SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='SQLTrace')

    DROP TABLE SQLTrace

GO

CREATE TABLE SQLTrace

(

    Event         CHAR(12) NOT NULL,

    UserName     CHAR(30) NOT NULL,

    ID             INT NOT NULL,

    SPID         INT NOT NULL,

    StartTime     datetime NULL,

    EndTime         datetime NULL,

    Application     CHAR(30) NOT NULL,

    Data         VARCHAR(255) NULL,

    Duration     INT NULL,

    CPU             INT NULL,

    Reads         INT NULL,

    Writes         INT NULL,

    NT_Domain     VARCHAR(30) NULL,

    NT_User       VARCHAR(30) NULL,

    HostName      VARCHAR(30) NULL,

    HostProcess     INT NULL

)

GO

Finally, load the data using bcp.

bcp pubs..SQLTrace in c:\activity.log -Usa -Psecret -S -c

See Also
System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_sscanf

Reads data from the string into the argument locations given by each format argument.

Syntax

xp_sscanf {string OUTPUT, format}
[, argument [,…n]]

Arguments
string
Is the character string to read the argument values from.
OUTPUT
When specified, places the value of argument in the output parameter.
format
Is a formatted character string similar to what is supported by the C-language sscanf function. Currently only the %s format argument is supported.
argument
Is a varchar variable set to the value of the corresponding format argument.
n
Is a placeholder indicating that a maximum of 50 arguments can be specified.
Return Code Values

0 (success) or 1 (failure)

Result Sets

xp_sscanf returns this message:

The command(s) completed successfully.

Permissions

Execute permissions default to the public role.

Examples

This example uses xp_sscanf to extract two values from a source string based on their positions in the format of the source string.

DECLARE @filename varchar (20), @message varchar (20)

EXEC xp_sscanf 'sync -b -fauthors10.tmp -rrandom', 'sync -b -f%s -r%s',

    @filename OUTPUT, @message OUTPUT

SELECT @filename, @message

Here is the result set:

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

authors10.tmp        random

See Also
xp_sprintf System Stored Procedures (General Extended Procedures)


xp_startmail

Starts a SQL Mail client session.

Syntax

xp_startmail [[@user =] 'user'] [,[@password =] 'password']

Arguments
[@user =] 'user'
Is an optional parameter specifying a mail username. user is sysname, with no default.
[@password =] 'password'
Is the mail password for the named user. password is sysname, with no default. A value of NULL is allowed when the mail client is started (on the same computer) before running xp_startmail.
Return Code Values

0 (success) or 1 (failure)

Result Sets

xp_startmail returns this message:

SQL mail session started.

Remarks

If user and password are provided, Microsoft® SQL Server™ attempts to log on to Windows NT Mail (or other MAPI provider) using that username and password. If user and password are provided but are incorrect, an error message is returned. If user and password are not provided, SQL Server uses the username and password specified in the SQL Server Properties dialog box.

Note If you use xp_startmail to start your mail sessions, you can optionally supply your login name and password so that you do not have to type it at the command prompt. SQL Mail will “piggyback” an existing client session of Windows NT Mail if one is running.

If there is an existing mail session, xp_startmail does not start a new one. If mail is being used on the same computer on which SQL Server is also running, the mail client must be started either before xp_startmail is executed, or before SQL Server is started if SQL Mail is configured to automatically start when SQL Server starts.

Permissions

Execute permissions for xp_startmail default to the members of the sysadmin fixed server role but can be granted to other users.

Examples
A. Use no variables with xp_startmail

This example starts mail using the username and password specified in SQL Server Setup.

USE master

EXEC xp_startmail

B. Use variables with xp_startmail

This example starts mail using the username janetl and the password abc12345.

USE master

EXEC xp_startmail 'janetl', 'abc12345'

See Also
sp_processmail | xp_sendmail
xp_deletemail | xp_stopmail
xp_findnextmsg | System Stored Procedures (SQL Mail Extended Procedures)
xp_readmail |


xp_stopmail

Stops a Microsoft® SQL Server™ mail client session.

Syntax

xp_stopmail

Return Code Values

0 (success) or 1 (failure)

Result Sets

xp_stopmail returns this message:

Stopped SQL mail session.

Remarks

If there is no existing SQL Server mail session to stop, a message is returned.

Permissions

Execute permissions for xp_stopmail default to the members of the sysadmin fixed server role but can be granted to other users.

See Also
sp_processmail | xp_sendmail
xp_deletemail | xp_startmail
xp_findnextmsg | System Stored Procedures (SQL Mail Extended Procedures)
xp_readmail |


xp_trace_addnewqueue

Adds a new trace queue and sets trace queue configuration values, including the size of the trace queue (the number of items to be held in the trace queue at one time).

Important When using the shared memory network library, Microsoft® SQL Server™ does not support impersonation unless connected by using Windows NT Authentication. To execute a SQL Server Profiler Extended Procedure against a local server through SQL Server Query Analyzer, use Windows NT Authentication.

Syntax

xp_trace_addnewqueue {max_items, timeout, thread_boost, thread_reduce,
required_columns, queue_handle OUTPUT}

Arguments
max_items
Is an integer representing the maximum number of items buffered or stored in the trace queue. The recommended value is 1000, the minimum is 1, and the maximum is 20,000.
timeout
Is an integer representing the time-out value in seconds for the trace queue. The default value is 5, the minimum is 1, and the maximum is 10. At time-out, the trace queue, for a brief period of time, stops accepting new events.
thread_boost
Is an integer representing the percentage of items in the trace queue causing the trace queue consumer to receive a boost in priority and increases the priority setting for the specified application thread. The default value is 95%, the minimum is 1%, and the maximum is 100%. thread_reduce cannot be greater than thread_boost.
thread_reduce
Is an integer representing the percentage of items in the trace queue causing the trace queue consumer to receive a reduction in priority and decreases the priority setting for the specified application thread. The default value is 90%, the minimum is 0%, and the maximum is 99%. thread_reduce cannot be greater than thread_boost.
required_columns
Is an integer mask representing the required columns to be shown in the trace output. The default is 0, which means all columns listed below are provided in the trace output. Choose from these values and use the bitwise OR (|) operator to combine them.

Value | Description
1 | Text data
2 | Binary data
4 | Database ID
8 | Transaction ID
16 | Connection ID
32 | Microsoft Windows NT® username
64 | Windows NT domain name
128 | Host name
256 | Host process ID
512 | Application name
1024 | SQL username
2048 | SQL process ID (SPID)
4096 | Duration
8192 | Start time
16384 | End time
32768 | Reads
65536 | Writes
131072 | CPU usage
524288 | Severity
1048576 | Event Subclass
2097152 | Object ID
8388608 | Index ID
16777216 | Integer data
33554432 | Server name
67108864 | Event Class

queue_handle
Is an integer representing the handle for the trace queue returned from this procedure. queue_handle must be declared before running the procedure.
OUTPUT
Specifies that the value returned is placed in the queue_handle parameter.
Return Code Values

0 (success) or >1 (failure)

Result Sets

xp_trace_addnewqueue returns this message:

The command(s) completed successfully.

Remarks

After a trace queue is created, there may come a time when the trace queue must be either stopped, or destroyed.

There are some special considerations when using the Replay feature of SQL Server Profiler which pertain to passwords, permissions, and authentication.

Permissions

Execute permissions for xp_trace_addnewqueue default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example creates a trace queue that writes events to a file and autostarts whenever the server is restarted.

--Declare the variables.

DECLARE @queue_handle int  --queue handle to refer

                           --to this trace by

DECLARE @column_value int  --data column bitmask

--Set the column mask for the data columns to capture

SET @column_value = 1|16|3|8192|128|512

--Create a queue.

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

--Specify the event classes to trace.

--To look up the names, execute xp_trace_geteventnames.

EXEC xp_trace_seteventclassrequired @queue_handle,
    10, 1 --RPC:Completed

EXEC xp_trace_seteventclassrequired @queue_handle,
    12, 1 --SQL:BatchCompleted

EXEC xp_trace_seteventclassrequired @queue_handle,
    14, 1 --Connect

EXEC xp_trace_seteventclassrequired @queue_handle,
    16, 1 --Disconnect

EXEC xp_trace_seteventclassrequired @queue_handle,
    17, 1 --ExistingConnection

--Set any filters. (Don't trace the Profiler).

EXEC xp_trace_setappfilter @queue_handle,
    NULL,
    'SQL Server Profiler%'

--Configure the queue to write to a file.

EXEC xp_trace_setqueuedestination @queue_handle,

    2,

    1,

    NULL,

    'c:\temp\demo.trc'

--Start the consumer that actually writes to a file.

EXEC xp_trace_startconsumer @queue_handle

--Display the queue handle. It will be needed

--later to stop the queue.

SELECT @queue_handle

--Save the queue definition as DemoQueue.

EXEC xp_trace_savequeuedefinition @queue_handle,

    'DemoQueue',

    1

--Mark it for autostart

EXEC xp_trace_setqueueautostart 'DemoQueue', 1

See Also
| (Bitwise OR) | xp_trace_pausequeue
xp_trace_destroyqueue | xp_trace_restartqueue
xp_trace_enumqueuehandles | xp_trace_savequeuedefinition
xp_trace_loadqueuedefinition | System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_deletequeuedefinition

Deletes the named trace queue from the registry.

Syntax

xp_trace_deletequeuedefinition {'queue_name', is_shared}

Arguments
'queue_name'
Is a string specifying the trace queue name. This name can be determined by executing xp_trace_enumqueuedefname.
is_shared
Is a Boolean value specifying whether the trace queue definition is shared (1) or private (0).
Return Code Values

0 (success) or >1 (failure)

Result Sets

xp_trace_deletequeuedefinition returns this message:

The command(s) completed successfully.

Permissions

Execute permissions for xp_trace_deletequeuedefinition default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example deletes the trace queues named Seattle SELECTs and UPDATEs, which is stored as a private trace queue definition. In order to perform the deletion of the trace queue, it is necessary for the trace to be a saved trace (executed by xp_trace_savequeuedefinition).

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_savequeuedefinition @queue_handle,

    'Seattle SELECTs and UPDATEs',

    0

EXEC xp_trace_deletequeuedefinition 'Seattle SELECTs and UPDATEs',

    0

See Also
xp_trace_destroyqueue | System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_savequeuedefinition |


xp_trace_destroyqueue

Destroys the given trace queue, but does not delete the queue definition. If the trace queue has a consumer, Microsoft® SQL Server™ waits to destroy the trace queue until the trace queue consumer has consumed all events in the trace queue.

Syntax

xp_trace_destroyqueue {queue_handle}

Arguments
queue_handle
Is an integer representing the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
Return Code Values

0 (success) or >1 (failure)

Result Sets

xp_trace_destroyqueue returns this message:

The command(s) completed successfully.

Permissions

Execute permissions for xp_trace_destroyqueue default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example destroys the trace queue named Seattle SELECTs.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_destroyqueue @queue_handle

See Also
xp_trace_addnewqueue | xp_trace_restartqueue
xp_trace_deletequeuedefinition | xp_trace_savequeuedefinition
xp_trace_pausequeue | System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_enumqueuedefname

Alphabetically lists all currently defined trace queue names.

Syntax

xp_trace_enumqueuedefname {is_shared} [, 'queue_name']

Arguments
is_shared
Is a Boolean value specifying whether to enumerate the shared (1) or private (0) trace queue definition(s).
'queue_name'
Is the trace queue name from which to begin the alphabetically ascending trace queue name list. If queue_name is specified, queue_name and those queue names that follow it in alphabetic order are listed. If queue_name is not specified, all currently defined trace queue names are returned.
Return Code Values

0 (success) or >1 (failure)

Result Sets
Column name | Description
QueueDefinitionName | Name of a currently defined trace queue

Permissions

Execute permissions for xp_trace_enumqueuedefname default to members of the sysadmin fixed server role but can be granted to other users.

Examples
A. Return all currently defined, shared trace queue names

This example retrieves all currently defined and shared queue names.

USE master

EXEC xp_trace_enumqueuedefname 1

Here is the result set (output may vary):

QueueDefinitionName

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

DemoQueue

London Attention

London Events

Seattle SQL Batch Starting and Completing

(4 row(s) affected)

B. Return all trace queue names after a specified name

This example retrieves all currently defined and shared definition trace queue names, in alphabetic order, that follow the London Events trace queue name.

USE master

EXEC xp_trace_enumqueuedefname 1,

    'London Events'

Here is the result set (output may vary):

QueueDefinitionName

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

London Events

Seattle SQL Batch Starting and Completing

(2 row(s) affected)

See Also
xp_trace_addnewqueue | System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_loadqueuedefinition |


xp_trace_enumqueuehandles

Numerically lists all currently active trace queue handles.

Syntax

xp_trace_enumqueuehandles [queue_handle]

Arguments
queue_handle
Is an integer, a trace queue handle, from which to begin the numerically ascending trace queue list. If queue_handle is specified, queue_handle and the queue handles that follow it in numeric order are listed. If queue_handle is not specified, all currently defined trace queue handles are returned. queue_handle is used to reference the trace queue and is returned in an output parameter by xp_trace_addnewqueue.
Return Code Values

0 (success) or >1 (failure)

Result Sets

xp_trace_enumqueuehandles returns this result set if no parameters are passed.

Column name | Description
QueueHandle | Queue number of a currently active trace queue

Permissions

Execute permissions for xp_trace_enumqueuehandles default to members of the sysadmin fixed server role but can be granted to other users.

Examples
A. List all currently defined trace queue handles

This example lists all currently defined trace queue handles.

Note This example assumes any trace queue handles returned were previously created by executing xp_trace_addnewqueue.

USE master

EXEC xp_trace_enumqueuehandles

Here is the result set (output may vary):

QueueHandle

-----------

2

3

4

(3 row(s) affected)

B. List all trace queue handles after a specific trace queue handle

This example lists all trace queues following the trace queue specified with @queue_handle variable.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_savequeuedefinition @queue_handle,

    'London INSERTs',

    0

EXEC xp_trace_enumqueuehandles @queue_handle

Here is the result set:

QueueHandle

-----------

12

(1 row(s) affected)

See Also
xp_trace_addnewqueue | xp_trace_loadqueuedefinition
xp_trace_enumqueuedefname | System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_eventclassrequired

Returns the class name for the event classes being captured for the given queue handle when event class information is provided.

Syntax

xp_trace_eventclassrequired {queue_handle} [, event_class]

Arguments
queue_handle
Is an integer that represents the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
event_class
Is an integer that represents the class of events to trace. If event_class is not specified, all event classes are returned, indicating whether they are being traced for queue_handle. Execute xp_trace_geteventnames to see this list. event_class can be one of these values.

Value | Event class | Description
0 | TraceStart | Given trace has been put into started state.
1 | TracePause | Given trace has been put into a paused state.
2 | TraceRestart | Given trace has been put into a restarted state.
3 | TraceAutoPause | Given trace has been put into an automatic pause state.
4 | TraceAutoRestart | Given trace has been put into an automatic restart state.
5 | TraceStop | Given trace has been put into a stopped state.
6 | EventRequired | Given trace has been put into an events to trace changed state.
7 | FilterChanged | Given trace has been put into a filter changed state.
8 | 8 | Reserved.
9 | 9 | Reserved.
10 | RPC:Completed | Occurs when a remote procedure call (RPC) has been completed.
11 | RPC:Starting | Occurs when an RPC has been started.
12 | SQL:BatchCompleted | Occurs when a Transact-SQL batch has been completed.
13 | SQL:BatchStarting | Occurs when a Transact-SQL batch is starting.
14 | Connect | Collects all connection events, such as when a client requests a connection to a server running Microsoft® SQL Server™.
15 | Disconnect | Collects all disconnect events, such as when a client issues a disconnect command.
16 | Attention | Collects all attention events, such as client-interrupt requests or broken client connections.
17 | ExistingConnection | Detects all users that were logged on before the trace started.
18 | ServiceControl | Tracks all server control events, such as server paused or restart events.
19 | DTCTransaction | Tracks MS DTC coordinated transactions between two or more databases.
20 | LoginFailed | Indicates that a login attempt to SQL Server from a client failed.
21 | EventLog | Indicates events logged in the Microsoft Windows NT® application log.
22 | ErrorLog | Indicates error events logged in the SQL Server error log.
23 | Lock:Released | Indicates that a lock on a resource, such as a page, has been released.
24 | Lock:Acquired | Indicates acquisition of a lock on a resource, such as a data page.
25 | Lock:Deadlock | Indicates that two concurrent transactions have deadlocked each other by trying to obtain incompatible locks on resources the other transaction owns.
26 | Lock:Cancel | Indicates that the acquisition of a lock on a resource has been canceled (for example, due to a deadlock).
27 | Lock:Timeout | Indicates that a request for a lock on a resource, such as a page, has timed out due to another transaction holding a blocking lock on the required resource. Time-out is determined by the @@LOCK_TIMEOUT function, and can be set with the SET LOCK_TIMEOUT statement.
28 | Insert | Occurs before an INSERT statement is executed.
29 | Update | Occurs before an UPDATE statement is executed.
30 | Delete | Occurs before DELETE statement is executed.
31 | Select | Occurs before SELECT statement is executed.
32 | ConnectionBeingKilled | Indicates that the connection is being killed.
33 | Exception | Indicates that an exception has occurred in SQL Server.
34 | SP:CacheMiss | Indicates when a stored procedure is not found in the procedure cache.
35 | SP:CacheInsert | Indicates when an item is inserted into the procedure cache.
36 | SP:CacheRemove | Indicates when an item is removed from the procedure cache.
37 | SP:Recompile | Indicates that a stored procedure is recompiling.
38 | SP:CacheHit | Indicates when a stored procedure is found in the procedure cache.
39 | SP:ExecContextHit | Indicates when the execution version of a stored procedure has been found in the procedure cache.
40 | SQL:StmtStarting | Occurs when the Transact-SQL statement is starting.
41 | SQL:StmtCompleted | Occurs when the Transact-SQL statement has completed.
42 | SP:Starting | Indicates when the stored procedure has started.
43 | SP:Completed | Indicates when the stored procedure has completed.
44 | SP:StmtStarting | Indicates when a statement within a stored procedure is starting.
45 | SP:StmtCompleted | Indicates when a statement within a stored procedure has completed.
46 | Object:Created | Indicates when an object has been created, such as for CREATE INDEX, CREATE TABLE, and CREATE DATABASE statements.
47 | Object:Deleted | Indicates when an object has been deleted, such as in DROP INDEX and DROP TABLE statements.
48 | Object:Opened | Indicates when an object has been accessed, such as for SELECT, INSERT, or DELETE statements.
49 | Object:Closed | Indicates when an object has been closed, such as the end of a SELECT, INSERT, or DELETE statement.
50 | SQLTransaction | Tracks Transact-SQL BEGIN, COMMIT, SAVE, and ROLLBACK TRANSACTION statements.
51 | Scan:Started | Indicates when a table or index scan has started.
52 | Scan:Stopped | Indicates when a table or index scan has stopped.
53 | CursorOpen | Indicates when a cursor has been opened on a Microsoft SQL Server table by ODBC or DB-Library.
54 | TransactionLog | Tracks when transactions are written to the transaction log.
55 | HashWarning | Indicates that a hashing operation (for example, hash join, hash aggregate, hash union, and hash distinct) that is not processing on a buffer partition has reverted to an alternate plan. This can occur because of recursion depth, data skew, trace flags, or bit counting.
56 | 56 | Reserved.
57 | 57 | Reserved.
58 | Auto-UpdateStats | Collects the events associated with the automatic updating of index statistics.
59 | Lock:Deadlock Chain | Is produced for each of the events leading up to the deadlock.
60 | Lock:Escalation | Indicates that a finer-grained lock has been converted to a coarser-grained lock (for example, a row lock that is escalated or converted to a page lock).
61 | OLEDB Errors | Indicates that an OLE DB error has occurred.
62 | Replay Error | Error returned by ODBC.
63 | Replay Internal Error | Internal replay error.
64 | Replay Result Set | Indicates the beginning of a result set returned by a query.
65 | Replay Result Row | Produced for each row returned from a replay result set.
66 | 66 | Reserved.
67 | Execution Warnings | Indicates any warnings that occurred during the execution of a SQL Server statement or stored procedure.
68 | Execution Plan | Displays the plan tree of the Transact-SQL statement being executed.
69 | Sort Warnings | Indicates sort operations that do not fit into memory. Does not include sort operations involving the creating of indexes; only sort operations within a query (such as an ORDER BY clause used in a SELECT statement).
70 | CursorPrepare | Indicates when a cursor has been prepared on a Transact-SQL statement by ODBC or DB-Library.
71 | Prepare SQL | ODBC, OLE DB, or DB-Library has prepared a Transact-SQL statement for use.
72 | Exec Prepared SQL | ODBC, OLE DB, or DB-Library has executed a prepared Transact-SQL statement.
73 | Unprepare SQL | ODBC, OLE DB, or DB-Library has unprepared (deleted) a prepared Transact-SQL statement.
74 | CursorExecute | A cursor previously prepared on a Transact-SQL statement by ODBC, OLE DB, or DB-Library is executed.
75 | CursorRecompile | A cursor that is opened on a Transact-SQL statement by ODBC or DB-Library has been recompiled either directly or due to a schema change.
76 | CursorImplicitConversion | A cursor on a Transact-SQL statement is converted by SQL Server from one type to another.
77 | CursorUnprepare | A prepared cursor on a Transact-SQL statement is unprepared (deleted) by ODBC, OLE DB, or DB-Library.
78 | CursorClose | A cursor previously opened on a Transact-SQL statement by ODBC, OLE DB, or DB-Library is closed.
79 | Missing Column Statistics | Column statistics that could have been useful for the query optimizer are not available.
80 | Missing Join Predicate | A query is being executed that has no join predicate. This could result in a long-running query.
81 | Server Memory Change | Microsoft SQL Server memory usage has increased or decreased by either 1 MB or 5 percent of the maximum server memory, whichever is greater.
82 | UserConfigurable:1 | User configurable event. Collects event data defined by the user. For more information about user configurable events, see xp_trace_generate_event.
83 | UserConfigurable:2 | User configurable event. Collects event data defined by the user.
84 | UserConfigurable:3 | User configurable event. Collects event data defined by the user.
85 | UserConfigurable:4 | User configurable event. Collects event data defined by the user.
86 | UserConfigurable:5 | User configurable event. Collects event data defined by the user.

Return Code Values

0 (success) or >1 (failure)

Result Sets

xp_trace_eventclassrequired returns this result set when both required parameters are supplied.

Column name | Description
EventClass | Event class name
EventRequired | Whether EventClass is being traced (1) or not (0)

Permissions

Execute permissions for xp_trace_eventclassrequired default to members of the sysadmin fixed server role but can be granted to other users.

Examples
A. Specify only a trace queue handle

This example retrieves event information for all event classes for the trace queue by using an event class of 29 (update events).

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_eventclassrequired @queue_handle,

    29

B. Specify a trace queue handle and an event class

This example retrieves connect event information for the trace queue.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_eventclassrequired @queue_handle,

    14

See Also
xp_trace_addnewqueue | xp_trace_seteventclassrequired
xp_trace_geteventnames | System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_flushqueryhistory

Flushes the last 100 Microsoft® SQL Server™ SQL and exception events into the specified file name.

Syntax

xp_trace_flushqueryhistory 'filename'

Arguments
'filename'
Is the file name, including path, of a query history file. If no path is specified, SQL Server writes the query history file to the root directory on the computer running SQL Server.
Return Code Values

0 (success) or >1 (failure)

Result Sets

When filename is valid, xp_trace_flushqueryhistory returns this message.

The command(s) completed successfully.

Remarks

When used following xp_trace_setqueryhistory, SQL Server Profiler can open the specified file name to view the last 100 SQL Server SQL and exception events.

Permissions

Execute permissions for xp_trace_flushqueryhistory default to members of the sysadmin fixed server role but can be granted to other users.

See Also
xp_trace_setqueryhistory System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_generate_event

Adds a user-defined event to all queues. Returns no result set.

Syntax

xp_trace_generate_event {event_class} [, event_subclass]
[, integer_data] [, 'text_data'] [, binary_data]
[, severity] [, database_id] [, object_id] [, index_id]
[, transaction_id] [, connection_id] [, 'nt_user_name']
[, 'nt_domain_name'] [, 'host_name'] [, host_process_id]
[, 'application_name'] [, 'sql_user_name'] [, spid]
[, duration] [, start_time] [, end_time] [, reads]
[, writes] [, cpu_usage] [, dont_set]

Arguments
event_class
Is an integer value representing the user-defined event class for the user-defined event. event_class should be a value not used for Microsoft® SQL Server™ event classes. For more information about supported SQL Server event classes, see xp_trace_geteventnames.
event_subclass
Is an integer value representing the user-defined event subclass for the user-defined event.
integer_data
Is an integer value representing any integer value for a user-defined event.
'text_data'
Is a character value representing the user-defined event description, up to 255 characters.
binary_data
Is a binary value representing binary data for the user-defined event.
severity
Is an integer value representing the user-defined event's severity. Use severity to capture user-defined events only with the specified severity level.
database_id
Is an integer value representing the database identification number for the user-defined event.
object_id
Is an integer value representing the object identification number for the user-defined event.
index_id
Is an integer value representing the index identification number for the user-defined event.
transaction_id
Is an integer value representing the transaction identification number for the user-defined event.
connection_id
Is an integer value representing the connection identification number for the user-defined event.
'nt_user_name'
Is a character value representing the Microsoft Windows NT® username for the user-defined event (used with Windows NT Authentication).
'nt_domain_name'
Is a character value representing the Windows NT domain name for the user-defined event (used with Windows NT Authentication).
'host_name'
Is a character value representing the host or computer name for the user-defined event.
host_process_id
Is an integer value representing the host process identification number for the user-defined event.
'application_name'
Is a character value representing the application name for the user-defined event. If sending data to a table (using xp_trace_setqueuedestination), application_name must be specified; otherwise, no data is added to the table.
'sql_user_name'
Is a character value representing the SQL Server username for the user-defined event (used with SQL Server Authentication).
spid
Is an integer value representing the system process identification number (SPID) for the user-defined event.
duration
Is an integer value representing the duration of the user-defined event.
start_time
Is an integer value representing the start time of the user-defined event.
end_time
Is an integer value representing the end time of the user-defined event.
reads
Is an integer value representing the number of reads for the user-defined event.
writes
Is an integer value representing the number of writes for the user-defined event.
cpu_usage
Is an integer value representing the cpu usage of the user-defined event.
dont_set
Is an integer value (item mask) representing those required data columns that SQL Server should not automatically fill for this user-defined event. For more information about required data columns, see xp_trace_addnewqueue
Return Code Values

0 (success) or >1 (failure)

Result Sets

xp_trace_generate_event returns this message for a valid user-defined event:

The command(s) completed successfully.

Remarks

Use xp_trace_generate_event to write a producer and to produce user-defined events.

The event classes designated with an event class description of UserConfigurable (UserConfigurable:1, UserConfigurable:2, UserConfigurable:3, UserConfigurable:4, and UserConfigurable:5) are those event classes that can be used with xp_trace_generate_event. To obtain the event class numbers and corresponding names, execute xp_trace_geteventnames.

Permissions

Execute permissions for xp_trace_generate_event default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example creates a user-defined event with an event class of 82. This event class indicates the running of a script, and the completion of one stage of the process.

DECLARE @myvariable int

SET @myvariable = 4 -- Initialize to completion level.

EXEC xp_trace_generate_event @event_class = 82,

    @text_data = 'Stage 1 of Stage 3',

    @application_name = 'Myscript',

    -- Put the return value in a variable to check completion status.
    @integer_data = @myvariable,

    @nt_user_name = 'janetj'

See Also
xp_trace_setqueuedestination System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_getappfilter

Retrieves the current application filter value, which is configured by executing xp_trace_setappfilter and associated with the specified trace queue.

Syntax

xp_trace_getappfilter {queue_handle}

Arguments
queue_handle
Is an integer that represents the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
Return Code Values

0 (success) or >1 (failure)

Result Sets
Column name | Description
EventQueue | The trace queue number
IncludeAppFilter | Application include filter for the trace queue
ExcludeAppFilter | Application exclude filter for the trace queue

Remarks

If an application filter was set by executing xp_trace_setappfilter, xp_trace_getappfilter returns the name(s) of applications that, set by executing xp_trace_seteventclassrequired, will be traced.

The output shows the application filters, included and excluded, for the trace queue.

Permissions

Execute permissions for xp_trace_getappfilter default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example retrieves the application filter, if one exists (one may have been set by previously executing xp_trace_setappfilter) for the specified trace queue (@queue_handle).

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_getappfilter @queue_handle

See Also
xp_trace_setappfilter System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_getconnectionidfilter

Retrieves the current connection ID filter value, which is configured by executing xp_trace_setconnectionidfilter and associated with the specified trace queue.

Syntax

xp_trace_getconnectionidfilter {queue_handle}

Arguments
queue_handle
Is an integer that represents the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
Return Code Values

0 (success) or >1 (failure)

Result Sets
Column name | Description
EventQueue | The trace queue number
ConnectionIDFilter | The connection ID filter for the trace queue

Permissions

Execute permissions for xp_trace_getconnectionidfilter default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example retrieves the connection ID filter, if one exists (one may have been set by previously executing xp_trace_setcpufilter), for the specified trace queue (@queue_handle).

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_getconnectionidfilter @queue_handle

See Also
xp_trace_setconnectionidfilter System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_getcpufilter

Retrieves the current CPU filter value, which is configured by executing xp_trace_setcpufilter and associated with the specified trace queue.

Syntax

xp_trace_getcpufilter {queue_handle}

Arguments
queue_handle
Is an integer that represents the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
Return Code Values

0 (success) or >1 (failure)

Result Sets
Column name | Description
EventQueue | The trace queue number
MinCPU | Minimum value of CPU, in milliseconds, for the trace queue
MaxCPU | Maximum value of CPU, in milliseconds, for the trace queue

Permissions

Execute permissions for xp_trace_getcpufilter default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example retrieves the cpu filter, if one exists (one may have been set by previously executing xp_trace_setcpufilter) for the specified trace queue (@queue_handle).

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_getcpufilter @queue_handle

See Also
xp_trace_setcpufilter System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_getdbidfilter

Retrieves the current database identification number (DBID) filter value, which is configured by executing xp_trace_setdbidfilter and associated with the specified trace queue.

Syntax

xp_trace_getdbidfilter {queue_handle}

Arguments
queue_handle
Is an integer that represents the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
Return Code Values

0 (success) or >1 (failure)

Result Sets
Column name | Description
EventQueue | The trace queue number
DatabaseIDFilter | Database ID filter for the trace queue

Remarks

If a database ID filter was set by executing xp_trace_setdbidfilter, xp_trace_getdbidfilter returns the database ID(s) for which the specified event class(es) (set with xp_trace_seteventclassrequired) will be traced.

The output shows the database identification numbers captured for the trace queue.

Permissions

Execute permissions for xp_trace_getdbidfilter default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example retrieves the database ID filter, if one exists (one may have been set by previously executing xp_trace_setdbidfilter) for the specified trace queue (@queue_handle).

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_getdbidfilter @queue_handle

See Also
xp_trace_setdbidfilter System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_getdurationfilter

Retrieves the current definition of the duration filter value (the event duration), which is configured by executing xp_trace_setdurationfilter and associated with the specified trace queue.

Syntax

xp_trace_getdurationfilter {queue_handle}

Arguments
queue_handle
Is an integer that represents the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
Return Code Values

0 (success) or >1 (failure)

Result Sets
Column name | Description
EventQueue | The trace queue number
MinDuration | Minimum value for event duration for the trace queue
MaxDuration | Maximum value for event duration for the trace queue

Permissions

Execute permissions for xp_trace_getdurationfilter default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example retrieves the duration filter, if one exists (one may have been set by previously executing xp_trace_setdurationfilter) for the specified trace queue (@queue_handle).

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_getdurationfilter @queue_handle

See Also
xp_trace_setdurationfilter System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_geteventfilter

Retrieves the current event class-specific text filter definition, which is configured by executing xp_trace_seteventfilter and associated with the specified trace queue.

Syntax

xp_trace_geteventfilter {queue_handle} [, event_class]

Arguments
queue_handle
Is an integer representing the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
event_class
Is an integer representing the event class.
Return Code Values

0 (success) or >1 (failure)

Result Sets

xp_trace_geteventfilter returns this result set and returns a row for each required column.

Column name | Description
EventName | The event name number
IncludeEventFilter | The include text filter value for the specified event class
ExcludeEventFilter | The exclude text filter value for the specified event class

Permissions

Execute permissions for xp_trace_geteventfilter default to members of the sysadmin fixed server role but can be granted to other users.

Examples
A. Retrieve all event class-specific information

This example retrieves all event class-specific filter information, if event class information was set (by previously executing xp_trace_seteventfilter) for the specified trace queue (@queue_handle).

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_geteventfilter @queue_handle

B. Retrieve filter information for a specific event class

This example retrieves the event class filter information (set by executing xp_trace_seteventfilter) for event class 12 (SQL:BatchCompleted).

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_geteventfilter @queue_handle,

    12

See Also
xp_trace_seteventfilter System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_geteventnames

Lists the names of all event classes.

Syntax

xp_trace_geteventnames [event_class]

Arguments
event_class
Is an integer representing the class of events to list.
Return Code Values

0 (success) or >1 (failure)

Result Sets

xp_trace_geteventnames returns this result set when event_class is not specified.

Column name | Description
EventClass | Event class
EventName | Name for the corresponding event class

Remarks

If event_class is specified, only that event class is returned. Given an event class value, it returns the name of that event class. If event_class is not specified, all event classes and their names are listed

Set the events available to trace by using xp_trace_seteventclassrequired.

Generate user configurable events by executing xp_trace_generate_event.

Permissions

Execute permissions for xp_trace_geteventnames default to members of the sysadmin fixed server role but can be granted to other users.

Examples
A. Retrieve all event class information

This example retrieves the names of all event classes that are available to trace.

USE master

EXEC xp_trace_geteventnames

Here is the result set:

EventClass  EventName

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

0           TraceStart

1           TracePause

2           TraceRestart

3           TraceAutoPause

4           TraceAutoRestart

5           TraceStop

6           EventRequired

7           FilterChanged

8           8

9           9

10          RPC:Completed

11          RPC:Starting

12          SQL:BatchCompleted

13          SQL:BatchStarting

14          Connect

15          Disconnect

16          Attention

17          ExistingConnection

18          ServiceControl

19          DTCTransaction

20          LoginFailed

21          EventLog

22          ErrorLog

23          Lock:Released

24          Lock:Acquired

25          Lock:Deadlock

26          Lock:Cancel

27          Lock:Timeout

28          Insert

29          Update

30          Delete

31          Select

32          ConnectionBeingKilled

33          Exception

34          SP:CacheMiss

35          SP:CacheInsert

36          SP:CacheRemove

37          SP:Recompile

38          SP:CacheHit

39          SP:ExecContextHit

40          SQL:StmtStarting

41          SQL:StmtCompleted

42          SP:Starting

43          SP:Completed

44          SP:StmtStarting

45          SP:StmtCompleted

46          Object:Created

47          Object:Deleted

48          Object:Opened

49          Object:Closed

50          SQLTransaction

51          Scan:Started

52          Scan:Stopped

53          CursorOpen

54          TransactionLog

55          Hash Warning

56          56

57          57

58          Auto-UpdateStats

59          Lock:Deadlock Chain

60          Lock:Escalation

61          OLEDB Errors

62          Replay Error

63          Replay Internal Error

64          Replay Result Set

65          Replay Result Row

66          66

67          Execution Warnings

68          Execution Plan

69          Sort Warnings

70          CursorPrepare

71          Prepare SQL

72          Exec Prepared SQL

73          Unprepare SQL

74          CursorExecute

75          CursorRecompile

76          CursorImplicitConversion

77          CursorUnprepare

78          CursorClose

79          Missing Column Statstics

80          Missing Join Predicate

81          Server Memory Change

82          UserConfigurable:1

83          UserConfigurable:2

84          UserConfigurable:3

85          UserConfigurable:4

86          UserConfigurable:5

(87 row(s) affected)

Note TraceStart, TracePause, TraceRestart, TraceAutoPause, TraceAutoRestart, and TraceStop are created by SQL Server Profiler.

ConnectionBeingKilled, Replay Error, Replay Internal Error, Replay Result Set, and Replay Result Row are used by Replay.

B. Retrieve event class name for a specific event class

This example retrieves the event class name (Attention) given the event class number (16).

USE master

EXEC xp_trace_geteventnames 16

Here is the result set:

EventClass   EventName

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

16          Attention

(1 row(s) affected)

See Also
xp_trace_eventclassrequired | System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_seteventclassrequired |


xp_trace_getevents

Removes events from the trace queue created with xp_trace_addnewqueue and returns the events as a result set.

Syntax

xp_trace_getevents {queue_handle, is_fulltext, is_integerevents}
[, number_of_events]

Arguments
queue_handle
Is an integer that represents the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
is_fulltext
Is a Boolean value that determines the length of the text field display.

Value | Description
0 | Returns up to 255 characters.
1 | Returns full text of up to 2,147,483,648 characters (2^31). ( )

is_integerevents
Is a Boolean value that determines the event class display.

Value | Description
0 | Displays event as a string.
1 | Displays event as a integer.

number_of_events
Is an integer that represents the number of events to fetch from the trace queue. If this parameter is not specified, number_of_events fetches events as they are added to the trace queue, which is an infinite setting, and xp_trace_getevents never returns until the trace queue is destroyed. The minimum value is 1 and the maximum value is 232 or 4294967296.
Return Code Values

0 (success) or >1 (failure)

Result Sets
Column name | Description
EventClass | Event class name
ConnectionId | Connection ID removing events from the trace queue
NTUser | Windows NT username
Host | Computer name
Application | Application name removing events from the trace queue
StartTime | Time event removal began

Permissions

Execute permissions for xp_trace_getevents default to members of the sysadmin fixed server role but can be granted to other users.

Examples
A. Retrieve all events as strings and with full text display

This example retrieves all events from the trace queue, returns the full text event information, and returns each event as a string (rather than an integer).

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_getevents @queue_handle,

    1,

    0

B. Retrieve all events as 255 characters and as integers

This example retrieves all events from the trace queue, displays the event information as a maximum of 255 characters, and displays each event as an integer (rather than a string).

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_getevents @queue_handle,

    0,

    1

See Also
xp_trace_addnewqueue | xp_trace_geteventnames
xp_trace_eventclassrequired | System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_gethostfilter

Retrieves the current host filter value, which is configured by executing xp_trace_sethostfilter and associated with the specified trace queue.

Syntax

xp_trace_gethostfilter {queue_handle}

Arguments
queue_handle
Is an integer that represents the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
Return Code Values

0 (success) or >1 (failure)

Result Sets
Column name | Description
EventQueue | The trace queue number
IncludeHostFilter | Host include filter for the trace queue
ExcludeHostFilter | Host exclude filter for the trace queue

Permissions

Execute permissions for xp_trace_gethostfilter default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example retrieves the host filter value for the trace queue.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_gethostfilter @queue_handle

See Also
xp_trace_sethostfilter System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_gethpidfilter

Retrieves the host process identification number (HPID) filter, which is configured by executing xp_trace_sethpidfilter and associated with the specified trace queue.

Syntax

xp_trace_gethpidfilter {queue_handle}

Arguments
queue_handle
Is an integer that represents the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
Return Code Values

0 (success) or >1 (failure)

Result Sets
Column name | Description
EventQueue | The trace queue number
HostProcessIDFilter | Host process ID filter value for the trace queue

Permissions

Execute permissions for xp_trace_gethpidfilter default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example retrieves the host process ID filter value for the trace queue.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_gethpidfilter @queue_handle

See Also
xp_trace_sethpidfilter System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_getindidfilter

Retrieves the current index identification number (INDID) filter, which is configured by executing xp_trace_setindidfilter and associated with this trace queue.

Syntax

xp_trace_getindidfilter {queue_handle}

Arguments
queue_handle
Is an integer that represents the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
Return Code Values

0 (success) or >1 (failure)

Result Sets
Column name | Description
EventQueue | The trace queue number
IndexIDFilter | Index ID filter value for the trace queue

Permissions

Execute permissions for xp_trace_getindidfilter default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example retrieves the index ID filter value for the trace queue.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_getindidfilter @queue_handle

See Also
xp_trace_setindidfilter System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_getntdmfilter

Retrieves the current Microsoft® Windows NT® domain name filter, which is configured by executing xp_setntdmfilter and associated with the specified trace queue.

Syntax

xp_trace_getntdmfilter {queue_handle}

Arguments
queue_handle
Is an integer that represents the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
Return Code Values

0 (success) or >1 (failure)

Result Sets
Column name | Description
EventQueue | Trace queue number
IncludeNTDmFilter | Windows NT include filter for the trace queue
ExcludeNTDmFilter | Windows NT exclude filter for the trace queue

Remarks

The output shows the include and exclude filters used on Windows NT domain names.

Describes the include logic and the exclude logic.

Permissions

Execute permissions for xp_trace_getntdmfilter default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example retrieves the Windows NT domain name filter value for the trace queue.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_getntdmfilter @queue_handle

See Also
xp_trace_setntdmfilter System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_getntnmfilter

Retrieves the current Microsoft® Windows NT® computer name filter, which is configured by executing xp_trace_setntnmfilter and associated with the specified trace queue.

Syntax

xp_trace_getntnmfilter {queue_handle}

Arguments
queue_handle
Is an integer that represents the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
Return Code Values

0 (success) or >1 (failure)

Result Sets
Column name | Description
EventQueue | The trace queue number
IncludeNTNmFilter | Windows NT computer name include filter value for the trace queue
ExcludeNTNmFilter | Windows NT computer name exclude filter value for the trace queue.

Remarks

The output shows the include and exclude filters used on Windows NT computer names.

Permissions

Execute permissions for xp_trace_getntnmfilter default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example retrieves the Windows NT username filter value for trace queue.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_getntnmfilter @queue_handle

See Also
xp_trace_setntnmfilter System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_getobjidfilter

Retrieves the current object identification number (OBJID) filter, which is configured by executing xp_trace_setobjidfilter and associated with the specified trace queue.

Syntax

xp_trace_getobjidfilter {queue_handle}

Arguments
queue_handle
Is an integer that represents the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
Return Code Values

0 (success) or >1 (failure)

Result Sets
Column name | Description
EventQueue | The trace queue number
ObjectIDFilter | Object ID include filter value for the trace queue

Permissions

Execute permissions for xp_trace_getobjidfilter default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example retrieves the object ID filter value for the trace queue.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_getobjidfilter @queue_handle

See Also
xp_trace_setobjidfilter System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_getqueueautostart

Retrieves the specified trace definition startup configuration information, which is configured by executing xp_setqueueautostart and associated with the specified trace queue definition. The trace queue startup configuration information indicates the given trace queue for automatic start.

Syntax

xp_trace_getqueueautostart {'queue_name'}

Arguments
'queue_name'
Is a string value that represents the trace queue name. This name can be determined by executing xp_trace_enumqueuedefname.
Return Code Values

0 (success) or >1 (failure)

Result Sets
Column name | Description
QueueName | The trace queue name
AutoStart | Whether the trace queue is autostart enabled (1) or not (0)

Permissions

Execute permissions for xp_trace_getqueueautostart default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example retrieves the trace queue autostart status for the trace queue. Because xp_trace_getqueueautostart retrieves a previously defined trace queue, xp_trace_setqueuedefinition is executed before xp_trace_getqueueautostart.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_savequeuedefinition @queue_handle,

    'London Attention',

    1

EXEC xp_trace_getqueueautostart 'London Attention'

See Also
xp_trace_addnewqueue | xp_trace_loadqueuedefinition
xp_trace_deletequeuedefinition | xp_trace_pausequeue
xp_trace_destroyqueue | xp_trace_restartqueue
xp_trace_enumqueuedefname | xp_trace_savequeuedefinition
xp_trace_enumqueuehandles | System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_getqueuedestination

Retrieves the current trace queue destination value, which is configured by executing xp_trace_setqueuedestination and associated with the specified trace queue.

Syntax

xp_trace_getqueuedestination {queue_handle} [, destination]

Arguments
queue_handle
Is an integer representing the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
destination
Is an integer indicating the destination for the trace queue data. For the possible values for destination, see xp_trace_setqueuedestination. If destination is not supplied, all four possible destinations and their values are listed.
Return Code Values

0 (success) or >1 (failure)

Result Sets
Column name | Description
Destination | Destination value for trace events
On | Whether the Destination is enabled (1) or not (0)
Server | Name of the server for the Destination
Object | Name of the object (for example, table name if Destination is a table)

Permissions

Execute permissions for xp_trace_getqueuedestination default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example retrieves the destinations, if one or more exist (one or more may have been set by previously executing xp_trace_setqueuedestination) for the specified trace queue (@queue_handle).

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_getqueuedestination @queue_handle

See Also
xp_trace_setqueuedestination System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_getqueueproperties

Retrieves all current filters associated with the specified trace queue.

Syntax

xp_trace_getqueueproperties {queue_handle}

Arguments
queue_handle
Is an integer that represents the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
Return Code Values

0 (success) or >1 (failure)

Result Sets

xp_trace_getqueueproperties returns this result set (each required column returns a row).

Column name | Description
EventName | Event number
IncludeEventFilter | The include filter for the event
ExcludeEventFilter | The exclude filter for the event

For each required column, xp_trace_getqueueproperties returns this result set.

Column name | Description
EventQueue | The trace queue number
IncludeAppFilter | Application include filter value for the trace queue
ExcludeAppFilter | Application exclude filter value for the trace queue

For each required column, xp_trace_getqueueproperties returns this result set.

Column name | Description
EventQueue | The trace queue number
IncludeHostFilter | The include computer name filter value for the trace queue
ExcludeHostFilter | The exclude computer name filter value for the trace queue

For each required column, xp_trace_getqueueproperties returns this result set.

Column name | Description
EventQueue | The trace queue number
IncludeUserFilter | The include username filter value for the trace queue
ExcludeUserFilter | The exclude username filter value for the trace queue

For each required column, xp_trace_getqueueproperties returns this result set.

Column name | Description
EventQueue | The trace queue number
IncludeNTNmFilter | Microsoft® Windows NT® include computer name filter value for the trace queue
ExcludeNTNmFilter | Microsoft Windows NT exclude computer name filter value for the trace queue

For each required column, xp_trace_getqueueproperties returns this result set.

Column name | Description
EventQueue | The trace queue number
IncludeNTDmFilter | Microsoft® Windows NT® include domain name filter value for the trace queue
ExcludeNTDmFilter | Microsoft Windows NT exclude domain name filter value for the trace queue

For each required column, xp_trace_getqueueproperties returns this result set.

Column name | Description
EventQueue | The trace queue number
IncludeTextFilter | The include text filter value for the trace queue
ExcludeTextFilter | The exclude text filter value for the trace queue

xp_trace_getqueueproperties returns this result set.

Column name | Description
EventQueue | The trace queue number
IndexIDFilter | Index ID filter value for the trace queue

xp_trace_getqueueproperties returns this result set.

Column name | Description
EventQueue | The trace queue number
DatabaseIDFilter | Database ID filter value for the trace queue

xp_trace_getqueueproperties returns this result set.

Column name | Description
EventQueue | The trace queue number
ObjectIDFilter | Object ID filter value for the trace queue

xp_trace_getqueueproperties returns this result set.

Column name | Description
EventQueue | The trace queue number
ConnectionIDFilter | Connection ID filter value for the trace queue

xp_trace_getqueueproperties returns this result set.

Column name | Description
EventQueue | The trace queue number
HostProcessIDFilter | Host process ID filter value for the trace queue

xp_trace_getqueueproperties returns this result set.

Column name | Description
EventQueue | The trace queue number
SPIDFilter | SPID filter value for the trace queue

xp_trace_getqueueproperties returns this result set.

Column name | Description
EventQueue | The trace queue number
MinSeverity | Minimum severity value for the trace queue
MaxSeverity | Maximum severity value for the trace queue

xp_trace_getqueueproperties returns this result set.

Column name | Description
EventQueue | The trace queue number
MinRead | Minimum read value for the trace queue
MaxRead | Maximum read value for the trace queue

xp_trace_getqueueproperties returns this result set.

Column name | Description
EventQueue | The trace queue number
MinWrite | Minimum write value for the trace queue
MaxWrite | Maximum write value for the trace queue

xp_trace_getqueueproperties returns this result set.

Column name | Description
EventQueue | The trace queue number
MinCPU | Minimum CPU value for the trace queue
MaxCPU | Maximum CPU value for the trace queue

xp_trace_getqueueproperties returns this result set.

Column name | Description
EventQueue | The trace queue number
MinDuration | Minimum duration value for the trace queue
MaxDuration | Maximum duration value for the trace queue

xp_trace_getqueueproperties returns this result set (one row for each event class).

Column name | Description
EventClass | Event class name
EventRequired | Whether this event class is required (1) or not (0) for the trace queue

Permissions

Execute permissions for xp_trace_getqueueproperties default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example retrieves all filter value information for the trace queue.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_getqueueproperties @queue_handle

See Also
xp_trace_addnewqueue System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_getreadfilter

Retrieves the current read filter, which is configured by executing xp_trace_setreadfilter and associated with the specified trace queue.

Syntax

xp_trace_getreadfilter {queue_handle}

Arguments
queue_handle
Is an integer that represents the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
Return Code Values

0 (success) or >1 (failure)

Result Sets
Column name | Description
EventQueue | The trace queue number
MinRead | Minimum read operation filter value for the trace queue
MaxRead | Maximum read operation filter value for the trace queue

Permissions

Execute permissions for xp_trace_getreadfilter default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example retrieves the read filter value information for trace queue.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_getreadfilter @queue_handle

See Also
xp_trace_setreadfilter System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_getserverfilter

Retrieves the current server filter, which is configured by executing xp_trace_setserverfilter and associated with the specified trace queue.

Syntax

xp_trace_getserverfilter {queue_handle}

Arguments
queue_handle
Is an integer that represents the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
Return Code Values

0 (success) or >1 (failure)

Result Sets
Column name | Description
EventQueue | The trace queue number
IncludeServerFilter | Server name include filter for the trace queue
ExcludeServerFilter | Server name exclude filter for the trace queue

Remarks

The output describes the included and the excluded servers for the trace.

Permissions

Execute permissions for xp_trace_getserverfilter default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example retrieves the server filter value information for the trace queue.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_getserverfilter @queue_handle

See Also
xp_trace_setserverfilter System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_getseverityfilter

Retrieves the current severity filter, which is configured by executing xp_trace_setseverityfilter and associated with the specified trace queue.

Syntax

xp_trace_getseverityfilter {queue_handle}

Arguments
queue_handle
Is an integer that represents the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
Return Code Values

0 (success) or >1 (failure)

Result Sets
Column name | Description
EventQueue | The trace queue number
MinSeverity | Minimum severity filter value for the trace queue
MaxSeverity | Maximum severity filter value for the trace queue

Permissions

Execute permissions for xp_trace_getseverityfilter default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example retrieves the severity filter value information for the trace queue.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_getseverityfilter @queue_handle

See Also
xp_trace_setseverityfilter System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_getspidfilter

Retrieves the current system (internal) process identification number (SPID) filter, which is configured by executing xp_trace_setspidfilter and associated with the specified trace queue.

Syntax

xp_trace_getspidfilter {queue_handle}

Arguments
queue_handle
Is an integer that represents the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
Return Code Values

0 (success) or >1 (failure)

Result Sets
Column name | Description
EventQueue | The trace queue number
SPIDFilter | SPID filter value for the trace queue

Permissions

Execute permissions for xp_trace_getspidfilter default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example retrieves the SPID filter value information for the trace queue.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_getspidfilter @queue_handle

See Also
xp_trace_setspidfilter System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_getsysobjectsfilter

Retrieves the current system objects filter, which is configured by executing xp_trace_setsysobjectsfilter and associated with the specified trace queue.

Syntax

xp_trace_getsysobjectsfilter {queue_handle}

Arguments
queue_handle
Is an integer that represents the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
Return Code Values

0 (success) or >1 (failure)

Result Sets
Column name | Description
EventQueue | The trace queue number
SystemObjectsFilter | Whether system objects are being captured (0) or not (1)

Permissions

Execute permissions for xp_trace_getsysobjectsfilter default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example retrieves the severity filter value information for trace queue.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_getsysobjectsfilter @queue_handle

See Also
xp_trace_setsysobjectsfilter System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_gettextfilter

Retrieves the current text filter, which is configured by executing xp_trace_settextfilter and associated with the specified trace queue.

Syntax

xp_trace_gettextfilter {queue_handle}

Arguments
queue_handle
Is an integer that represents the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
Return Code Values

0 (success) or >1 (failure)

Result Sets
Column name | Description
EventQueue | The trace queue number
IncludeTextFilter | The include text filter value for the trace queue
ExcludeTextFilter | The exclude text filter value for the trace queue

Permissions

Execute permissions for xp_trace_gettextfilter default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example retrieves the text filter value information for trace queue.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_gettextfilter @queue_handle

See Also
xp_trace_settextfilter System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_getuserfilter

Retrieves the current SQL user filter, which is configured by executing xp_trace_setuserfilter and associated with the specified trace queue.

Syntax

xp_trace_getuserfilter {queue_handle}

Arguments
queue_handle
Is an integer that represents the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
Return Code Values

0 (success) or >1 (failure)

Result Sets
Column name | Description
EventQueue | The trace queue number
IncludeUserFilter | The include user filter value for the trace queue
ExcludeUserFilter | The exclude user filter value for the trace queue

Remarks

The output shows the include and exclude filters used for the Microsoft® SQL Server™ usernames.

Permissions

Execute permissions for xp_trace_getuserfilter default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example retrieves the user filter value information for the trace queue.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_getuserfilter @queue_handle

See Also
xp_trace_setuserfilter System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_getwritefilter

Retrieves the current write filter, which is configured by executing xp_trace_setwritefilter and associated with the specified trace queue.

Syntax

xp_trace_getwritefilter {queue_handle}

Arguments
queue_handle
Is an integer that represents the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
Return Code Values

0 (success) or >1 (failure)

Result Sets
Column name | Description
EventQueue | The trace queue number
MinWrite | Minimum write value for the trace queue
MaxWrite | Maximum write value for the trace queue

Permissions

Execute permissions for xp_trace_getwritefilter default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example retrieves the write filter value information for the trace queue.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_getwritefilter @queue_handle

See Also
xp_trace_setwritefilter System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_loadqueuedefinition

Loads a saved trace queue definition stored in the registry, which is configured by executing xp_trace_savequeuedefinition and associated with the specified trace queue. A trace queue definition is all of the information that makes up a trace queue including the name, the data to trace for the trace queue, and any configured filters.

Syntax

xp_trace_loadqueuedefinition {queue_handle, 'queue_name', is_shared}

Arguments
queue_handle
Is an integer representing the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
'queue_name'
Is a string specifying the trace queue name. queue_name can be determined by executing xp_trace_enumqueuedefname.
is_shared
Is a Boolean value specifying whether the trace queue definition is shared (1) or private (0).
Return Code Values

0 (success) or >1 (failure)

Result Sets

xp_trace_loadqueuedefinition returns this message:

The command(s) completed successfully.

Remarks

A trace queue handle must be created by using xp_trace_addnewqueue before calling xp_trace_loadqueuedefinition.

The trace queue definition information, configured and saved by using xp_trace_savequeuedefinition, is used by the specified trace queue to determine the events, data, and filters that will be applied.

Permissions

Execute permissions for xp_trace_loadqueuedefinition default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example loads a shared trace queue definition for the trace queue. Because xp_trace_loadqueuedefinition requires a previously saved trace queue definition, xp_trace_savequeuedefinition is executed before xp_trace_loadqueuedefinition.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_savequeuedefinition @queue_handle,

    'Seattle SQL Batch Starting and Completing',

    1

EXEC xp_trace_loadqueuedefinition @queue_handle,

    'Seattle SQL Batch Starting and Completing',

    1

See Also
xp_trace_addnewqueue | xp_trace_pausequeue
xp_trace_deletequeuedefinition | xp_trace_restartqueue
xp_trace_destroyqueue | xp_trace_setqueueautostart
xp_trace_enumqueuehandles | System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_getqueueautostart |


xp_trace_pausequeue

Suspends new events from being added to the trace queue.

Syntax

xp_trace_pausequeue {queue_handle}

Arguments
queue_handle
Is an integer that represents the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
Return Code Values

0 (success) or >1 (failure)

Result Sets

xp_trace_loadpausequeue returns this message:

The command(s) completed successfully.

Remarks

xp_trace_pausequeue does not impose a time limit before allowing the addition of new events to the trace queue. Use xp_trace_restartqueue to restart a paused trace queue.

Pause a trace queue to:

  • Check the status of an existing trace.
  • Monitor the output of an existing trace, if the trace queue is producing a larger volume of trace information than expected.
Permissions

Execute permissions for xp_trace_pausequeue default to members of the sysadmin fixed server role but can be granted to other users. Any person who defines a trace queue has the appropriate permissions to pause processing of the same trace queue.

Examples

This example pauses the specified trace queue.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_pausequeue @queue_handle

See Also
xp_trace_addnewqueue | xp_trace_loadqueuedefinition
xp_trace_deletequeuedefinition | xp_trace_restartqueue
xp_trace_destroyqueue | xp_trace_savequeuedefinition
xp_trace_enumqueuedefname | xp_trace_getqueueautostart
xp_trace_enumqueuehandles | System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_setqueueautostart |


xp_trace_restartqueue

Restarts a previously paused trace queue.

Syntax

xp_trace_restartqueue {queue_handle}

Arguments
queue_handle
Is an integer that represents the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
Return Code Values

0 (success) or >1 (failure)

Result Sets

xp_trace_restartqueue returns this message:

The command(s) completed successfully.

Permissions

Execute permissions for xp_trace_restartqueue default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example restarts the previously pauses trace queue definition for trace queue.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_pausequeue @queue_handle

EXEC xp_trace_restartqueue @queue_handle

See Also
xp_trace_addnewqueue | xp_trace_getqueueautostart
xp_trace_deletequeuedefinition | xp_trace_loadqueuedefinition
xp_trace_destroyqueue | xp_trace_pausequeue
xp_trace_enumqueuedefname | xp_trace_savequeuedefinition
xp_trace_enumqueuehandles | System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_savequeuedefinition

Specifies the trace queue definition to save.

Syntax

xp_trace_savequeuedefinition {queue_handle, 'queue_name', is_shared}

Arguments
queue_handle
Is an integer representing the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
'queue_name'
Is a string specifying the name under which the trace queue is saved.
is_shared
Is a Boolean value specifying whether a trace queue definition is private (0) or shared (1).
Return Code Values

0 (success) or >1 (failure)

Result Sets

xp_trace_savequeuedefinition returns this message:

The command(s) completed successfully.

Remarks

If you choose to save a queue definition as a private definition, it is only available to you. If you choose to save a queue definition as a shared definition, it is available to anyone who logs on to that particular computer.

Permissions

Execute permissions for xp_trace_savequeuedefinition default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example saves the trace queue definition for the Seattle SQL Batch Starting and Completing trace queue as a private trace queue definition.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_savequeuedefinition @queue_handle,

    'Seattle SQL Batch Starting and Completing',

    0

See Also
xp_trace_addnewqueue | xp_trace_loadqueuedefinition
xp_trace_deletequeuedefinition | xp_trace_pausequeue
xp_trace_destroyqueue | xp_trace_restartqueue
xp_trace_enumqueuedefname | xp_trace_setqueueautostart
xp_trace_enumqueuehandles | System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_getqueueautostart |


xp_trace_setappfilter

Specifies the application filter, or the applications to include or exclude for the trace specified. Microsoft® SQL Server™ captures the required information, configured by executing xp_trace_seteventclassrequired, for the included applications, if any, and does not capture the required information for the excluded applications, if any.

Syntax

xp_trace_setappfilter {queue_handle, 'include_only_applications',
'exclude_applications'}

Arguments
queue_handle
Is an integer that represents the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
'include_only_applications'
Is a string that represents the application include filter. The application include filter indicates the applications, separated by semicolons (;), that should be considered when capturing data previously determined by sp_seteventclassrequired. The % wildcard character can be used in specifying the applications to include in the trace. If NULL, there are no restrictions on applications to include for the specified event class(es). The table shows three common applications you can choose to trace events for (these applications are included with SQL Server).

Value | Description
MS SQLEM | SQL Server Enterprise Manager
Microsoft SQL Server Query Analyzer | SQL Server Query Analyzer
xpsqlweb.dll | Web Assistant Wizard

'exclude_applications'
Is a string that represents the application exclude filter. The application exclude filter indicates the applications, separated by semicolons (;), that should not be considered when capturing data previously determined by sp_seteventclassrequired. The % wildcard character can be used in specifying the applications to exclude for the trace. If NULL, there are no application exclude requirements. The most common application you may choose to exclude is SQL Server Profiler itself.
Return Code Values

0 (success) or >1 (failure)

Result Sets

xp_trace_setappfilter returns this message:

The command(s) completed successfully.

Remarks

When you specify one or more applications to include, all other applications are excluded.

Note The event class list can be generated using xp_trace_geteventnames.

Permissions

Execute permissions for xp_trace_setappfilter default to members of the sysadmin fixed server role but can be granted to other users.

Examples
A. Include only SQL Server Query Analyzer and SQL Server Enterprise Manager

This example executes xp_trace_setappfilter to include events from SQL Server Query Analyzer and SQL Server Enterprise Manager.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_setappfilter @queue_handle,

    'Microsoft SQL Server Query Ana%;MS SQLEM%',

    NULL

B. Include only SQL Server Query Analyzer and exclude SQL Server Profiler

This example executes xp_trace_setappfilter to only include events from SQL Server Query Analyzer.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_setappfilter @queue_handle,

    'Microsoft SQL Server Query Ana%',

    'SQL Server Profiler%'

See Also
xp_trace_addnewqueue | xp_trace_getqueueproperties
xp_trace_enumqueuehandles | System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_getappfilter |


xp_trace_setconnectionidfilter

Specifies the connection ID filter, or the connection ID to include for the events specified. Microsoft® SQL Server™ captures the required information, configured by executing xp_trace_seteventclassrequired, for the included connection ID.

Syntax

xp_trace_setconnectionidfilter {queue_handle, connection_ID}

Arguments
queue_handle
Is an integer that represents the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
connection_ID
Is an integer that specifies the connection ID. Connection IDs can be obtained by starting a trace in SQL Server Profiler and then identifying a unique connection ID to trace.
Return Code Values

0 (success) or >1 (failure)

Result Sets

xp_trace_setconnectionidfilter returns this message:

The command(s) completed successfully.

Permissions

Execute permissions for xp_trace_setconnectionidfilter default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example configures the connection ID filter for a trace queue and uses a connection ID value of 1323.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_setconnectionidfilter @queue_handle,

    1323

See Also
xp_trace_addnewqueue | xp_trace_getqueueproperties
xp_trace_getconnectionidfilter | System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_enumqueuehandles |


xp_trace_setcpufilter

Specifies the CPU filter, or the minimum and maximum CPU time in milliseconds to include for the events specified. Microsoft® SQL Server™ captures the required information, configured by executing xp_trace_seteventclassrequired, for all events with a CPU time greater than the minimum, if any, and less than the maximum, if any.

Syntax

xp_trace_setcpufilter {queue_handle, minimum_cpu, maximum_cpu}

Arguments
queue_handle
Is an integer representing the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
minimum_cpu
Is an integer specifying the minimum number of CPU milliseconds for which to trace. If 0, there is no minimum_cpu value. The maximum value that can be used is 232 or 4294967296.
maximum_cpu
Is an integer specifying the maximum number of CPU milliseconds for which to trace. If 0, there is no maximum_cpu value. The maximum value that can be used is 232 or 4294967296.
Return Code Values

0 (success) or >1 (failure)

Result Sets

xp_trace_setcpufilter returns this message:

The command(s) completed successfully.

Permissions

Execute permissions for xp_trace_setcpufilter default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example configures the CPU filter for the trace queue and specifies a minimum of 100 CPU milliseconds and a maximum of 5000 milliseconds.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_setcpufilter @queue_handle,

    100,

    5000

See Also
xp_trace_addnewqueue | xp_trace_getqueueproperties
xp_trace_enumqueuehandles | System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_getcpufilter |


xp_trace_setdbidfilter

Specifies the database identification number (ID) filter, or the database to include for the events specified. Microsoft® SQL Server™ captures the required information, configured by executing xp_trace_seteventclassrequired, for the specified DBID.

Syntax

xp_trace_setdbidfilter {queue_handle, database_ID}

Arguments
queue_handle
Is an integer representing the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
database_ID
Is an integer specifying for which database ID to trace events. Execute sp_helpdb to determine possible database ID values for this filter.
Return Code Values

0 (success) or >1 (failure)

Result Sets

xp_trace_setdbidfilter returns this message:

The command(s) completed successfully.

Remarks

If a database ID filter was set by executing xp_trace_setdbidfilter, xp_trace_getdbidfilter returns the database ID(s) for which the specified event class(es) will be traced.

Permissions

Execute permissions for xp_trace_setdbidfilter default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example sets the database ID for the trace queue that was configured to include a database with a DBID of 17.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_setdbidfilter @queue_handle,

    17

See Also
sp_helpdb | xp_trace_getdbidfilter
xp_trace_addnewqueue | xp_trace_getqueueproperties
xp_trace_enumqueuehandles | System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_setdurationfilter

Specifies the duration filter, or the minimum and maximum event duration to capture for the events specified. Microsoft® SQL Server™ captures the required information, configured by executing xp_trace_seteventclassrequired, for all events with a duration greater than the minimum duration, if any, and less than the maximum duration, if any.

Syntax

xp_trace_setdurationfilter {queue_handle, minimum_duration,
maximum_duration}

Arguments
queue_handle
Is an integer representing the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
minimum_duration
Is an integer specifying the minimum duration of an event for which to trace. If 0, there is no minimum_duration value. The maximum value that can be used is 232 or 4294967296.
maximum_duration
Is an integer specifying the maximum duration of an event for which to trace. If 0, there is no maximum_duration value. The maximum value that can be used is 232 or 4294967296.
Return Code Values

0 (success) or >1 (failure)

Result Sets

xp_trace_setdurationfilter returns this message:

The command(s) completed successfully.

Permissions

Execute permissions for xp_trace_setdurationfilter default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example configures the duration filter for the trace queue and specifies a minimum duration of 1000 and a maximum of 23427.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_setdurationfilter @queue_handle,

    1000,

    23427

See Also
xp_trace_addnewqueue | xp_trace_getqueueproperties
xp_trace_getdurationfilter | System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_enumqueuehandles |


xp_trace_seteventclassrequired

Specifies the event classes to trace or not trace for the specified trace queue.

Syntax

xp_trace_seteventclassrequired {queue_handle, event_class,
isrequired}

Arguments
queue_handle
Is an integer representing the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
event_class
Is an integer representing the class of events to capture.
isrequired
Is a Boolean value indicating whether event_class is included (1) or is not included (0) in trace results.
Return Code Values

0 (success) or >1 (failure)

Result Sets

xp_trace_seteventclassrequired returns this message:

The command(s) completed successfully.

Remarks

Generate the event class list by executing xp_trace_geteventnames.

Permissions

Execute permissions for xp_trace_seteventclassrequired default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example sets the trace queue to trace all attention events (event class value of 16).

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_seteventclassrequired @queue_handle,

    16,

    1

See Also
xp_trace_addnewqueue | xp_trace_geteventnames
xp_trace_eventclassrequired | System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_seteventfilter

Specifies an event-specific text filter, or the text to include or exclude from the event specified. Microsoft® SQL Server™ captures the required information, configured by executing xp_trace_seteventclassrequired, for the included text for the specified event class and does not capture the required information for the excluded text, if any.

Syntax

xp_trace_seteventfilter {queue_handle, event_class, 'include_only_events',
'exclude_events'}

Arguments
queue_handle
Is an integer that represents the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
event_class
Is an integer value that represents the event class to filter. For more information about the possible values for event_class, see xp_trace_eventclassrequired.
'include_only_events'
Is a string value that represents the event include filter. The event include filter indicates the events, separated by semicolons (;), that should be considered when capturing data previously determined by xp_seteventclassrequired. The % wildcard character can be used in specifying the events to include in the trace. If NULL, there are no restrictions on events to include for the specified event classes.
'exclude_events'
Is a string value that represents the event exclude filter. The event exclude filter indicates the events, separated by semicolons (;), that should not be considered when capturing data previously determined by sp_seteventclassrequired. The % wildcard character can be used in specifying the events to exclude in the trace. If NULL, there are no excluded events for the specified event classes.
Return Code Values

0 (success) or >1 (failure)

Result Sets

xp_trace_seteventfilter returns this message:

The command(s) completed successfully.

Remarks

Generate the event class list by executing xp_trace_geteventnames.

When you specify one or more events to include, all other events are excluded.

Permissions

Execute permissions for xp_trace_seteventfilter default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example configures the event filter to retrieve all INSERT, UPDATE, and DELETE events in event class 13 (SQL:BatchStarting) for the trace queue.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_seteventfilter @queue_handle,

    13,

    'INSERT%;DELETE%;UPDATE%',

    NULL

See Also
xp_trace_addnewqueue | xp_trace_getqueueproperties
xp_trace_geteventfilter | System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_enumqueuehandles |


xp_trace_sethostfilter

Specifies the host name filter, or the hosts (computers) to include and/or exclude for the events specified. Microsoft® SQL Server™ captures the required information, configured by executing xp_trace_seteventclassrequired, for the included hosts, if any, and does not capture the required information for the excluded hosts, if any.

Syntax

xp_trace_sethostfilter {queue_handle, 'include_hosts', 'exclude_hosts'}

Arguments
queue_handle
Is an integer that represents the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
'include_hosts'
Is a string value that represents the host include filter. The host include filter indicates the hosts, separated by semicolons (;), that should be considered when capturing data previously determined by sp_seteventclassrequired. The % wildcard character can be used in specifying the hosts to include in the trace. If NULL is passed, there are no restrictions on hosts to include for the specified event classes.

Note Host names can be found in the sysprocesses system table.

'exclude_hosts'
Is a string value that represents the host exclude filter. The host exclude filter indicates the hosts, separated by semicolons (;), that should not be considered when capturing data previously determined by sp_seteventclassrequired. The % wildcard character can be used in specifying the hosts to exclude from the trace. If NULL, there are no excluded hosts for the specified event classes.
Return Code Values

0 (success) or >1 (failure)

Result Sets

xp_trace_sethostfilter returns this message:

The command(s) completed successfully.

Remarks

Generate the event class list by executing xp_trace_geteventnames.

When you have specify one or more hosts to include, all other hosts are excluded.

Permissions

Execute permissions for xp_trace_sethostfilter default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example configures the host filter value for trace queue so all hosts starting with the string SEATTLE will be included in the trace.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_sethostfilter @queue_handle,

    'SEATTLE%',

    NULL

See Also
xp_trace_addnewqueue | xp_trace_getqueueproperties
xp_trace_enumqueuehandles | System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_gethostfilter |


xp_trace_sethpidfilter

Specifies the host process identification number (HPID) filter, or the host process ID to include for the events specified. Microsoft® SQL Server™ captures the required information, configured by executing xp_trace_seteventclassrequired, for the specified HPID.

Syntax

xp_trace_sethpidfilter {queue_handle, process_ID}

Arguments
queue_handle
Is an integer representing the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
process_ID
Is an integer specifying the host process ID. Host process IDs can be found in the sysprocesses system table.
Return Code Values

0 (success) or >1 (failure)

Result Sets

xp_trace_sethpidfilter returns this message:

The command(s) completed successfully.

Permissions

Execute permissions for xp_trace_sethpidfilter default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example configures the host process ID filter value for the trace queue.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_sethpidfilter @queue_handle,

    5199

See Also
xp_trace_addnewqueue | xp_trace_getqueueproperties
xp_trace_enumqueuehandles | System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_gethpidfilter |


xp_trace_setindidfilter

Specifies the index identification number (INDID) filter, or the index ID to include for the events specified. Microsoft® SQL Server™ captures the required information, configured by executing xp_trace_seteventclassrequired, for the specified INDID.

Syntax

xp_trace_setindidfilter {queue_handle, index_ID}

Arguments
queue_handle
Is an integer representing the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
index_ID
Is an integer specifying the database index ID for which to capture events. Index IDs can be found in the sysindexes system table.
Return Code Values

0 (success) or >1 (failure)

Result Sets

xp_trace_setindidfilter returns this message:

The command(s) completed successfully.

Permissions

Execute permissions for xp_trace_setindidfilter default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example configures the index ID filter value for the trace queue and uses an index ID of 91, which is the index ID number for the index of a table.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_setindidfilter @queue_handle,

    91

See Also
xp_trace_addnewqueue | xp_trace_getqueueproperties
xp_trace_enumqueuehandles | System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_getindidfilter |


xp_trace_setntdmfilter

Specifies the existing Microsoft® Windows NT® domain name filter, or the existing Windows NT domains to include or exclude for the events specified. Microsoft SQL Server™ captures the required information, configured by executing xp_trace_seteventclassrequired, for the included Windows NT domains, if any, and does not capture the required information for the excluded Windows NT domains, if any.

Syntax

xp_trace_setntdmfilter {queue_handle, 'include_domains',
'exclude_domains'}

Arguments
queue_handle
Is an integer that represents the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
'include_domains'
Is a string value that represents the Windows NT domain name include filter. The Windows NT domain name include filter indicates the Windows NT domains, separated by semicolons (;), that should be considered when capturing data previously determined by sp_seteventclassrequired. The % wildcard character can be used in specifying the Windows NT domains to include in the trace. If NULL, there are no restrictions on Windows NT domains to include for the specified event classes.

Note Windows NT domain values can be obtained either from knowledge of the domain names or from the sysprocesses system table.

'exclude_domains'
Is a string value that represents the Windows NT domain name exclude filter. The Windows NT domain name exclude filter indicates the Windows NT domains, separated by semicolons (;), that should not be considered when capturing data previously determined by sp_seteventclassrequired. The % wildcard character can be used in specifying the Windows NT domains to exclude in the trace. If NULL, there are no excluded Windows NT domains for the specified event classes.
Return Code Values

0 (success) or >1 (failure)

Result Sets

xp_trace_setntdmfilter returns this message:

The command(s) completed successfully.

Remarks

To further filter a trace, see one of the xp_trace_set*filter procedures.

Generate the event class list by executing xp_trace_geteventnames.

When you specify one or more domain names to include, all other domain names are excluded.

Permissions

Execute permissions for xp_trace_setntdmfilter default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example configures the Windows NT domain name filter value for the trace queue. The Windows NT domains to include are sales and marketing, and the domain to exclude is the accounting domain.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_setntdmfilter @queue_handle,

    'sales%;marketing%',

    'accounting%'

See Also
xp_trace_enumqueuehandles | xp_trace_getqueueproperties
xp_trace_getntdmfilter | System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_setntnmfilter

Specifies the Microsoft® Windows NT® username filter or the Windows NT usernames to include or exclude for the events specified. Microsoft SQL Server™ captures the required information, configured by executing xp_trace_seteventclassrequired, for the included Windows NT usernames, if any, and does not capture the required information for the excluded Windows NT usernames, if any.

Syntax

xp_trace_setntnmfilter {queue_handle, 'include_NTusers',
'exclude_NTusers'}

Arguments
queue_handle
Is an integer that represents the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
'include_NTusers'
Is a string value that represents the Windows NT username include filter. The Windows NT username include filter indicates the Windows NT users, separated by semicolons (;), that should be considered when capturing data previously determined by sp_seteventclassrequired. The % wildcard character can be used in specifying the Windows NT users to include in the trace. If NULL, there are no restrictions on Windows NT users to include for the specified event classes.
'exclude_NTusers'
Is a string value that represents the Windows NT username exclude filter. The Windows NT username exclude filter indicates the Windows NT users, separated by semicolons (;), that should not be considered when capturing data previously determined by sp_seteventclassrequired. The % wildcard character can be used in specifying the Windows NT users to exclude in the trace. If NULL, there are no excluded Windows NT users for the specified event classes.
Return Code Values

0 (success) or >1 (failure)

Result Sets

xp_trace_setntnmfilter returns this message:

The command(s) completed successfully.

Remarks

Generate the event class list by executing xp_trace_geteventnames.

When you specify one or more usernames to include, all other usernames are excluded.

Permissions

Execute permissions for xp_trace_setntnmfilter default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example configures the Windows NT username filter value for trace queue. The usernames to include are nancyd and stevenb. The username janetl is excluded.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_setntnmfilter @queue_handle,

    'nancyd%;stevenb%',

    'janetl%'

See Also
xp_trace_enumqueuehandles | xp_trace_getqueueproperties
xp_trace_getntnmfilter | System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_setobjidfilter

Specifies the object identification number (OBJID) filter or the object ID to include for the events specified. Microsoft® SQL Server™ captures the required information, configured by executing xp_trace_seteventclassrequired, for the specified OBJID.

Syntax

xp_trace_setobjidfilter {queue_handle, object_ID}

Arguments
queue_handle
Is an integer that represents the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
object_ID
Is an integer that specifies the object ID for which to capture events. Object IDs can be obtained from the sysobjects system table.
Return Code Values

0 (success) or >1 (failure)

Result Sets

xp_trace_setobjidfilter returns this message:

The command(s) completed successfully.

Permissions

Execute permissions for xp_trace_setobjidfilter default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example configures the object ID filter value for the trace queue. A value of 532 is used as the title ID for the titles table in the pubs database.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_setobjidfilter @queue_handle,

    532

See Also
xp_trace_enumqueuehandles | xp_trace_getqueueproperties
xp_trace_getobjidfilter | System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_setqueryhistory

Specifies the enabling or disabling of query history using the SQL Server Profiler extended stored procedures. Query history consists of a trace of the last 100 events that occurred before a high-severity SQL Server exception. Query history traces SQL:BatchStarting, RPC:Starting and Exception events and captures all data columns. When an exception of severity 17 or greater occurs, the query history is written to the file Blackbox.trc in \Mssql7\Log.

Syntax

xp_trace_setqueryhistory [[@local_variable =] value]

Arguments
@local_variable
Is a local variable of bit data type.
value
Is whether query history is enabled (1) or disabled (0). When query history is enabled, SQL Server captures the last 100 SQL Server events. If value is not specified, SQL Server returns the current value for xp_trace_setqueryhistory.
Return Code Values

0 (success) or >1 (failure)

Result Sets

If value is specified, xp_trace_setqueryhistory returns this message:

The command(s) completed successfully.

If value is not specified, xp_trace_setqueryhistory returns this result set.

Column name | Description
QueryHistoryConfigValue | Whether the query history trace is configured to start on start up: 1 = True 0 = False
QueryHistoryRunValue | Whether the query history trace is running: 1 = True 0 = False

Permissions

Execute permissions for xp_trace_setqueryhistory default to members of the sysadmin fixed server role but can be granted to other users.

See Also
DECLARE @local_variable | xp_trace_flushqueryhistory
SET @local_variable | System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_setqueueautostart

Configures the specified trace queue for automatic startup on the server’s next restart. There is no maximum number of automatic start trace queues.

Syntax

xp_trace_setqueueautostart {'queue_name', autostart_value}

Arguments
'queue_name'
Is a string specifying the trace queue name. This name can be determined by executing xp_trace_enumqueuedefname and must be a shared trace queue definition.
autostart_value
Is a Boolean value that tells Microsoft® SQL Server™ whether the specified trace queue should be automatically started on the next server restart (1) or not (0).
Return Code Values

0 (success) or >1 (failure)

Result Sets

xp_trace_setqueueautostart returns this message:

The command(s) completed successfully.

Remarks

Only shared queue definitions can be autostarted.

Permissions

Execute permissions for xp_trace_setqueueautostart default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example configures the London Events trace queue for autostart.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_savequeuedefinition @queue_handle,

    'London Events',

    1

EXEC xp_trace_setqueueautostart 'London Events',

    1

See Also
xp_trace_addnewqueue | xp_trace_loadqueuedefinition
xp_trace_deletequeuedefinition | xp_trace_pausequeue
xp_trace_destroyqueue | xp_trace_restartqueue
xp_trace_enumqueuedefname | xp_trace_savequeuedefinition
xp_trace_enumqueuehandles | System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_getqueueautostart |


xp_trace_setqueuecreateinfo

Specifies the trace queue properties to modify.

Syntax

xp_trace_setqueuecreateinfo {queue_handle, max_items, timeout,
thread_boost, thread_reduce, event_class}

Arguments
queue_handle
Is an integer representing the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
max_items
Is an integer representing the maximum number of items to be buffered or stored in the trace queue. The recommended value is 1000, the minimum is 1, and the maximum is 20000.
timeout
Is an integer representing the time-out value in seconds for the trace queue. The default value is 5, the minimum is 1, and the maximum is 10.
thread_boost
Is an integer representing the percentage of items in the trace queue that will cause the trace queue consumer to receive a boost in priority and increases the priority setting for the specified application thread. The default percentage is 95, the minimum is 1, and the maximum is 100. thread_reduce cannot be greater than thread_boost.
thread_reduce
Is an integer representing the percentage of items in the trace queue that will cause the trace queue consumer to receive a reduction in priority and decreases the priority setting for the specified application thread. The default percentage is 90, the minimum is 0, and the maximum is 99. thread_reduce cannot be greater than thread_boost.
event_class
Is an integer representing the class of events to trace. If event_class is not specified, all event classes are returned, indicating whether they are being traced for the given queue_handle. 0 specifies all event classes. Execute xp_trace_geteventnames to see this list.
Return Code Values

0 (success) or >1 (failure)

Result Sets

xp_trace_setqueuecreateinfo returns this message:

The command(s) completed successfully.

Permissions

Execute permissions for xp_trace_setqueuecreateinfo default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example modifies a previously created trace queue to include all columns in the output.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_setqueuecreateinfo @queue_handle,

    12500,

    10,

    35,

    10,

    0

See Also
xp_trace_addnewqueue | System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_getqueueproperties |


xp_trace_setqueuedestination

Specifies the trace queue destination filter, or the destination for the events specified. Microsoft® SQL Server™ captures the required information, configured by executing xp_trace_seteventclassrequired, and sends the captured information to the specified destination.

Syntax

xp_trace_setqueuedestination
{
queue_handle, destination, value
{[, 'server'] [, 'object'] }
}

Arguments
queue_handle
Is an integer that represents the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
destination
Is an integer that indicates the destination for the trace queue data. destination can be one of these values.

Value | Description
2 | To file
3 | To application log
4 | To table
5 | To forwarded server

If multiple destinations are required, xp_trace_setqueuedestination can be called multiple times. Here are some guidelines for working with destinations:

  • If sending to a table, be sure to set the application parameter of xp_trace_generate_event; otherwise, no data is added to the destination table.
  • If a new type value is specified (for example, To table was previously chosen and the most recently executed value for xp_trace_setqueuedestination is now To file), trace queue information is sent to both destinations.
  • If type was previously To file and a new file name is specified, the new file is used as the destination.
  • A maximum of one file name and one table can be specified as destinations for any one trace queue.
  • If type is To file and subsequently changed To table, xp_trace_
    setqueuedestination     must be called twice: the first to turn off the file destination, and the second to turn on the table destination.
  • There is a maximum number of one type of each destination type, and a maximim of four total destinations for a trace queue.
value
Is whether the destination is enabled (1) or not (0).
'server'
Is the name of the registered server to which the appropriate trace queue information is sent. server is string. If destination is forwarding (5) or application log (3), this parameter is the name of the server for which events should be forwarded, or the server application log for which to send trace queue information.
'object'
Is the name of the file (if destination is 2) or table (if destination is 4) for which to send trace queue information. object is string, and can be an existing table or file (depending on destination), or it can be nonexisting. If object does not exist, SQL Server creates it.

Note Files created by xp_trace_setqueuedestination have the trace file format. To see a trace file from the SQL Server Profiler graphical interface, open the file as a trace file rather than as an SQL script.

Return Code Values

0 (success) or >1 (failure)

Result Sets

xp_trace_setqueuedestination returns this message:

The command(s) completed successfully.

Remarks

Assume there are two servers: S1 and S2. If a client (named client) writes to a table on server S2 from server S1, server S2 sees the security context of server S1. In future releases of Microsoft Windows NT®, server S2 will see the security context of the client rather than of server S1.

Forwarding is a process that involves two or more servers and allows traced events from one or more servers to be forwarded to a designated main SQL Server. Before enabling forwarding, the trace queue must be created on the originating computer. Then, forwarding (by using destination) can be enabled. In addition, the required data must include the server name.

All events captured by the main, managing SQL Server get compiled into one master list of events, which is prefaced by the originating server name. This compiled event list is useful for minimizing storage space because there is only one file to store rather than two or more (each server, without forwarding, stores its own event file). Forwarding can also assist in load balancing and central server administration because one central server can be monitored rather than many individual servers.

Here are some guidelines for using forwarding:

· Each server can only forward to one other server once.

· No recursion is possible.

· Only events that were created by the originating server can be forwarded. Events forwarded to a server cannot be forwarded again.

· With three servers, any one of the servers can see what events and data each of the other servers is capturing.

Permissions

Execute permissions for xp_trace_setqueuedestination default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example sends the trace queue information to both a file and a table.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,
    5,
    95,
    90,
    @column_value,
    @queue_handle OUTPUT

EXEC xp_trace_setqueuedestination @queue_handle,
    2,
    0,
    NULL,
    'c:\myfile.txt'

EXEC xp_trace_setqueuedestination @queue_handle,
    4,
    0,
    'SEATTLE2',
    'mytable'

See Also
xp_trace_addnewqueue | xp_trace_getqueueproperties
xp_trace_enumqueuehandles | xp_trace_startconsumer
xp_trace_getqueuedestination | System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_setreadfilter

Specifies the read filter, or the minimum and maximum number of logical read operations to capture for the events specified. Microsoft® SQL Server™ captures the required information, configured by executing xp_trace_seteventclassrequired, for all events with a read value greater than the minimum read value, if any, and less than the maximum read value, if any.

Syntax

xp_trace_setreadfilter {queue_handle, minimum_read, maximum_read}

Arguments
queue_handle
Is an integer representing the handle for the trace queue. queue_handle is used to reference the trace queue event placed in an output parameter by xp_trace_addnewqueue.
minimum_read
Is an integer specifying the minimum cumulative process reads for which to trace. There is no default value. If 0, there are no minimum restrictions. The maximum value is 4294967295.
maximum_read
Is an integer specifying the maximum cumulative process reads for which to trace. There is no default value. If 0, there are no maximum restrictions. The maximum value is 4294967295.
Return Code Values

0 (success) or >1 (failure)

Result Sets

xp_trace_setreadfilter returns this message:

The command(s) completed successfully.

Permissions

Execute permissions for xp_trace_setreadfilter default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example configures the read filter value information for the trace queue. A minimum read operation value of 250 is specified, and the maximum number of read operations is 5000.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_setreadfilter @queue_handle,

    250,

    5000

See Also
xp_trace_addnewqueue | xp_trace_getreadfilter
xp_trace_enumqueuehandles | System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_getqueueproperties |


xp_trace_setserverfilter

Specifies the Microsoft® SQL Server™ name filter, or the SQL Server names to include or exclude for the events specified. SQL Server captures the required information, configured by executing xp_trace_seteventclassrequired, for the included server names, if any, and does not capture the required information for the excluded server names, if any. Any SQL Server name can be specified.

Syntax

xp_trace_setserverfilter {queue_handle, 'include_servers',
'exclude_servers'}

Arguments
queue_handle
Is an integer representing the handle for the trace queue. queue_handle is used to reference the trace queue and placed in an output parameter by xp_trace_addnewqueue.
'include_servers'
Is a string value representing the SQL Server name include filter. The server name include filter indicates the SQL Servers, separated by semicolons (;), that should be considered when capturing data previously determined by sp_seteventclassrequired. The % wildcard character can be used in specifying the SQL Servers to include in the trace. If NULL is passed, there are no restrictions on servers to include for the specified event classes.
'exclude_servers'
Is a string value representing the SQL Server name exclude filter. The server name exclude filter indicates the SQL Servers, separated by semicolons (;), that should not be considered when capturing data previously determined by sp_seteventclassrequired. The % wildcard character can be used in specifying the SQL Servers to exclude in the trace. If NULL is passed, there are no excluded servers for the specified event classes.
Return Code Values

0 (success) or >1 (failure)

Result Sets

xp_trace_setserverfilter returns this message:

The command(s) completed successfully.

Remarks

Generate the event class list by executing xp_trace_geteventnames.

When you specify one or more SQL Server names to include, all other server names are excluded.

Permissions

Execute permissions for xp_trace_setserverfilter default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example configures the server filter value information for the trace queue. Servers included are those with LONDON in the server name, and servers excluded are those with SEATTLE in the server name.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_setserverfilter @queue_handle,

    'LONDON%',

    'SEATTLE%'

See Also
xp_trace_addnewqueue | xp_trace_getserverfilter
xp_trace_enumqueuehandles | System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_getqueueproperties |


xp_trace_setseverityfilter

Specifies the severity filter, or the minimum and maximum event severity levels to capture for the events specified. Microsoft® SQL Server™ captures the required information, configured by executing xp_trace_seteventclassrequired, for all events with a severity level greater than the minimum severity value, if any, and less than the maximum severity level, if any.

Syntax

xp_trace_setseverityfilter {queue_handle, minimum_severity,
maximum_severity}

Arguments
queue_handle
Is an integer representing the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
minimum_severity
Is an integer specifying the minimum severity for which to trace. There is no default value. If 0, there are no minimum restrictions. The maximum value is 4294967295.

Note Obtain severity levels from the sysmessages system table.

maximum_severity
Is an integer specifying the maximum severity for which to trace. There is no default value. If 0, there are no maximum restrictions. The maximum value is 4294967295.
Return Code Values

0 (success) or >1 (failure)

Result Sets

xp_trace_setseverityfilter returns this message:

The command(s) completed successfully.

Permissions

Execute permissions for xp_trace_setseverityfilter default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example configures the severity filter value information for trace queue. A minimum severity level of 14 is specified, and a maximum severity level of 25 is specified.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_setseverityfilter @queue_handle,

    14,

    25

See Also
xp_trace_addnewqueue | xp_trace_getseverityfilter
xp_trace_enumqueuehandles | System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_getqueueproperties |


xp_trace_setspidfilter

Specifies the system process identification number (SPID) filter to include for the events specified. Microsoft® SQL Server™ captures the required information, configured by executing xp_trace_seteventclassrequired, for the specified SPID.

Syntax

xp_trace_setspidfilter {queue_handle, spid}

Arguments
queue_handle
Is an integer representing the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
spid
Is an integer specifying the SPID for the events to capture. Execute sp_who to determine valid SPIDs.
Return Code Values

0 (success) or >1 (failure)

Result Sets

xp_trace_setspidfilter returns this message:

The command(s) completed successfully.

Permissions

Execute permissions for xp_trace_setspidfilter default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example configures the SPID filter value information for the trace queue. A SPID of 41 is supplied.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_setspidfilter @queue_handle,

    41

See Also
sp_who | xp_trace_getqueueproperties
xp_trace_addnewqueue | xp_trace_getspidfilter
xp_trace_enumqueuehandles | System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_setsysobjectsfilter

Specifies the system objects filter, or if system objects are to be captured or not, for the events specified.

Syntax

xp_trace_setsysobjectsfilter {queue_handle, sysobjects_value }

Arguments
queue_handle
Is an integer that represents the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
sysobjects_value
Is an integer that indicates whether system objects should be captured (0) or not (1).
Return Code Values

0 (success) or >1 (failure)

Result Sets

xp_trace_setsysobjectsfilter returns this message:

The command(s) completed successfully.

Permissions

Execute permissions for xp_trace_setsysobjectsfilter default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example enables the capturing of system objects by setting sysobjects_value to 1.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_setsysobjectsfilter @queue_handle, 1

See Also
xp_trace_addnewqueue | xp_trace_getsysobjectsfilter
xp_trace_enumqueuehandles | System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_getqueueproperties |


xp_trace_settextfilter

Specifies the text filter, or the text to include or exclude for the events specified. Microsoft® SQL Server™ captures the required information, configured by executing xp_trace_seteventclassrequired, for the included text, if any, and does not capture the required information for the excluded text, if any.

Syntax

xp_trace_settextfilter {queue_handle, 'include_text', exclude_text'}

Arguments
queue_handle
Is an integer that represents the handle for the trace queue. queue_handle is used to reference the trace queue and placed in an output parameter by xp_trace_addnewqueue.
'include_text'
Is a string value that represents the text include filter. The text include filter indicates the text, separated by semicolons (;), that should be considered when capturing data previously determined by sp_seteventclassrequired. The % wildcard character can be used in specifying the text to include in the trace. If NULL, there is no restrictions on text to include for the specified event classes.
'exclude_text'
Is a string value that represents the text exclude filter. The text exclude filter indicates the text, separated by semicolons (;), that should not be considered when capturing data previously determined by sp_seteventclassrequired. The % wildcard character can be used in specifying the text to exclude in the trace. If NULL, there is no excluded text for the specified event classes.

Note Generate the event class list by executing xp_trace_geteventnames.

Return Code Values

0 (success) or >1 (failure)

Result Sets

xp_trace_settextfilter returns this message:

The command(s) completed successfully.

Remarks

When you specify one or more text strings to include, all other text strings are excluded.

Permissions

Execute permissions for xp_trace_settextfilter default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example configures the text filter value information for the trace queue. Events included are those with UPDATE in them.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_settextfilter @queue_handle,

    'UPDATE%',

    NULL

See Also
xp_trace_addnewqueue | xp_trace_gettextfilter
xp_trace_enumqueuehandles | System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_getqueueproperties |


xp_trace_setuserfilter

Specifies the Microsoft® SQL Server™ username filter, or the SQL Server usernames to include or exclude for the events specified. SQL Server captures the required information, configured by executing xp_trace_seteventclassrequired, for the included usernames, if any, and does not capture the required information for the excluded usernames, if any.

Syntax

xp_trace_setuserfilter {queue_handle, 'include_users', 'exclude_users'}

Arguments
queue_handle
Is an integer representing the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
'include_users'
Is a string value representing the username include filter. The username include filter indicates the usernames, separated by semicolons (;), that should be considered when capturing data previously determined by sp_seteventclassrequired. The % wildcard character can be used in specifying the usernames to include in the trace. If NULL, there are no restrictions on usernames to include for the specified event classes.

Note SQL Server usernames are those usernames used with SQL Server Authentication rather than Windows NT Authentication. Usernames can be obtained from the syslogins system table.

'exclude_users'
Is a string value representing the username exclude filter. The username exclude filter indicates the usernames, separated by semicolons (;), that should not be considered when capturing data previously determined by sp_seteventclassrequired. The % wildcard character can be used in specifying the usernames to exclude in the trace. If NULL, there are no excluded usernames for the specified event classes.
Return Code Values

0 (success) or >1 (failure)

Result Sets

xp_trace_setuserfilter returns this message:

The command(s) completed successfully.

Remarks

When you specify one or more SQL Server usernames to include, all other SQL Server usernames are excluded.

Permissions

Execute permissions for xp_trace_setuserfilter default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example configures the user filter value information for trace queue. All events for user janetl are traced and no users are excluded.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_setuserfilter @queue_handle,

    'janetl%',

    NULL

See Also
xp_trace_addnewqueue | xp_trace_getqueueproperties
xp_trace_enumqueuehandles | System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_getuserfilter |


xp_trace_setwritefilter

Specifies the write filter, or the minimum and maximum write operations to capture for the events specified. Microsoft® SQL Server™ captures the required information, configured by executing xp_trace_seteventclassrequired, for all events with a number of write operations greater than the minimum, if any, and less than the maximum, if any.

Syntax

xp_trace_setwritefilter {queue_handle, minimum_write,
maximum_write}

Arguments
queue_handle
Is an integer representing the handle for the trace queue. queue_handle is used to reference the trace queue and is placed in an output parameter by xp_trace_addnewqueue.
minimum_write
Is an integer specifying the minimum cumulative process writes for which to trace. There is no default value. If 0, there are no minimum restrictions. The maximum value is 4294967295.
maximum_write
Is an integer specifying the maximum cumulative process writes for which to trace. There is no default value. If 0, there are no maximum restrictions. The maximum value is 4294967295.
Return Code Values

0 (success) or >1 (failure)

Result Sets

xp_trace_setwritefilter returns this message:

The command(s) completed successfully.

Permissions

Execute permissions for xp_trace_setwritefilter default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example configures the write filter value information for trace queue. A minimum write value of 200 is specified and the maximum write operations value is 4750.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_setwritefilter @queue_handle,

    200,

    4750

See Also
xp_trace_addnewqueue | xp_trace_getwritefilter
xp_trace_enumqueuehandles | System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_getqueueproperties |


xp_trace_startconsumer

Starts the specified consumer (set with xp_trace_setqueuedestination) that consumes events from the queue and sends it to the destination specified in the queue definition.

Syntax

xp_trace_startconsumer {queue_handle}

Arguments
queue_handle
Is an integer that represents the handle for the trace queue. queue_handle is used to reference the trace queue and placed in an output parameter by xp_trace_addnewqueue.
Return Code Values

0 (success) or >1 (failure)

Result Sets

xp_trace_startconsumer returns this message:

The command(s) completed successfully.

Permissions

Execute permissions for xp_trace_startconsumer default to members of the sysadmin fixed server role but can be granted to other users.

Examples

This example starts the consumer for the trace queue.

USE master

DECLARE @queue_handle int, @column_value int

SET @column_value = 16|32|8192|128|512

EXEC xp_trace_addnewqueue 1000,

    5,

    95,

    90,

    @column_value,

    @queue_handle OUTPUT

EXEC xp_trace_setqueuedestination @queue_handle,
    2,
    1,
    NULL,
    'c:\temp\demo.trc'

EXEC xp_trace_startconsumer @queue_handle

See Also
xp_trace_addnewqueue | System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_setqueuedestination |


System Tables

The information used by Microsoft® SQL Server™ and its components are stored in special tables known as system tables.

Note System tables should not be altered directly by any user. For example, do not attempt to modify system tables with DELETE, UPDATE, or INSERT statements, or user-defined triggers.

Applications should not be written to query the system tables directly. Applications should instead use any of these components to retrieve information stored in the system tables:

  • Information schema views
  • System stored procedures
  • Transact-SQL statements and functions
  • SQL-DMO
  • Database application programming interfaces (API) catalog functions

These components constitute a published API for obtaining system information from SQL Server. Microsoft maintains the compatibility of these components from release to release. The format of the system tables is dependent upon the internal architecture of SQL Server and may change from release to release. Therefore, applications that directly access the system tables may have to be changed before they can access a later version of SQL Server.

System Tables in the master Database Only

These tables store server-level system information.

sysaltfiles | sysdevices | sysoledbusers
syscharsets | syslanguages | sysperfinfo
sysconfigures | syslockinfo | sysprocesses
syscurconfigs | syslogins | sysremotelogins
sysdatabases | sysmessages | sysservers

System Tables in Every Database

These tables store database-level system information for each database.

sysallocations | sysfiles | sysobjects
syscolumns | sysforeignkeys | syspermissions
syscomments | sysfulltextcatalogs | sysprotects
sysconstraints | sysindexes | sysreferences
sysdepends | sysindexkeys | systypes
sysfilegroups | sysmembers | sysusers

SQL Server Agent Tables in the msdb Database

These tables store information used by SQL Server Agent.

sysalerts | sysjobschedules | systargetservergroupmembers
syscategories | sysjobservers | systargetservergroups
sysdownloadlist | sysjobsteps | systargetservers
sysjobhistory | sysnotifications | systaskids
sysjobs | sysoperators |

Tables in the msdb Database

These tables store information used by database backup and restore operations.

backupfile | backupset | restorefilegroup
backupmediafamily | restorefile | restorehistory
backupmediaset |  |

Tables Used to Store Replication Information

These tables are used by replication and stored in the master database.

sysarticles | syspublications | sysservers
sysdatabases | sysreplicationalerts | syssubscriptions
sysobjects |  |

These tables are used by replication and stored in the distribution database.

MSagent_parameters | MSmerge_agents | Msrepl_originators
MSagent_profiles | MSmerge_history | MSrepl_transactions
MSarticles | MSmerge_subscriptions | MSrepl_version
MSdistpublishers | MSpublication_access | MSsnapshot_agents
MSdistributiondbs | Mspublications | MSsnapshot_history
MSdistribution_agents | Mspublisher_databases | MSsubscriber_info
MSdistribution_history | MSreplication_objects | MSsubscriber_schedule
MSdistributor | MSreplication_subscriptions | MSsubscriptions
MSlogreader_agents | MSrepl_commands | MSsubscription_properties
MSlogreader_history | MSrepl_errors |

These tables are used by replication and stored in the user’s database.

MSmerge_contents | MSmerge_subscriptions | sysmergepublications
MSmerge_delete_conflicts | MSmerge_tombstone | sysmergeschemachange
MSmerge_genhistory | sysarticleupdates | sysmergesubscriptions
MSmerge_replinfo | sysmergearticles | sysmergesubsetfilters


backupfile

Contains one row for each data or log file that is backed up. This table is stored in the msdb database.

Column name | Data type | Description
backup_set_id | int NOT NULL REFERENCES backupset(backup_ set_id) | Unique identification number of the file containing the backup set.
first_family_number | tinyint NULL | Family number of the first media containing this backup file.
first_media_number | smallint NULL | Media number of the first media containing this backup file.
filegroup_name | nvarchar(128) NULL | Name of the filegroup containing the database (data or log) file that was backed up.
page_size | int NULL | Size of the page, in bytes.
file_number | numeric(10,0) NOT NULL | Unique file identification number (FILE_ID).
backed_up_page_count | numeric(10,0) NULL | Number of pages backed up.
file_type | char(1) NULL | File backed up. Can be either D for data or L for log.
source_file_block_size | numeric(10,0) NULL | Device that the original data or log file resided on when it was backed up.
file_size | numeric(20,0) NULL | Length of the file that is backed up, in bytes.
logical_name | nvarchar(128) NULL | Logical name of the file that is backed up.
physical_drive | varchar(260) NULL | Physical drive or partition name.
physical_name | varchar(260) NULL | Remainder of the physical (operating system) file name.


backupmediafamily

Contains one row for each media family. This table is stored in the msdb database.

Column name | Data type | Description
media_set_id | int NOT NULL REFERENCES backupmediaset (media_set_id) | Unique identification number that identifies the media set of which this family is a member.
family_sequence_ number | tinyint NOT NULL | Position of this media family in the media set.
media_family_id | uniqueidentifier NULL | Unique identification number that identifies the media family.
media_count | int NULL | Number of media in the media family.
logical_device_name | nvarchar(128) NULL | Name of the backup device in sysdevices. logical_device_name is NULL if this is a temporary backup device (as opposed to a permanent backup device that exists in sysdevices).
physical_device_ name | nvarchar(260) NULL | Physical name of the backup device.
device_type | tinyint NULL | Type of backup device. Can be: Disk 2 = Temporary 102 = Permanent Tape 5 = Temporary 105 = Permanent Pipe 6 = Temporary 106 = Permanent All permanent device names and device numbers can be found in sysdevices.
physical_block_size | int NULL | Physical block size that was used to write the media family.


backupmediaset

Contains one row for each backup media set. This table is stored in the msdb database.

Column name | Data type | Description
media_set_id | int IDENTITY PRIMARY KEY | Unique media set identification number.
media_uuid | uniqueidentifier NULL | Number of media in the media set. If only one media family in the backup set, then this column is NULL (media_family_count is 1).
media_family_count | tinyint NULL | Number of media families in the media set.
name | nvarchar(128) NULL | Name of the media set. For more information, see MEDIANAME and MEDIADESCRIPTION in BACKUP.
description | nvarchar(255) NULL | Textual description of the media set. For more information, see MEDIANAME and MEDIADESCRIPTION in BACKUP.
software_name | nvarchar(128) NULL | Name of the backup software that wrote the media label.
software_vendor_id | int NULL | Identification number of the software vendor that wrote the backup media label. The Microsoft® SQL Server™ value for this column is hexadecimal 0x1200.
MTF_major_version | tinyint NULL | Major version number of Microsoft Tape Format used to generate this media set.


backupset

Contains a row for each backup set. This table is stored in the msdb database.

Column name | Data type | Description
backup_set_id | int NOT NULL IDENTITY PRIMARY KEY | Unique backup set identification number that identifies the backup set.
backup_set_uuid | uniqueidentifier NOT NULL | Unique backup set identification number that identifies the backup set on the media.
media_set_id | int NOT NULL REFERENCES backupmediaset (media_set_id) | Unique media set identification number that identifies the media set containing the backup set.
first_family_number | tinyint NULL | Family number of the media where the backup set starts.
first_media_number | smallint NULL | Media number of the media where the backup set starts.
last_family_number | tinyint NULL | Family number of the media where the backup set ends.
last_media_number | smallint NULL | Media number of the media where the backup set ends.
catalog_family_ number | tinyint NULL | Family number of the media containing the start of the backup set directory.
catalog_media_ number | smallint NULL | Media number of the media containing the start of the backup set directory.
position | int NULL | Backup set position used in the restore operation to locate the appropriate backup set and files. For more information, see FILE in BACKUP.
expiration_date | datetime NULL | Date and time the backup set expires.
software_vendor_id | int NULL | Identification number of the software vendor writing the backup media header.
name | nvarchar(128) NULL | Name of the backup set.
description | nvarchar(255) NULL | Description of the backup set.
user_name | nvarchar(128) NULL | Name of the user performing the backup operation.
software_major_ version | tinyint NULL | Microsoft® SQL Server™ major version number.
software_minor_ version | tinyint NULL | SQL Server minor version number.
software_build_ version | smallint NULL | SQL Server build number.
time_zone | smallint NULL | Difference between local time (where the backup operation is taking place) and Universal Coordinated Time (UCT) in 15-minute intervals. Values can be -48 through +48, inclusive. A value of 127 indicates unknown. For example, -20 is Eastern Standard Time (EST) or 5 hours after UCT.
mtf_minor_version | tinyint NULL | Microsoft Tape Format minor version number.
first_lsn | numeric(25,0) NULL | Log sequence number of the first or oldest log record in the backup set.
last_lsn | numeric(25,0) NULL | Log sequence number of the last or newest log record in the backup set.
checkpoint_lsn | numeric(25,0) NULL | Log sequence number of the log record where recovery must start.
database_backup_lsn | numeric(25,0) NULL | Log sequence number of the most recent full database backup.
database_creation_ date | datetime NULL | Date and time the database was originally created.
backup_start_date | datetime NULL | Date and time the backup operation started.
backup_finish_date | datetime NULL | Date and time the backup operation finished.
type | char(1) NULL | Backup type. Can be: D = Database I = Database Differential L = Log F = File or Filegroup
sort_order | smallint NULL | Sort order of the server performing the backup operation.
code_page | smallint NULL | Code page of the server performing the backup operation.
compatibility_level | tinyint NULL | Compatibility level setting for the database. Can be: 60 = SQL Server version 6.0 65 = SQL Server 6.5 70 = SQL Server 7.0 For more information about compatibility levels, see sp_dbcmptlevel.
database_version | int NULL | Database version number.
backup_size | numeric(20,0) NULL | Size of the backup set, in bytes.
database_name | nvarchar(128) NULL | Name of the database involved in the backup operation.
server_name | nvarchar(128) NULL | Name of the server running the SQL Server backup operation.
machine_name | nvarchar(128) NULL | Name of the computer running SQL Server.


MSagent_parameters

Contains parameters associated with an agent profile. The parameter names are the same as those supported by the agent. This table is stored in the distribution database.

Column name | Data type | Description
profile_id | int | Configuration ID from the MSagent_profiles table
parameter_name | sysname | Name of the parameter
value | nvarchar(255) | Value of the parameter


MSagent_profiles

Contains one row for each defined replication agent profile. This table is stored in the distribution database.

Column name | Data type | Description
profile_id | int | Configuration ID from the MSagent_profiles table.
profile_name | sysname | Unique for agent type.
agent_type | int | Type of agent: 1 = Snapshot Agent 2 = Log Reader Agent 3 = Distribution Agent 4 = Merge Agent
type | int | Type of profile: 0 = System 1 = Custom
description | varchar(3000) | Description of the configuration.
def_profile | bit | Specifies whether this configuration is the default for this agent type.


MSarticles

Contains one row for each article being replicated by a Publisher. This table is stored in the distribution database.

Column name | Data type | Description
publisher_id | smallint | ID of the Publisher
publisher_db | sysname | Name of the Publisher database
publication_id | int | ID of the publication
article | sysname | Name of the article
article_id | int | ID of the article
source_object | sysname | Name of the source object from which to add the article
description | nvarchar(255) | Description of the article


MSdistpublishers

Contains one row for each remote Publisher supported by the local Distributor. This table is stored in the distribution database.

Column name | Data type | Description
name | sysname | Name of the Publisher Distributor.
distribution_db | sysname | Name of the distribution database.
working_directory | nvarchar(255) | Name of the working directory used to store data and schema files for the publication.
security_mode | int | Security mode implemented at the Distributor: 0 = SQL Server Authentication 1 = Windows NT Authentication
login | sysname | Login ID for SQL Server Authentication.
password | sysname | Password for SQL Server Authentication.
active | bit | Indicates whether the local Distributor is in use by the remote Publisher.
distributor_login | sysname | Distributor login.


MSdistributiondbs

Contains one row for each distribution database defined on the local Distributor. This table is stored in the replicated database.

Column name | Data type | Description
name | sysname | Name of the distribution database.
min_distretention | int | Minimum retention period, in hours, before transactions are deleted.
max_distretention | int | Maximum retention period, in hours, before transactions are deleted.
history_retention | int | Number of hours to retain history.


MSdistribution_agents

Contains one row for each Distribution Agent running at the local Distributor. This table is stored in the distribution database.

Column name | Data type | Description
id | int | ID of the Distribution Agent.
name | nvarchar(100) | Name of the Distribution Agent.
publisher_database_id | int | ID of the Publisher database.
publisher_db | sysname | Name of the Publisher database.
publication | sysname | Name of the publication.
subscriber_id | smallint | ID of the Subscriber.
subscriber_db | sysname | Name of the subscription database.
subscription_type | int | Type of subscription: 0 = Push 1 = Pull 2 = Anonymous
local_job | bit | Indicates whether there is a SQL Server Agent job on the local Distributor.
job_id | binary(16) | Job identification number.
subscription_guid | binary(16) | ID of the subscriptions of this agent.
profile_id | int | Configuration ID from the MSagent_profiles table.
anonymous_subid | uniqueidentifier | ID of an anonymous agent.
subscriber_name | sysname | Name of the Subscriber.
virtual_agent_id | int | ID of the virtual agent.
anonymous_agent_id | int | ID of the anonymous agent.


MSdistribution_history

Contains history rows for the Distribution Agents associated with the local Distributor. This table is stored in the distribution database.

Column name | Data type | Description
agent_id | int | ID of the Distribution Agent.
runstatus | int | Running status: 0 = Start 2 = Succeed 3 = In progress 4 = Idle 5 = Retry 6 = Fail
start_time | datetime | Time to begin execution of the job.
time | datetime | Time the message is logged.
duration | int | Duration, in seconds, of the message session.
comments | nvarchar(255) | Message text.
xact_seqno | varbinary(16) | Last processed transaction sequence number.
delivered_transactions | int | Total number of transactions delivered in the session.
delivered_commands | int | Total number of commands delivered in the session.
average_commands | int | Average number of commands delivered in the session.
delivery_rate | float | Average delivered commands per second.
delivery_latency | int | Latency between the command entering the distribution database and being applied to the Subscriber.
total_delivered_commands | int | Total number of commands delivered since the subscription was created.
error_id | int | ID of the error in the MSrepl_error system table.
timestamp | timestamp | Timestamp column of this table.


MSdistributor

Contains the Distributor properties. This table is stored in the replicated database.

Column name | Data type | Description
property | sysname | Name of the property
value | nvarchar(3000) | Value of the property


MSlogreader_agents

Contains one row for each Log Reader Agent running at the local Distributor. This table is stored in the distribution database.

Column name | Data type | Description
id | int | ID of the Log Reader Agent.
name | nvarchar(100) | Name of the Log Reader Agent.
publisher_id | smallint | ID of the Publisher.
publisher_db | sysname | Name of the Publisher database.
publication | sysname | Name of the publication.
local_job | bit | Indicates whether there is a SQL Server Agent job on the local Distributor.
job_id | binary(16) | Job identification number.
profile_id | int | Configuration ID from the MSagent_profiles table.


MSlogreader_history

Contains history rows for the Log Reader Agents associated with the local Distributor. This table is stored in the distribution database.

Column name | Data type | Description
agent_id | int | ID of the Log Reader Agent.
runstatus | int | Running status: 0 = Start 2 = Succeed 3 = In progress 4 = Idle 5 = Retry 6 = Fail
start_time | datetime | Time to begin execution of the job.
time | datetime | Time the message is logged.
duration | int | Duration, in seconds, of the message session.
comments | nvarchar(255) | Message text.
xact_seqno | varbinary(16) | Last processed transaction sequence number.
delivery_time | int | Time first transaction is delivered.
delivered_transactions | int | Total number of transactions delivered in the session.
delivered_commands | int | Total number of commands delivered in the session.
average_commands | int | Average number of commands delivered in the session.
delivery_rate | float | Average delivered commands per second.
delivery_latency | int | Latency between the command entering the distribution database and being applied to the Subscriber.
error_id | int | ID of the error in the MSrepl_error system table.
timestamp | timestamp | Timestamp column of this table.


MSmerge_agents

Contains one row for each Merge Agent running at the Subscriber. This table is stored in the distribution database.

Column name | Data type | Description
id | int | ID of the Merge Agent.
name | nvarchar(100) | Name of the Merge Agent.
publisher_id | smallint | ID of the Publisher.
publisher_db | sysname | Name of the Publisher database.
publication | sysname | Name of the publication.
subscriber_id | smallint | ID of the Subscriber.
subscriber_db | sysname | Name of the subscription database.
local_job | bit | Indicates whether there is a SQL Server Agent job on the local Distributor.
job_id | binary(16) | Job identification number.
profile_id | int | Configuration ID from the MSagent_profiles table.
anonymous_subid | uniqueidentifier | ID of an anonymous agent.
subscriber_name | sysname | Name of the Subscriber.


MSmerge_contents

Contains one row for each row modified in the current database since it was published. This table is used by the default priority-based conflict resolver to determine the rows that have changed. This table is stored in the published database.

Column name | Data type | Description
tablenick | int | Nickname of the published table.
rowguid | uniqueidentifier | Row identifier from the published table.
generation | int | Generation of the row identified by the tablenick and rowguid.
partchangegen | int | Indicates that the data change caused a change in the partition: 0 = No change 1= Change
joinchangegen | int | Indicates that the data change caused a change in the join filter: 0 = No change 1= Change
lineage | varbinary(249) | Subscriber nickname, version number pairs that are used to maintain a history of changes to this row.
colvl | varbinary(2048) | Column version information.


MSmerge_delete_conflicts

Contains tombstone information for rows that were deleted and subsequently had the delete undone because it conflicted with an update performed at another replica. This table is stored in the database used for conflict logging, usually the publishing database but can be the subscribing database if there is decentralized conflict logging.

Column name | Data type | Description
tablenick | int | Nickname of the table.
rowguid | uniqueidentifier | Row identifier for the deleted row.
origin_datasource | varchar(255) | Indicates the version of the record that was deleted and the updates that were known when it was deleted. This allows rules for consistent resolution of a conflict when one Subscriber updates a row while it is being deleted at another Subscriber.
conflict_type | int | Type of conflict: 1 = Update conflict 2 = Upload error 3 = Download error 4 = Update or delete conflict 5 = Column update conflict
reason_code | int | Error code. May be context-sensitive-based on conflict_type
reason_text | nvarchar(720) | Description of the error code.
pubid | uniqueidentifier | Publication identifier.


MSmerge_genhistory

Contains one row for each generation that a Subscriber knows about (within the retention period). It is used to avoid sending common generations during exchanges and to resynchronize Subscribers that are restored from backups. This table is stored in the distribution database.

Column name | Data type | Description
guidsrc | uniqueidentifier | Global identifier of the changes identified by generation at the Subscriber.
guidlocal | uniqueidentifier | Local identifier of the changes identified by generation at the Subscriber.
pubid | uniqueidentifier | Publication identifier.
generation | int | Generation value.
art_nick | int | Nickname for the article.
nicknames | varbinary(255) | A list of nicknames of other Subscribers that are known to already have this generation. Used to avoid sending a generation to a Subscriber that has already seen those changes. Nicknames in the nicknames list are maintained in sorted order to make searches more efficient. If there are more nicknames than can fit in this field, they will not benefit from this optimization.
coldate | datetime | Date when current generation is added to the table.


MSmerge_history

Contains history rows for previous updates to Subscriber. This table is stored in the distribution database.

Column name | Data type | Description
agent_id | int | ID of the agent.
runstatus | int | Running status: 0 = Start 2 = Succeed 3 = In progress 4 = Idle 5 = Retry 6 = Fail
start_time | datetime | Time execution of the job began.
time | datetime | Time of this history entry.
duration | int | Cumulative duration, in seconds, of this session.
comments | nvarchar(255) | Message text.
delivery_time | int | Number of seconds it took to apply a batch of changes.
delivery_rate | float | Average delivered commands per second.
publisher_insertcount | int | Number of inserts at the Publisher.
publisher_updatecount | int | Number of updates at the Publisher.
publisher_deletecount | int | Number of deletes at the Publisher.
publisher_conflictcount | int | Number of conflicts at the Publisher.
subscriber_insertcount | int | Number of inserts at the Subscriber.
subscriber_updatecount | int | Number of updates at the Subscriber.
subscriber_deletecount | int | Number of deletes at the Subscriber.
subscriber_conflictcount | int | Number of conflicts at the Subscriber.
error_id | int | ID of an error in the MSrepl_error system table.
timestamp | timestamp | Timestamp column of this table.


MSmerge_replinfo

Contains one row for each replica made from the local server. This table contains the job IDs for the merge tasks and is used in tracking generation information. This table is stored in the published database.

Column name | Data type | Description
repid | uniqueidentifier | Unique ID for the replica.
replnickname | int | Compressed nickname for the replica.
recgen | int | Number of the last generation received.
recguid | uniqueidentifier | Unique ID of the last generation received.
sentgen | int | Number of the last generation sent.
sentguid | uniqueidentifier | Unique ID of the last generation sent.
schemaversion | int | Number of the last schema received.
schemaguid | uniqueidentifier | Unique ID of the last schema received.
merge_jobid | binary(16) | SQL Server Agent ID for this Merge Agent.
snapshot_jobid | binary(16) | Snapshot job ID servicing this publication.


MSmerge_subscriptions

Contains one row for each subscription serviced by the Merge Agent at the Subscriber. This table is stored in the distribution database.

Column name | Data type | Description
publisher_id | smallint | ID of the Publisher.
publisher_db | sysname | Name of the Publisher database.
publication_id | int | ID of the publication.
subscriber_id | smallint | ID of the Subscriber.
subscriber_db | sysname | Name of the subscription database.
subscription_type | int | Type of subscription: 0 = Push 1 = Pull 2 = Anonymous
sync_type | tinyint | Type of synchronization: 1 = Automatic 2 = No sync
status | tinyint | Status of the subscription: 0 = Inactive 1 = Subscribed 2 = Active
subscription_time | datetime | Time the subscription was added.
login_name | sysname | Name used to log in to the Subscriber.


MSmerge_tombstone

Contains information on deleted rows and allows deletes to be propagated to other Subscribers. This table is stored in the published database.

Column name | Data type | Description
rowguid | uniqueidentifier | Row identifier.
tablenick | int | Nickname of the table.
type | tinyint | Type of delete: 1 = User delete 5 = Row no longer belongs to the filtered partition 6 = System delete
lineage | varbinary(255) | Indicates the version of the record that was deleted, and which updates were known when it was deleted. Allows rules for consistent resolution of a conflict when one Subscriber updates a row while it is being deleted at another Subscriber.
generation | int | Is assigned by a generation grouping routine. If a Subscriber requests generation N, then only tombstones with generation >= N or generation == 0 are sent. (RowGeneration == 0 indicates that it was deleted after the generation grouping routine was executed.)
reason | varchar(255) | Text field containing the reason that tombstone was created.


MSpublication_access

Contains a row for each Microsoft® SQL Server™ login that has access to the specific publication or Publisher. This table is stored in the distribution database.

Column name | Data type | Description
publisher_id | smallint | ID of the Publisher
publication_id | int | ID of the publication
login | sysname | Microsoft Windows NT® accounts that exist at both Publisher and Distributor side


MSpublications

Contains one row for each publication that is replicated by a Publisher. This table is stored in the distribution database.

Column name | Data type | Description
publisher_id | smallint | ID of the Publisher.
publisher_db | sysname | Name of the Publisher database.
publication | sysname | Name of the publication.
publication_id | int identity | ID of the publication.
publication_type | int | Type of publication: 0 = Snapshot 1 = Transactional
thirdparty_flag | bit | Indicates whether a publication is a Microsoft® SQL Server™ database: 0 = SQL Server 1 = Data source other than SQL Server
independent_agent | bit | Indicates whether there is a stand-alone Distribution Agent for this publication.
immediate_sync | bit | Indicates whether synchronization files are created or re-created each time the Snapshot Agent runs.
allow_push | bit | Indicates whether push subscriptions can be created for the given publication.
allow_pull | bit | Indicates whether pull subscriptions can be created for the given publication.
allow_anonymous | bit | Indicates whether anonymous subscriptions can be created for the given publication.
description | nvarchar(255) | Description of the publication.
vendor_name | nvarchar(100) | Name of the vendor (if Publisher is not a SQL Server database).


MSpublisher_databases

Contains one row for each Publisher/Publisher database pair serviced by the local Distributor. This table is stored in the distribution database.

Column name | Data type | Description
publisher_id | smallint | ID of the Publisher
publisher_db | sysname | Name of the Publisher database
id | int | ID of the row


MSreplication_objects

Contains one row for each object that is associated with replication in the Subscriber database. This table is stored in the Subscriber database.

Column name | Data type | Description
publisher | sysname | Name of the Publisher
publisher_db | sysname | Name of the Publisher database
publication | sysname | Name of the publication
object_name | sysname | Name of the object
object_type | char(2) | Object type: u = Table t = Trigger


MSreplication_subscriptions

Contains one row of replication information for each Distribution Agent servicing the local Subscriber database. This table is stored in the Subscriber database.

Column name | Data type | Description
publisher | sysname | Name of the Publisher.
publisher_db | sysname | Name of the Publisher database.
publication | sysname | Name of the publication.
independent_agent | bit | Indicates whether there is a stand-alone Distribution Agent for this publication.
subscription_type | int | Type of subscription: 0 = Push 1 = Pull 2 = Anonymous
distribution_agent | nvarchar(100) | Name of the Distribution Agent.
time | smalldatetime | Time of the last update by Distribution Agent.
description | nvarchar(255) | Description of the subscription.
transaction_timestamp | varbinary(16) | Synctran.
update_mode | tinyint | Type of update.
agent_id | binary(16) | ID of the agent.
subscription_guid | binary(16) | Global identifier for the version of the subscription on the publication.
subid | binary(16) | Global identifier for an anonymous subscription.
reinit | int | Default 0.


MSrepl_commands

Contains rows of replicated commands. This table is stored in the distribution database.

Column name | Data type | Description
publisher_database_id | int | ID of the Publisher database.
xact_seqno | varbinary(16) | Transaction sequence number.
type | int | Command type.
article_id | int | ID of the article.
originator_id | int | ID of the originator.
command_id | int | ID of the command.
partial_command | bit | Indicates whether this is a partial command.
command | varbinary(1024) | Command value.


MSrepl_errors

Contains rows with extended replication agent failure information. This table is stored in the distribution database.

Column name | Data type | Description
id | int | ID of the error
time | datetime | Time the error occurred
error_type_id | int | Reserved for future use
source_type_id | int | Error source type ID
source_name | nvarchar(100) | Name of the error source
error_code | sysname | Error code
error_text | ntext | Error message


MSrepl_originators

Contains one row for each updatable Subscriber from which the transaction originated. This table is stored in the distribution database.

Column name | Data type | Description
id | int | ID of the updating Subscriber
publisher_database_id | int | ID of the Publisher database
srvname | sysname | Name of the updating server
dbname | sysname | Name of the updating database


MSrepl_transactions

Contains one row for each replicated transaction. This table is stored in the distribution database.

Column name | Data type | Description
publisher_database_id | int | ID of the Publisher database
xact_id | varbinary(16) | ID of the transaction
xact_seqno | varbinary(16) | Sequence number of the transaction
entry_time | datetime | Time the transaction entered the distribution database


MSrepl_version

Contains one row with the current version of replication installed. This table is stored in the distribution database.

Column name | Data type | Description
major_version | int | Major version number of the distribution database.
minor_version | int | Minor version number of the distribution database.
revision | int | Revision number.
db_existed | bit | Indicates whether the distribution database exists before sp_adddistributiondb is called.


MSsnapshot_agents

Contains one row for each Snapshot Agent associated with the local Distributor. This table is stored in the distribution database.

Column name | Data type | Description
id | int | ID of the Snapshot Agent.
name | nvarchar(100) | Name of the Snapshot Agent.
publisher_id | smallint | ID of the Publisher.
publisher_db | sysname | Name of the Publisher database.
publication | sysname | Name of the publication.
local_job | bit | Indicates whether there is a SQL Server Agent job on the local Distributor.
job_id | binary(16) | Job identification number.
profile_id | int | Configuration ID from the MSagent_profiles table.


MSsnapshot_history

Contains history rows for the Snapshot Agents associated with the local Distributor. This table is stored in the distribution database.

Column name | Data type | Description
agent_id | int | ID of the Snapshot Agent.
runstatus | int | Running status: 0 = Start 2 = Succeed 3 = In progress 4 = Idle 5 = Retry 6 = Fail
start_time | datetime | Time to begin execution of the job.
time | datetime | Time the message is logged.
duration | int | Duration, in seconds, of the message session.
comments | nvarchar(255) | Message text.
delivered_transactions | int | Total number of transactions delivered in the session.
delivered_commands | int | Average delivered commands per second.
delivery_rate | float | Average delivered commands per second.
error_id | int | ID of the error in the MSrepl_error system table.
timestamp | timestamp | Timestamp column of this table.


MSsubscriber_info

Contains one row for each Publisher/Subscriber pair that is being pushed subscriptions from the local Distributor. This table is stored in the distribution database.

Column name | Data type | Description
publisher | sysname | Name of the Publisher
subscriber | sysname | Name of the Subscriber
type | tinyint | Subscriber type: 0 = Microsoft® SQL Server™ Subscriber 1 = ODBC data source
login | sysname | Login for SQL Server Authentication
password | sysname | Password for SQL Server Authentication
description | nvarchar(255) | Description of the Subscriber
security_mode | int | Implemented security mode: 0 = SQL Server Authentication 1 = Windows NT Authentication


MSsubscriber_schedule

Contains default merge and transactional synchronization schedules for each Publisher/Subscriber pair. This table is stored in the distribution database.

Column name | Data type | Description
publisher | sysname | Name of the Publisher.
subscriber | sysname | Name of the Subscriber.
agent_type | smallint | Type of agent: 0 = Distribution Agent 1 = Merge Agent
frequency_type | int | Frequency with which to schedule the Distribution Agent: 1 = One time 2 = On demand 4 = Daily 8 = Weekly 16 = Monthly 32 = Monthly relative 64 = Autostart (default) 124 = Recurring
frequency_interval | int | Value to apply to the frequency set by frequency_type.
frequency_relative_ interval | int | Date of the Distribution Agent: 1 = First (default) 2 = Second 4 = Third 8 = Fourth 16 = Last
frequency_recurrence_ factor | int | Recurrence factor used by frequency_type.
frequency_subday | int | How often to reschedule during the defined period: 1 = Once 2 = Second 4 = Minute (default) 8 = Hour
frequency_subday_ interval | int | Interval for frequency_subday.
active_start_time_ of_day | int | Time of day when the Distribution Agent will first be scheduled, formatted as HHMMSS.
active_end_time_ of_day | int | Time of day when the Distribution Agent will stop being scheduled, formatted as HHMMSS.
active_start_date | int | Date when the Distribution Agent will first be scheduled, formatted as YYYYMMDD.
active_end_date | int | Date when the Distribution Agent will stop being scheduled, formatted as YYYYMMDD.


MSsubscriptions

Contains one row for each subscription serviced by the local Distributor. This table is stored in the distribution database.

Column name | Data type | Description
publisher_id | smallint | ID of the Publisher.
publisher_db | sysname | Name of the Publisher database.
publication_id | int | ID of the publication.
article_id | int | ID of the article.
subscriber_id | smallint | ID of the Subscriber.
subscriber_db | sysname | Name of the subscription database.
subscription_type | int | Type of subscription: 0 = Push 1 = Pull 2 = Anonymous
sync_type | tinyint | Type of synchronization: 1 = Automatic 2 = No sync
status | tinyint | Status of the subscription: 0 = Inactive 1 = Subscribed 2 = Active
subscription_seqno | varbinary(16) | Snapshot transaction sequence number.
snapshot_seqno_flag | bit | 1 = subscription_seqno is the snapshot sequence number.
independent_agent | bit | Indicates whether there is a stand-alone Distribution Agent for this publication.
subscription_time | datetime | Synctran.
synctran_conflict_method | tinyint | Type of synctran conflict method: 0 = None 1 = Row compare 2 = Timestamp
agent_id | int | ID of the agent.
update_mode | tinyint | Type of update.
publisher_seqno | varbinary(16) | Sequence number of the transaction at the Publisher for this subscription.


MSsubscription_properties

Contains rows for the parameter information for pull Distribution Agents. This table is stored in the Subscriber database.

Column name | Data type | Description
publisher | sysname | Name of the Publisher.
publisher_db | sysname | Name of the Publisher database.
publication | sysname | Name of the publication.
publication_type | int | Type of publication: 0 = Snapshot 1 = Transactional
publisher_login | sysname | Login ID used at the Publisher for SQL Server Authentication.
publisher_password | sysname | Password used at the Publisher for SQL Server Authentication.
publisher_security_mode | int | Security mode implemented at the Publisher: 0 = SQL Server Authentication 1 = Windows NT Authentication
encrypted_publisher_password | bit | Indicates whether password is encrypted.
distributor_login | sysname | Distributor login.
distributor_password | sysname | Distributor password.
distributor_security_mode | int | Security mode implemented at the Distributor: 0 = SQL Server Authentication 1 = Windows NT Authentication
encrypted_distributor_password | bit | Distributor password stored in encrypted form.
ftp_address | sysname | Network address of the FTP service for the Distributor.
ftp_port | int | Port number of the FTP service for the Distributor.
ftp_login | sysname | Username used to connect to the FTP service.
ftp_password | sysname | User password used to connect to the FTP service.


restorefile

Contains one row for each restored file, including files restored indirectly by filegroup name. This table is stored in the msdb database.

Column name | Data type | Description
restore_history_id | int NOT NULL REFERENCES restorehistory(restore_ history_id) | Unique identification number identifying the corresponding restore operation.
file_number | numeric(10,0) NULL | File identification number of the restored file. This number must be unique within each database.
destination_phys_drive | varchar(260) NULL | Drive or partition to which the file was restored.
destination_phys_name | varchar(260) NULL | Name of the file, without the drive or partition information, where the file was restored.


restorefilegroup

Contains one row for each restored filegroup. This table is stored in the msdb database.

Column name | Data type | Description
restore_history_id | int NOT NULL REFERENCES restorehistory(restore_ history_id) | Unique identification number identifying the corresponding restore operation
filegroup_name | nvarchar(128) NULL | Name of the filegroup being restored


restorehistory

Contains one row for each restore operation. This table is stored in the msdb database.

Column name | Data type | Description
restore_history_id | int NOT NULL IDENTITY PRIMARY KEY | Unique identification number identifying each restore operation.
restore_date | datetime NULL | Date and time of the restore operation.
destination_database_ name | nvarchar(128) NULL | Name of the destination database for the restore operation.
user_name | nvarchar(128) NULL | Name of the user who performed the restore operation.
backup_set_id | int NOT NULL REFERENCES backupset(backup_ set_id) | Unique identification number identifying the backup set being restored.
restore_type | char(1) NULL | Type of restore operation: D = Database F = File G = Filegroup L = Log V = Verifyonly
replace | bit NULL | Indicates whether the restore operation specified the REPLACE option: 1 = Specified 0 = Not specified
recovery | bit NULL | Indicates whether the restore operation specified the RECOVERY or NORECOVERY option: 1 = RECOVERY 0 = NORECOVERY
restart | bit NULL | Indicates whether the restore operation specified the RESTART option: 1 = Specified 0 = Not specified
stop_at | datetime NULL | Point in time to which the database was recovered.
device_count | tinyint NULL | Number of devices involved in the restore operation. This number can be less than the number of media families for the backup.


sysalerts

Contains one row for each alert. An alert is a message sent in response to an event. An alert can forward messages beyond the Microsoft® SQL Server™ environment, and an alert can be an e-mail or pager message. An alert also can generate a task.

Column name | Data type | Description
id | int | Alert ID.
name | sysname | Alert name.
event_source | nvarchar(100) | Source of the event: SQL Server.
event_category_id | int | Reserved for future use.
event_id | int | Reserved for future use.
message_id | int | User-defined message ID or reference to sysmessages message that triggers this alert.
severity | int | Severity that triggers this alert.
enabled | tinyint | Status of the alert: 0 = Disabled 1 = Enabled
delay_between_ responses | int | Wait period, in seconds, between notifications for this alert.
last_occurrence_date | int | Last occurrence (date) of the alert.
last_occurrence_time | int | Last occurrence (time of day) of the alert.
last_response_date | int | Last notification (date) of the alert.
last_response_time | int | Last notification (time of day) of the alert.
notification_message | nvarchar(512) | Additional information sent with the alert.
include_event_ description | tinyint | Bitmask representing whether the event description is sent by either or both: 1 = E-mail 2 = Pager
database_name | sysname | Database in which this alert must occur to trigger this alert.
event_description_ keyword | nvarchar(100) | Pattern the error must match in order for the alert to trigger.
occurrence_count | int | Number of occurrences for this alert.
count_reset_date | int | Day (date) count will be reset to 0.
count_reset_time | int | Time of day count will be reset to 0.
job_id | uniqueidentifier | ID of the task executed when this alert occurs.
has_notification | int | Number of operators who receive e-mail notification when alert occurs.
flags | int | Reserved.
performance_condition | nvarchar(512) | Reserved.
category_id | int | Reserved.


sysallocations

Contains a row for each allocation unit. This table is stored in each database.

Column | Data Type | Description
objid | int | Object identification number.
indid | smallint | Index identification number.
fileid | smallint | File identification number.
gaminterval | int | Interval used for the global allocation map (GAM). For more information, see Space Allocation and Reuse.
iampage | binary(6) | Index allocation map.


sysaltfiles

Contains one row for each file in a database. This table is stored in the master database.

Column name | Data type | Description
fileid | smallint | File identification number which is unique for each database.
groupid | smallint | Filegroup identification number.
size | int | File size, in 8 KB pages.
maxsize | int | Maximum file size (in 8 KB pages). A value of 0 indicates no growth, and a value of -1 indicates that the file should grow until the disk is full.
growth | int | Growth size of the database. A value of 0 indicates no growth. Can be either the number of pages or the percentage of file size, depending on the value of status. If status is 0x100000, then growth is the percentage of file size; otherwise, it is the number of pages.
status | int | The growth value in either megabytes (MB) or kilobytes (K).
perf | int | Reserved.
dbid | smallint | Database identification number of the database to which this file belongs.
name | nchar(128) | Logical name of the file.
filename | nchar(260) | Name of the physical device, including the full path of the file.


sysarticles

Contains a row for each article defined in the local database. This table is stored in the published database.

Column name | Data type | Description
artid | int | Identity column that provides a unique ID number for the article.
columns | varbinary(32) | Columns in the tables that are being published.
creation_script | nvarchar(255) | Schema script for the article.
del_cmd | nvarchar(255) | Command to execute upon DELETE; otherwise, construct from the log.
description | nvarchar(255) | Descriptive entry for the article.
dest_table | sysname | Name of the destination table.
filter | int | Stored procedure ID, used for horizontal partitioning.
filter_clause | ntext | WHERE clause of the article, used for horizontal filtering.
ins_cmd | nvarchar(255) | Command to execute upon INSERT; otherwise, construct from the log.
name | sysname | Name associated with the article, unique within the publication.
objid | int | Published table object ID.
pubid | int | ID of the publication to which the article belongs.
pre_creation_ cmd | tinyint | Pre-creation command for DROP TABLE, DELETE TABLE, or TRUNCATE: 0 = None 1 = DROP 2 = DELETE 3 = TRUNCATE
status | tinyint | Bitmap used to describe a property of the article: 0x00 = Article is inactive. 0x01 = Article is active.
sync_objid | int | ID of the table or view that represents the article definition.
type | tinyint | Type of article: 1 = Log-based article 3 = Log-based article with manual filter 5 = Log-based article with manual view 7 = Log-based article with manual filter and manual view
upd_cmd | nvarchar(255) | Command to execute upon UPDATE; otherwise, construct from the log.
schema_option | binary(8) | Indicates what is to be scripted out.
dest_owner | sysname | Owner of the table at the destination database.


sysarticleupdates

Contains one row for each article that supports immediate-updating subscriptions. This table is stored in the replicated database.

Column name | Data type | Description
artid | int | Identity column providing a unique ID number for the article.
pubid | int | ID of the publication to which the article belongs.
sync_ins_proc | int | ID of the stored procedure handling Insert Sync Transactions.
sync_upd_proc | int | ID of the stored procedure handling Update Sync Transactions.
sync_del_proc | int | ID of the stored procedure handling Delete Sync Transactions.
autogen | bit | Indicates that stored procedures are automatically generated: 0 = False, not automatic 1 = True, automatic


syscacheobjects

Contains information on how the cache is being used. syscacheobjects belongs to the master database. The table shows cache lookup keys.

Column name | Data type | Description
bucketid | int | Bucket ID. Values indicates a range from 0 to (directory size -1). Directory size is the size of the hash table.
Cacheobjtype | nvarchar(34) | Type of object in the cache: Compiled Plan Executable Plan Parse Tree Cursor Parse Tree Extended Stored Procedure.
Objtype | nvarchar(16) | Type of object: Stored Procedure Prepared statement Ad hoc query (Transact SQL submitted as language events from isql or osql, as opposed to remote procedure calls) ReplProc (replication procedure) Trigger View Default User table System table Check Rule
objid | int | One of the main keys used for looking up an object in the cache. This is the object ID stored in sysobjects for database objects (procedures, views, triggers, and so on.) For cache objects such as ad hoc or prepared SQL, objid is an internally generated value.
dbid | smallint | Database ID in which the cache object was compiled.
uid | smallint | Indicates the creator of the plan for ad hoc query plans and prepared plans. -2 indicates the batch submitted does not depend on implicit name resolution and can be shared among different users. This is the preferred method. Any other value represents the user ID of the user submitting the query in the database.
refcounts | int | Number of other cache objects referencing this cache object. A count of 1 is the base.
usecounts | int | Number of times this cache object has been used since inception.
pagesused | int | Number of memory pages consumed by the cache object.
setopts | int | SET option settings that affect a compiled plan. These are part of the cache key. Changes to values in this column indicate users have modified SET options. These options include ANSI_PADDING FORCEPLAN CONCAT_NULL_YIELDS_NULL ANSI_WARNINGS ANSI_NULLS QUOTED_IDENTIFIER ANSI_NULL_DFLT_ON ANSI_NULL_DFLT_OFF
langid | smallint | Language ID. ID of the language of the connection that created the cache object.
dateformat | smallint | Date format of the connection that created the cache object.
status | int | Indicates whether the cache object is a cursor plan. Currently, only the least significant bit is used.
sqlbytes | int | Length of name or batch submitted. Can be used to distinguish two names or submitted batches if the first 128 characters are the same.
sql | nvarchar(256) | Procedure name or first 128 characters of the batch submitted.


syscategories

Contains the categories used by SQL Server Enterprise Manager to organize jobs, alerts, and operators. This table is stored in the msdb database.

Column name | Data type | Description
category_id | int | ID of the category
category_class | int | Type of item in the category: 1 = Job 2 = Alert 3 = Operator
category_type | tinyint | Type of category: 1 = Local 2 = Multiserver 3 = None
name | sysname | Name of the category


syscharsets

Contains one row for each character set and sort order defined for use by Microsoft® SQL Server™. One of the sort orders is marked in sysconfigures as the default sort order, which is the only one actually in use.

Column name | Data type | Description
type | smallint | Type of entity this row represents. 1001 is a character set; 2001 is a sort order.
id | tinyint | Unique ID for the character set or sort order. Note sort orders and character sets cannot share the same ID number. The ID range of 1 through 240 is reserved for SQL Server use.
csid | tinyint | If the row represents a character set, this field is unused. If the row represents a sort order, this field is the ID of the character set that the sort order is built on. It is assumed a character set row with this ID exists in this table.
status | smallint | Internal system status information bits.
name | sysname | Unique name for the character set or sort order. This field must contain only the letters A-Z or a-z, numbers 0 - 9, and underscores(_). It must begin with a letter.
description | nvarchar(255) | Optional description of the features of the character set or sort order.
binarydefinition | varbinary(255) | For internal use only.
definition | image | Internal definition of the character set or sort order. The structure of the data in this field depends on the type.


syscolumns

Contains one row for every column in every table and view, and a row for each parameter in a stored procedure. This table is in each database.

Column name | Data type | Description
name | sysname | Name of the column or procedure parameter.
id | int | Object ID of the table to which this column belongs, or the ID of the stored procedure with which this parameter is associated.
xtype | tinyint | Physical storage type from systypes.
typestat | tinyint | For internal use only.
xusertype | smallint | ID of extended user-defined data type.
length | smallint | Maximum physical storage length from systypes.
xprec | tinyint | For internal use only.
xscale | tinyint | For internal use only.
colid | smallint | Column or parameter ID.
xoffset | smallint | For internal use only.
bitpos | tinyint | For internal use only.
reserved | tinyint | For internal use only.
colstat | smallint | For internal use only.
cdefault | int | ID of the default for this column.
domain | int | ID of the rule or CHECK constraint for this column.
number | smallint | Subprocedure number when the procedure is grouped (0 for nonprocedure entries).
colorder | smallint | For internal use only.
autoval | varbinary(255) | For internal use only.
offset | smallint | Offset into the row in which this column appears; if negative, variable-length row.
status | tinyint | Bitmap used to describe a property of the column or the parameter: 0x08 = Column allows null values. 0x10 = ANSI padding was in effect when varchar or varbinary columns were added. Trailing blanks are preserved for varchar and trailing zeros are preserved for varbinary columns. 0x40 = Parameter is an OUTPUT parameter. 0x80 = Column is an identity column.
type | tinyint | Physical storage type from systypes.
usertype | smallint | ID of user-defined data type from systypes.
printfmt | varchar(255) | For internal use only.
prec | smallint | Level of precision for this column.
scale | int | Scale for this column.
iscomputed | int | Flag indicating whether the column is computed: 0 = Noncomputed 1 = Computed
isoutparam | int | Is whether the procedure parameter is an output parameter: 1 = True 0 = False
isnullable | int | Is whether the column allows null values: 1 = True 0 = False


syscomments

Contains entries for each view, rule, default, trigger, CHECK constraint, DEFAULT constraint, and stored procedure. The text column contains the original SQL definition statements, which are limited to a maximum size of 4 MB. This table is stored in each database.

Important None of the entries in syscomments should be deleted. If an entry in syscomments is manually removed or modified, the corresponding stored procedure will not function properly. To hide or encrypt stored procedure definitions, use CREATE PROCEDURE with the ENCRYPTION keyword.

Column name | Data type | Description
id | int | Object ID to which this text applies.
number | smallint | Number within procedure grouping, if grouped. 0 for entries that are not procedures.
colid | smallint | Row sequence number for object definitions longer than 4,000 characters.
status | smallint | For internal use only.
ctext | varbinary(8000) | Actual text of the SQL definition statement.
texttype | smallint | 0 = User-supplied comment 1 = System-supplied comment 4 = Encrypted comment
language | smallint | For internal use only.
encrypted | bit | Indicates whether the procedure is encrypted. 0 = Not encrypted 1 = Encrypted
compressed | bit | Indicates whether or not the procedure is compressed. 0 = Not compressed 1 = Compressed
text | nvarchar(4000) | Actual text of the SQL definition statement.


sysconfigures

Contains one row for each configuration option set by a user. sysconfigures contains the configuration options defined before the most recent Microsoft® SQL Server™ startup, plus any dynamic configuration options set since then. This table is only in the master database.

Column name | Data type | Description
value | int | User-modifiable value for the variable (being used by SQL Server only if RECONFIGURE has been executed).
config | smallint | Configuration variable number.
comment | nvarchar(255) | Explanation of the configuration option.
status | smallint | Bitmap indicating the status for the option. Possible values include: 0 = Static (The setting takes effect when the server is restarted.) 1 = Dynamic (The variable takes effect when the RECONFIGURE statement is executed.) 2 = Advanced (The variable is displayed only when the show advanced option is set.) 3 = Dynamic and advanced


sysconstraints

Contains mappings of constraints to the objects that own the constraints. This table is stored in each database.

Column name | Data type | Description
constid | int | Constraint number.
id | int | ID of the table that owns the constraint.
colid | smallint | ID of the column on which the constraint is defined, 0 if a table constraint.
spare1 | tinyint | Reserved.
status | int | 1 = PRIMARY KEY constraint 2 = UNIQUE KEY constraint 3 = FOREIGN KEY constraint 4 = CHECK constraint 5 = DEFAULT constraint 16 = Column-level constraint 32 = Table-level constraint
actions | int | Reserved.
error | int | Reserved.


syscurconfigs

Contains an entry for each of the current configuration options. In addition, this table contains four entries that describe the configuration structure. syscurconfigs is built dynamically when queried by a user. For more information, see sysconfigures.

Column name | Data type | Description
value | int | User-modifiable value for the variable (being used by Microsoft® SQL Server™ only if RECONFIGURE has been executed).
config | smallint | Configuration variable number.
comment | nvarchar(255) | Explanation of the configuration option.
status | smallint | Bitmap indicating the status for the option. Possible values include: 0 = Static (The setting takes effect when the server is restarted.) 1 = Dynamic (The variable takes effect when the RECONFIGURE statement is executed.) 2 = Advanced (The variable is displayed only when the show advanced option is set.) 3 = Dynamic and advanced


sysdatabases

Contains one row for each database on Microsoft® SQL Server™. When SQL Server is initially installed, sysdatabases contains entries for the master, model, msdb, mssqlweb, and tempdb databases. This table is stored only in the master database.

Column name | Data type | Description
name | sysname | Name of the database.
dbid | smallint | Database ID.
sid | varbinary(149) | System ID of the database creator.
mode | smallint | Used internally for locking a database while it is being created.
status | int | Status bits, some of which can be set by the user with sp_dboption (read only, dbo use only, single user, and so on): 1 = autoclose; set with sp_dboption. 4 = select into/bulkcopy; set with sp_dboption. 8 = trunc. log on chkpt; set with sp_dboption. 16 = torn page detection, set with sp_dboption. 32 = loading. 64 = pre recovery. 128 = recovering. 256 = not recovered. 512 = offline; set with sp_dboption. 1024 = read only; set with sp_dboption. 2048 = dbo use only; set with sp_dboption. 4096 = single user; set with sp_dboption. 32768 = emergency mode. 4194304 = autoshrink. 1073741824 = cleanly shutdown. Multiple bits can be on at the same time.
status2 | int | 16384 = ANSI null default; set with sp_dboption. 65536 = concat null yields null , set with sp_dboption. 131072 = recursive triggers, set with sp_dboption. 1048576 = default to local cursor, set with sp_dboption. 8388608 = quoted identifier, set with sp_dboption. 33554432 = cursor close on commit, set with sp_dboption. 67108864 = ANSI nulls, set with sp_dboption. 268435456 = ANSI warnings, set with sp_dboption. 536870912 = full text enabled, set with sp_fulltext_database
crdate | datetime | Creation date.
reserved | datetime | Reserved for future use.
category | int | Contains a bitmap of information used for replication: 1 = Published 2 = Subscribed 4 = Merge Published 8 = Merge Subscribed
cmptlevel | tinyint | Compatibility level for the database. For more information, see sp_dbcmptlevel.
filename | nvarchar(260) | Operating-system path and name for the database’s primary file. Will be added in a future release.
suid | smallint | ID of the SQL Server login that owns the database.
version | smallint | Internal version number of the SQL Server code with which the database was created.


sysdepends

Contains dependency information between objects (views, procedures, and triggers), and the objects (tables, views, and procedures) contained in their definition. This table is stored in each database.

Column name | Data type | Description
id | int | Object ID.
depid | int | Dependent object ID.
number | smallint | Procedure number.
depnumber | smallint | Dependent procedure number.
status | smallint | Internal status information.
depdbid | smallint | Reserved.
depsiteid | smallint | Reserved.
selall | bit | On if the object is used in a SELECT * statement.
resultobj | bit | On if the object is being updated.
readobj | bit | On if the object is being read.


sysdevices

Contains one row for each disk backup file, tape backup file, and database file. This table is stored only in the master database.

Important This system table is provided for backward compatibility only. In earlier versions of Microsoft® SQL Server™, this table contained a list of all database files. For SQL Server version 7.0, a list of database files is stored in the sysfiles system table of each database.

Column name | Data type | Description
name | sysname | Logical name of the backup file or database file.
size | int | Size of the file in 2 KB pages.
low | int | Maintained for backward compatibility only.
high | int | Maintained for backward compatibility only.
status | smallint | Bitmap indicating the type of device: 1 = Default disk 2 = Physical disk 4 = Logical disk 8 = Skip header 16 = Backup file 32 = Serial writes 4096 = Read-only
cntrltype | smallint | Controller type: 0 = Non-CD-ROM database file 2 = Disk backup file 3 - 4 = Diskette backup file 5 = Tape backup file 6 = Named-pipe file
phyname | nvarchar(260) | Name of the physical file.


sysdownloadlist

Holds the queue of download instructions for all target servers.

Column name | Data type | Description
instance_id | int | Identity column that provides the natural insertion sequence of rows.
source_server | nvarchar(30) | Name of the source server.
operation_code | tinyint | Operation code for the job: 1 = INS (INSERT 2 = UPD (UPDATE) 3 = DEL (DELETE) 4 = START 5 = STOP
object_type | tinyint | Object type code. For Microsoft® SQL Server™ version 7.0, this value can be 1, which corresponds to JOB.
object_id* | uniqueidentifier | Object identification number.
target_server | nvarchar(30) | Name of the target server.
error_message | nvarchar(1024) | Error message if the target server encounters an error when processing the particular row.
date_posted | datetime | Date and time the job was posted to the target server.
date_downloaded | datetime | Date and time job was last downloaded.
status | tinyint | Status of the job: 0 = Not yet downloaded 1 = Successfully downloaded
* The object_id column can be a value of -1 which corresponds to a value of ALL if the operation_code column is a value of DELETE.


sysfiles

Contains one row for each file in a database. This system table is a virtual table; it cannot be updated or modified directly.

Column name | Data type | Description
fileid | smallint | File identification number unique for each database.
groupid | smallint | Filegroup identification number.
size | int | Size of the file (in 8 KB pages).
maxsize | int | Maximum file size (in 8 KB pages). A value of 0 indicates no growth, and a value of -1 indicates that the file should grow until the disk is full.
growth | int | Growth size of the database. A value of 0 indicates no growth. Can be either the number of pages or the percentage of file size, depending on value of status. If status contains 0x100000, then growth is the percentage of file size; otherwise, it is number of pages.
status | int | Status bits for the growth value in either megabytes (MB) or kilobytes (K). 0x1 = Default device. 0x2 = Disk file. 0x40 = Log device. 0x80 = File has been written to since last backup. 0x4000 = Device created implicitly by the CREATE DATABASE statement. 0x8000 = Device created during database creation. 0x100000 = Growth is in percentage, not pages.
perf | int | Reserved.
name | nchar(128) | Logical name of the file.
filename | nchar(260) | Name of the physical device, including the full path of the file.


sysfilegroups

Contains one row for each filegroup in a database. This table is stored in each database. There is at least one entry in this table that is for the primary filegroup.

Column name | Data type | Description
groupid | smallint | Group identification number unique for each database.
allocpolicy | smallint | Reserved.
status | int | 0x8 = READ ONLY 0x10 = DEFAULT
groupname | sysname | Name of the filegroup.


sysforeignkeys

Contains information regarding the FOREIGN KEY constraints that are in table definitions. This table is stored in each database.

Column name | Data type | Description
constid | int | ID of the FOREIGN KEY constraint.
fkeyid | int | Object ID of the table with the FOREIGN KEY constraint.
rkeyid | int | Object ID of the table referenced in the FOREIGN KEY constraint.
fkey | smallint | ID of the referencing column.
rkey | smallint | ID of the referenced column.
keyno | smallint | Position of the column in the reference column list.


sysfulltextcatalogs

Lists the set of full-text catalogs.

Column name | Data type | Description
ftcatid | smallint | Identifier of the full-text catalog.
name | sysname | Full-text catalog name given by the user.
status | smallint | Reserved; internal use only.
path | nvarchar(260) | Root path given by the user. A value of NULL means a path was not given and the default (installation) path was used.


sysindexes

Contains one row for each index and table in the database. This table is stored in each database.

Column name | Data type | Description
id | int | ID of table (for indid = 0 or 255). Otherwise, ID of table to which the index belongs.
status | int | Internal system-status information: 1 = Cancel command if attempt to insert duplicate key. 2 = Unique index. 4 = Cancel command if attempt to insert duplicate row. 16 = Clustered index. 64 = Index allows duplicate rows. 2048 = Index used to enforce PRIMARY KEY constraint. 4096 = Index used to enforce UNIQUE constraint.
first | binary(6) | Pointer to the first or root page.
indid | smallint | ID of index: 1 = Clustered index. >1 = Nonclustered. 255 = Entry for tables that have text or image data.
root | binary(6) | For indid >= 1 and < 255, root is the pointer to the root page. For indid = 0 or indid = 255, root is the pointer to the last page.
minlen | smallint | Minimum size of a row.
keycnt | smallint | Number of keys.
groupid | smallint | Filegroup ID on which the object was created.
dpages | int | For indid = 0 or indid = 1, dpages is the count of data pages used. For indid=255, it is set to 0. Otherwise, it is the count of index pages used.
reserved | int | For indid = 0 or indid = 1, reserved is the count of pages allocated for all indexes and table data. For indid = 255, reserved is a count of the pages allocated for text or image data. Otherwise, it is the count of pages allocated for the index.
used | int | For indid = 0 or indid = 1, used is the count of the total pages used for all index and table data. For indid = 255. used is a count of the pages used for text or image data. Otherwise, it is the count of pages used for the index.
rowcnt | binary(8) | Data-level rowcount based on indid = 0 and indid = 1, and the value is repeated for indid >1. For indid = 255, rowcnt is set to 0.
rowmodctr | int | Counts the total number of inserted, deleted, or updated rows since the last time statistics were updated for the table.
soid | tinyint | Sort order ID that the index was created with. 0, if there is no character data in the keys.
csid | tinyint | Character set ID that the index was created with. 0, if there is no character data in the keys.
xmaxlen | smallint | Maximum size of a row.
maxirow | smallint | Maximum size of a nonleaf index row.
OrigFillFactor | tinyint | Original fillfactor value used when the index was created. This value is not maintained; however, it can be helpful if you need to re-create an index and do not remember what fillfactor was used.
reserved1 | tinyint | Reserved.
reserved2 | int | Reserved.
FirstIAM | binary(6) | Reserved.
impid | smallint | Reserved. Index implementation flag.
lockflags | smallint | Used to constrain the considered lock granularities for an index. For example, a lookup table that is essentially read-only could be set up to do only table level locking to minimize locking cost.
pgmodctr | int | Used to track the number of pages that have changed in an index.
keys | varbinary(512) | List of the column IDs of the columns that make up the index key.
name | sysname | Name of table (for indid = 0 or 255). Otherwise, name of index.
statblob | image | Statistics BLOB.
maxlen | int | Reserved.
rows | int | Data-level rowcount based on indid = 0 and indid = 1, and the value is repeated for indid >1. For indid = 255, rows is set to 0. Provided for backward compatibility.


sysindexkeys

Contains information for the keys or columns in an index. This table is stored in each database.

Column name | Data type | Description
id | int | ID of the table
indid | smallint | ID of the index
colid | smallint | ID of the column
keyno | smallint | Position of the column in the index


sysjobhistory

Contains information about the execution of scheduled jobs by SQL Server Agent. This table is stored in the msdb database.

Column name | Data type | Description
instance_id | int | Unique identifier for the row.
job_id | uniqueidentifier | Job ID.
step_id | int | ID of the step in the job.
step_name | sysname | Name of the step.
sql_message_id | int | ID of any Microsoft® SQL Server™ error message returned if the job failed.
sql_severity | int | Severity of any SQL Server error.
message | nvarchar(1024) | Text, if any, of a SQL Server error.
run_status | int | Status of the job execution: 0 = Failed 1 = Succeeded 2 = Retry 3 = Canceled 4 = In progress
run_date | int | Date the job or step started execution. For an In Progress history, this is the date/time the history was written.
run_time | int | Time the job or step completed.
run_duration | int | Amount of time incurred in the execution of the job or step.
operator_id_ emailed | int | ID of the operator notified when the job completed.
operator_id_ netsent | int | ID of the operator notified by a message when the job completed.
operator_id_paged | int | ID of the operator notified by pager when the job completed.
retries_attempted | int | Number of retry attempts for the job or step.
server | nvarchar(30) | Name of the server where the job was executed.


sysjobschedules

Contains schedule information for jobs to be executed by SQL Server Agent. This table is stored in the msdb database.

Column name | Data type | Description
schedule_id | int | ID of the schedule.
job_id | uniqueidentifier | ID of the job.
name | sysname | Name of the schedule.
enabled | int | Enabled status of the schedule.
freq_type int Frequency of the schedule execution:
1 = Once
4 = Daily
8 = Weekly
16 = Monthly
32 = Monthly relative
64 = Execute when SQL Server
Agent starts
freq_interval int Value indicating on which days the schedule runs.

If freq_type is 4 (daily), the value is every freq_interval days.

If freq_type is 8 (weekly), the value is a bitmask indicating the days in which weekly schedules are run. The freq_interval values are:
1 = Sunday
2 = Monday
4 = Tuesday
8 = Wednesday
16 = Thursday
32 = Friday
64 = Saturday

If freq_type is 16 (monthly), the value is freq_interval day of the month.

If freq_type is 32 (monthly relative), freq_interval can be one of these values:
1 = Sunday
2 = Monday
3 = Tuesday
4 = Wednesday
5 = Thursday
6 = Friday
7 = Saturday
8 = Day
9 = Weekday
10 = Weekend day
freq_subday_type int Units for the freq_subday_interval:
1 = At the specified time
2 = Seconds
4 = Minutes
8 = Hours
freq_subday_
interval 		int Number of freq_subday_type periods to occur between each scheduled execution of the job.
freq_relative_
interval 		int Scheduled job’s occurrence of the freq_interval in each month when freq_type is 32 (monthly relative):
1 = First
2 = Second
4 = Third
8 = Fourth
16 = Last
freq_recurrence_
factor 		int Number of weeks or months between the scheduled execution of the job.
active_start_date | int | Date to begin executing the job.
active_end_date | int | Date to stop executing the job.
active_start_time | int | Time to start executing the job.
active_end_time | int | Time to stop executing the job.
next_run_date | int | Date that the job will next execute.
next_run_time | int | Time that the job will next execute.
date_created | datetime | Date the scheduled job entry was created.


sysjobs

Stores the information for each scheduled job to be executed by SQL Server Agent. This table is stored in the msdb database.

Column name | Data type | Description
job_id | uniqueidentifier | Unique ID of the job.
originating_server | nvarchar(30) | Name of the server from which the job came.
name | sysname | Name of the job.
enabled | tinyint | Indicates whether the job is enabled to be executed.
description | nvarchar(512) | Description for the job.
start_step_id | int | ID of the step in the job where execution should begin.
category_id | int | ID of the job category.
owner_sid | varbinary(85) | System identification number (SID) of the job owner.
notify_level_ eventlog | int | Bitmask indicating under what circumstances a notification event should be logged to the Microsoft® Windows NT® application log: 0 = Never 1 = When a succeeds 2 = When the job fails 3 = Whenever the job completes (regardless of the job outcome)
notify_level_email | int | Bitmask indicating under what circumstances a notification e-mail should be sent when a job completes: 0 = Never 1 = When the job succeeds 2 = When the job fails 3 = Whenever the job completes (regardless of the job outcome)
notify_level_netsend | int | Bitmask indicating under what circumstances a network message should be sent when a job completes: 0 = Never 1 = When the job succeeds 2 = When the job fails 3 = Whenever the job completes (regardless of the job outcome)
notify_level_page | int | Bitmask indicating under what circumstances a page should be sent when a job completes: 0 = Never 1 = When the job succeeds 2 = When the job fails 3 = Whenever the job completes (regardless of the job outcome)
notify_email_ operator_id | int | E-mail name of the operator to notify.
notify_netsend_ operator_id | int | ID of the computer or user used when sending network messages.
notify_page_ operator_id | int | ID of the computer or user used when sending a page.
delete_level | int | Bitmask indicating under what circumstances the job should be deleted when a job completes: 0 = Never 1 = When the job succeeds 2 = When the job fails 3 = Whenever the job completes (regardless of the job outcome)
date_created | datetime | Date the job was created.
date_modified | datetime | Date the job was last modified.
version_number | int | Version of the job.


sysjobservers

Stores the association or relationship of a particular job with one or more target servers.

Column name | Data type | Description
job_id | uniqueidentifier | Job identification number.
server_id | int | Server identification number.
last_run_outcome | tinyint | Outcome for the job’s last run: 0 = Succeed 1 = Fail 2 = Cancel
last_outcome_ message | nvarchar(1024) | Associated message, if any, with the last_run_outcome column.
last_run_date | int | Date the job was last run.
last_run_time | int | Time the job was last run.
last_run_duration | int | Duration of the job’s run, in seconds.


sysjobsteps

Contains the information for each step in a job to be executed by SQL Server Agent. This table is stored in the msdb database.

Column name | Data type | Description
job_id | uniqueidentifier | ID of the job.
step_id | int | ID of the step in the job.
step_name | sysname | Name of the job step.
subsystem | varchar(60) | Name of the subsystem used by SQL Server Agent to execute the job step.
command | nvarchar(3200) | Command to be executed by subsystem.
flags | int | Reserved.
additional_ parameters | ntext | Reserved.
cmdexec_success_ code | int | Error-level value returned by CmdExec subsystem steps to indicate success.
on_success_action | tinyint | Action to be performed when a step is executed successfully.
on_success_step_id | int | ID of the next step to execute when a step is executed successfully.
on_fail_action | tinyint | Action to be performed when a step is not executed successfully.
on_fail_step_id | int | ID of the next step to execute when a step is not executed successfully.
server | sysname | Reserved.
database_name | sysname | Name of the database in which command is executed if subsystem is TSQL.
database_user_name | sysname | Name of the database user whose account will be used when executing the step.
retry_attempts | int | Number of retry attempts made if the step fails.
retry_interval | int | Amount of time to wait between retry attempt.
os_run_priority | int | Reserved.
output_file_name | nvarchar(200) | Name of the file in which the step’s output is saved when subsystem is TSQL or CmdExec.
last_run_outcome | int | Outcome of the previous execution of the job step.
last_run_duration | int | Amount of time incurred in the previous execution of the job.
last_run_retries | int | Number of retry attempts in the last execution of the job step.
last_run_date | int | Date of the job step’s previous execution.
last_run_time | int | Time of the job step’s previous execution.


syslanguages

Contains one row for each language present in Microsoft® SQL Server™. Although U.S. English is not in syslanguages, it is always available to SQL Server. This table is stored only in the master database.

Column name | Data type | Description
langid | smallint | Unique language ID.
dateformat | nchar(3) | Date order (for example, DMY).
datefirst | tinyint | First day of the week: 1 for Monday, 2 for Tuesday, and so on through 7 for Sunday.
upgrade | int | Reserved for system use.
name | sysname | Official language name (for example, français).
alias | sysname | Alternate language name (for example, french).
months | nvarchar(372) | Comma-separated list of full-length month names in order from January through December, with each name containing as many as 20 characters.
shortmonths | varchar(132) | Comma-separated list of short-month names in order from January through December, with each name containing as many as 9 characters.
days | nvarchar(217) | Comma-separated list of day names in order from Monday through Sunday, with each name containing as many as 30 characters.
lcid | int | Microsoft Windows NT® locale ID for the language.
mslangid | smallint | SQL Server message group ID.

Twenty-four SQL Server provided languages are installed. Here is a list of the languages.

Name in English | NT LCID | SQL Server Message Group ID
English | 1033 | 1033
German | 1031 | 1031
French | 1036 | 1036
Japanese | 1041 | 1041
Danish | 1030 | 1030
Spanish | 1034 | 1034
Italian | 1040 | 1040
Dutch | 1043 | 1043
Norwegian | 2068 | 2068
Portuguese | 2070 | 2070
Finnish | 1035 | 1035
Swedish | 1053 | 1053
Czech | 1029 | 1029
Hungarian | 1038 | 1038
Polish | 1045 | 1045
Romanian | 1048 | 1048
Croatian | 1050 | 1050
Slovak | 1051 | 1051
Slovene | 1060 | 1060
Greek | 1032 | 1032
Bulgarian | 1026 | 1026
Russian | 1049 | 1049
Turkish | 1055 | 1055


syslockinfo

Contains information on all granted, converting, and waiting lock requests. This table is a denormalized tabular view of internal data structures of the lock manager and is stored only in the master database.

Column name | Data type | Description
rsc_text | nchar(32) | Textual description of a lock resource. Contains the portion of the resource name that is distinct from the rsc_dbid, rsc_objid, rsc_indid triple, if one exists.
rsc_bin | binary(16) | Binary lock resource. Contains the actual lock resource that is contained in the lock manager. This column is included for tools that are aware of the lock resource format for generating their own formatted lock resource, and for performing self joins on syslockinfo.
rsc_valblk | binary(16) | Lock value block. Some resource types may include additional data in the lock resource that is not hashed by the lock manager to determine ownership of a particular lock resource. For example, page locks are not owned by a particular object ID. For lock escalation and other purposes, however, the object ID of a page lock may be placed in the lock value block.
rsc_dbid | smallint | Database ID associated with the resource.
rsc_indid | smallint | Index ID associated with the resource, if appropriate.
rsc_objid | int | Object ID associated with the resource, if appropriate.
rsc_type tinyint Resource type. Can be:

1 = NULL Resource (not used)
2 = Database
3 = File
4 = Index
5 = Table
6 = Page
7 = Key
8 = Extent
9 = RID (Row ID)
rsc_flag | tinyint | Internal resource flags.
req_mode tinyint Lock request mode. This column is the lock mode of the requester and represents either the granted mode, or the convert or waiting mode. Can be:

0 = NULL. No access is granted to the resource. Serves as a placeholder.

1 = Sch-S (Schema stability). Ensures that a schema element, such as a table or index, is not dropped while any session holds a schema stability lock on the schema element.

2 = Sch-M (Schema modification). Must be held by any session that wants to change the schema of the specified resource. Ensures that no other sessions are referencing the indicated object.

3 = IS (Intent Shared). Indicates the intention to place S locks on some subordinate resource in the lock hierarchy.

4 = SIU (Shared Intent Update). Indicates shared access to a resource with the intent of acquiring update locks on subordinate resources in the lock hierarchy.

5 = IS-S (Intent Shared-Shared). Is a composite key-range lock mode that is used to ensure serializability in index row-level locking.

6 = IX (Intent Exclusive). Indicates that the locking session will acquire X locks on subordinate resources in the lock hierarchy.

7 = SIX (Shared Intent Exclusive). Indicates shared access to a resource with the intent of acquiring exclusive locks on subordinate resources in the lock hierarchy.

8 = S (Shared). The holding session is granted shared access to the resource.

9 = U (Update). Indicates an update lock acquired on resources that may eventually be updated. It is used to prevent a common form of deadlock that occurs when multiple sessions are locking resources and are potentially updating them at a later time.

10 = IIn-Nul. (Intent Insert-NULL). Is a composite key-range lock mode that is used in index row-level locking.

11 = IS-X (Intent Shared-Exclusive) Used by serializable transactions inserting into a range that has been previously scanned.

12 = IU (Intent Update). Indicates that the locking session will acquire update locks on subordinate resources in the lock hierarchy.

13 = IS-U. (Intent Shared-Update). Used for serializable update scans.

14 = X. (Exclusive). The holding session is granted exclusive access to the resource.

15 = BU. Used by bulk operations.
req_status tinyint Status of the lock request. Can be:
1 = Granted
2 = Converting
3 = Waiting
req_refcnt | smallint | Lock reference count. Each time a transaction asks for a lock on a particular resource, a reference count is incremented. The lock cannot be released until the reference count equals 0.
req_cryrefcnt | smallint | Carry-over reference count. Most locks are released at the end of a transaction. Certain locks, such as cursor marker locks, are not released at the end of a transaction and are held, or carried over, to the next transaction.
req_lifetime | int | Lock lifetime bitmap. During certain query processing strategies, locks must be maintained on resources until the query processor has completed a particular phase of the query. The lock lifetime bitmap is used by the query processor and transaction manager to denote groups of locks that can be released when a certain phase of a query is completed. Certain bits in the bitmap are used to denote locks that are held until the end of a transaction, even if their reference count equals 0.
req_spid | int | Internal Microsoft® SQL Server™ process ID of the session requesting the lock.
req_ecid | int | Execution context ID (ECID). Used to denote which thread in a parallel operation owns a particular lock.
req_ownertype smallint Type of object associated with the lock. Can be one of the following:
1 = Transaction
2 = Session
3 = Cursor


syslogins

Contains one row for each login account.

Column name | Data type | Description
suid | smallint | Server user ID.
sid | varbinary(85) | Security identifier.
status | smallint | For internal use only.
createdate | datetime | Date the login was added.
updatedate | datetime | Date the login was updated.
accdate | datetime | For internal use only.
totcpu | int | For internal use only.
totio | int | For internal use only.
spacelimit | int | For internal use only.
timelimit | int | For internal use only.
resultlimit | int | For internal use only.
name | varchar(30) | Login ID of the user.
dbname | nvarchar(128) | Name of the user’s default database when connection is established.
password | nvarchar(128) | Encrypted password of the user (may be NULL).
language | nvarchar(128) | User’s default language.
denylogin | int | 1, if login is a Microsoft® Windows NT® user or group and has been denied access.
hasaccess | int | 1, if login has been granted access to the server.
isntname | int | 1 if login is a Windows NT user or group; 0 if the login is a Microsoft SQL Server™ login.
isntgroup | int | 1, if login is a Windows NT group.
isntuser | int | 1, if login is a Windows NT user.
sysadmin | int | 1, if login is a member of the sysadmin server role.
securityadmin | int | 1, if login is a member of the securityadmin server role.
serveradmin | int | 1, if login is a member of the serveradmin fixed server role.
setupadmin | int | 1, if login is a member of the setupadmin fixed server role.
processadmin | int | 1, if login is a member of the processadmin fixed server role.
diskadmin | int | 1, if login is a member of the diskadmin fixed server role.
dbcreator | int | 1, if login is a member of the dbcreator fixed server role.
loginname | nvarchar(128) | Actual name of the login, which may be different from the login name used by SQL Server.


sysmembers

Contains a row for each member of a database role. This table is stored in each database.

Column name | Data type | Description
memberuid | smallint | User ID for the role member.
groupuid | smallint | User ID for the role.


sysmergearticles

Contains one row for each merge article defined in the local database. This table is stored in the published database.

Column name | Data type | Description
name | sysname | Name of the article.
type | tinyint | Article type.
objid | int | Object identifier.
sync_objid | int | Object ID of the view representing the synchronized data set.
view_type | tinyint | Type of view. Can be: 0 = Not a view; use all of base object. 1 = Permanent view. 2 = Temporary view.
artid | uniqueidentifier | Identity column used to provide a unique identification number for the given article. artid is derived from sysobjects.srcid.
description | nvarchar(255) | Brief description of the article.
pre_creation_ command | nvarchar(10) | Default action to take when the article is created in the subscription database. Can be: None = If the table already exists at the Subscriber, no action is taken. Delete = Issues a delete based on the WHERE clause in the subset filter. Drop (default) = Drops the table before re-creating it. Truncate = Same as delete, but deletes pages instead of rows. Does not take a WHERE clause, however.
pubid | uniqueidentifier | ID of the publication to which the current article belongs.
nickname | int | Nickname mapping for article identification.
column_tracking | int | Indicates whether column tracking is implemented for the article.
status | tinyint | Bitmap used to indicate the status of the article.
conflict_table | sysname | Name of the local table that contains the conflicting records for the current article. This table is supplied for information only, and its contents may be modified or deleted by custom conflict resolution routines or directly by the administrator.
creation_script | nvarchar(255) | Creation script for this article.
conflict_script | nvarchar(255) | Conflict script for this article.
article_resolver | nvarchar(255) | Custom row-level conflict resolver for this article.
ins_conflict_proc | sysname | Procedure used to write conflict to conflict_table.
insert_proc | sysname | Procedure used by the default conflict resolver to insert rows during synchronization.
update_proc | sysname | Procedure used by the default conflict resolver to update rows during synchronization.
schema_option | binary(8) | Indicates what is to be scripted out.
destination_object | sysname | Name of the table created at the Subscriber.
resolver_clsid | nvarchar(1000) | ID of the custom conflict resolver.
subset_filterclause | nvarchar(2000) | Filter clause for this article.
missing_col_count | int | Number of missing columns.
missing_cols | varbinary(128) | Bit map of missing columns.
columns | varbinary(128) | Reserved for future use.
resolver_info | sysname | Storage for additional information required by custom conflict resolvers.


sysmergepublications

Contains one row for each merge publication defined in the database. This table is stored in the published database.

Column name | Data type | Description
publisher | sysname | Name of the default server.
publisher_db | sysname | Name of the default Publisher database.
name | sysname | Name of the publication.
description | nvarchar(255) | Brief description of the publication.
retention | int | Retention period, expressed in days, for the entire publication set.
publication_type | tinyint | Indicates the publication is filtered: 0 = Not filtered 1 = Filtered
pubid | uniqueidentifier | Unique identification number for this publication; generated when the publication is added.
designmasterid | uniqueidentifier | Reserved for future use.
parentid | uniqueidentifier | Indicates the parent publication from which the current peer or subset publication was created (used for hierarchical publishing topologies).
sync_mode | tinyint | Synchronization mode of this publication: 0 = Native 1 = Character
allow_push | int | Indicates whether the publication allows push subscriptions.
allow_pull | int | Indicates whether the publication allows pull subscriptions.
allow_anonymous | int | Indicates whether the publication allows anonymous subscriptions.
centralized_ conflicts | int | Indicates whether the conflict records are stored at the Publisher.
status | tinyint | Reserved for future use.
snapshot_ready | tinyint | Indicates the snapshot of the publication is ready: 0 = Snapshot is ready for use. 1 = Snapshot is not ready for use.
enabled_for_ internet | bit | Indicates whether the synchronization files for the publication are exposed to the Internet, through FTP and other services.


sysmergeschemachange

Contains information about the last schema change. This table is stored in the published database.

Column name | Data type | Description
pubid | uniqueidentifier | ID of the publication.
artid | uniqueidentifier | ID of the article.
schemaversion | int | Number of the last schema change.
schemaguid | uniqueidentifier | Unique ID of the last schema.
schematype | int | Type of schema: 1 = Schema 2 = System schema 3 = Trigger script
schematext | nvarchar(255) | Name of the script file, or a command which includes a file name.


sysmergesubscriptions

Contains one row for each known Subscriber and is a local table at the Publisher. This table is stored in the published database.

Column name | Data type | Description
subid | uniqueidentifier | Unique identification number for Subscription.
partnerid | uniqueidentifier | ID of the partner to which it subscribes.
datasource_type | int | Type of data source: 0 = SQL Server 2 = Jet OLE DB
datasource_path | nvarchar(255) | If a Jet datasource, path to the .mdb file.
srvid | int | Contains the sysservers.srvguid and, with db_name, allows for the subscription to be identified in the local server.
db_name | sysname | Name of the subscribing database.
pubid | uniqueidentifier | Publication from which the current subscription was created.
status | tinyint | Contains a bitmap that indicates the status of the subscription: 1 = Inactive 2 = Subscribed 3 = Active 4 = SchemaMismatch 5 = SubscriptionTooOld 6 = SubscriptionOutOfSync
subscriber_type | int | Type of Subscriber: 1 = Global 2 = Local 3 = Anonymous
subscription_type | int | Type of subscription: 0 = Push 1 = Pull
priority | real | Specifies the subscription priority and allows the implementation of priority-based conflict resolution. 0.00 for all local or anonymous subscriptions.
sync_type | tinyint | Type of synchronization: 1 = Automatic 2 = No synchronization
description | nvarchar(255) | Brief description of the subscription.
login_name | sysname | Name of the user who created the subscription.
last_validated | datetime | Time of the last successful validation of Subscriber data.


sysmergesubsetfilters

Contains join filter information for partitioned articles. This table is stored in the published database.

Column name | Data type | Description
filtername | sysname | Name of the filter used to create the article.
join_filterid | int | ID of the object representing the join filter.
pubid | uniqueidentifier | ID of the publication.
artid | uniqueidentifier | ID of the article.
art_nickname | int | Nickname of the article.
join_tablename | sysname | Name of the table to join to determine if the row belongs.
join_nickname | int | Nickname of the table to join to determine if the row belongs.
join_unique_key | int | Indicates a join on a unique key: 0 = Not a unique key. 1 = A unique key.
join_filterclause | nvarchar(1000) | Filter clause used for the join.


sysmessages

Contains one row for each system error or warning that can be returned by Microsoft® SQL Server™. SQL Server displays the error description on the user’s screen.

Column name | Data type | Description
error | int | Unique error number.
severity | smallint | Severity level of the error.
dlevel | smallint | Reserved. For internal use only.
description | nvarchar(255) | Explanation of the error with placeholders for parameters.
mslangid | smallint | System message group ID.


sysnotifications

Contains one row for each notification.

Column name | Data type | Description
alert_id | int | ID of the alert.
operator_id | int | Operator ID to whom this notification should be sent.
notification_method | tinyint | Method of notification: 1 = E-mail 2 = Pager 4 = netsend 7 = All


sysobjects

Contains one row for each object (constraint, default, log, rule, stored procedure, and so on) created within a database. In tempdb only, this table includes a row for each temporary object.

Column name | Data type | Description
name | sysname | Object name.
Id | int | Object identification number.
xtype | char(2) | Object type. Can be one of these object types: C = CHECK constraint D = Default or DEFAULT constraint F = FOREIGN KEY constraint L = Log P = Stored procedure PK = PRIMARY KEY constraint (type is K) RF = Replication filter stored procedure S = System table TR = Trigger U = User table UQ = UNIQUE constraint (type is K) V = View X = Extended stored procedure
uid | smallint | User ID of owner object.
info | smallint | Reserved. For internal use only.
status | int | Reserved. For internal use only.
base_schema_ver | int | Count of changes in schema of a given object (incremented if a rule or default is added).
replinfo | int | Reserved. For use by replication.
parent_obj | int | Object identification number of parent object (for example, the table ID if a trigger or constraint).
crdate | datetime | Date the object was created.
ftcatid | smallint | Identifier of the full-text catalog for all user tables registered for full-text indexing, and 0 for all user tables not registered.
schema_ver | int | Version number that is incremented every time the schema for a table changes.
stats_schema_ver | int | Version number of the statistics.
type | char(2) | Object type. Can be one of these values: C = CHECK constraint D = Default or DEFAULT constraint F = FOREIGN KEY constraint K = PRIMARY KEY or UNIQUE constraint L = Log P = Stored procedure R = Rule RF = Replication filter stored procedure S = System table TR = Trigger U = User table V = View X = Extended stored procedure
userstat | smallint | Reserved.
sysstat | smallint | Internal status information.
indexdel | smallint | Index delete count (incremented if an index is deleted).
refdate | datetime | Reserved for future use.
version | int | Reserved for future use.
deltrig | int | Reserved.
instrig | int | Reserved.
updtrig | int | Reserved.
seltrig | int | Reserved.
category | int | Used for publication, constraints, and identity.
cache | smallint | Reserved.


sysoledbusers

Contains one row for each user and password mapping for the specified linked server. This table is stored in the master database.

Column name | Data type | Description
rmtsrvid | smallint | SID (security identification number) of the server.
rmtloginame | nvarchar(128) | Name of the remote login that loginsid maps to for linked rmtservid.
rmtpassword | nvarchar(128) | Encrypted password for the specified remote login in linked rmtsrvid.
loginsid | varbinary(85) | SID of the local login to be mapped.
status | smallint | If this value is 1, the mapping should use the user’s own credentials.
changedate | datetime | Date mapping information was last changed.


sysoperators

Contains one row for each operator.

Column name | Data type | Description
id | int | ID of the operator.
name | sysname | Name of the operator.
enabled | tinyint | Status of alert notifications (Boolean). If 1, this operator can receive notifications when an alert occurs.
email_address | nvarchar(100) | E-mail address for this operator.
last_email_date | int | Date this operator last received an e-mail alert notification.
last_email_time | int | Time of day this operator last received an e-mail alert notification.
pager_address | nvarchar(100) | Pager address for this operator.
last_pager_date | int | Date this operator last received a pager alert notification.
last_pager_time | int | Time of day this operator last received a pager alert notification.
weekday_pager_ start_time | int | Time of day on a weekday (Monday through Friday) after which this operator is available to receive a pager alert notification.
weekday_pager_ end_time | int | Time of day on a weekday (Monday through Friday) after which this operator is not available to receive a pager alert notification.
saturday_pager_ start_time | int | Time of day on Saturday after which this operator is available to receive a pager alert notification.
saturday_pager_ end_time | int | Time of day on Saturday after which this operator is not available to receive a pager alert notification.
sunday_pager_ start_time | int | Time of day on Sunday after which this operator is available to receive a pager alert notification.
sunday_pager_ end_time | int | Time of day on Sunday after which this operator is not available to receive a pager alert notification.
pager_days | tinyint | Bitmask that is the days of the week during which this operator is available to receive a pager alert notification.
netsend_address | nvarchar(100) | Reserved.
last_netsend_date | int | Date that the most recent network message was last sent to the specified operator ID.
last_netsend_time | int | Time that the most recent network message was last sent to the specified operator ID.
category_id | int | Reserved.


sysperfinfo

Contains a Microsoft® SQL Server™ representation of the internal performance counters that can be displayed through the Windows NT Performance Monitor.

Note The Windows NT Performance Monitor is available only when using Microsoft Windows NT® as the operating system.

Column name | Data type | Description
object_name | nchar(128) | Performance object name, such as SQL Server: Lock Manager or SQL Server: Buffer Manager.
counter_name | nchar(128) | Name of the performance counter within the object, such as Page Requests or Locks Requested.
instance_name | nchar(128) | Named instance of the counter. For example, there are counters maintained for each type of lock, such as Table, Page, Key, and so on. The instance name distinguishes between similar counters.
cntr_value | int | Actual counter value. In most cases, this will be a level or monotonically increasing counter that counts occurrences of the instance event.
cntr_type | int | Type of counter as defined by the Windows NT performance architecture.


syspermissions

Contains information about permissions that have been granted and denied to users, groups, and roles in the database. This table is stored in each database.

Column name | Data type | Description
id | int | ID of the object for object permissions; 0 for statement permissions.
grantee | smallint | ID of the user, group, or role affected by the permission.
grantor | smallint | ID of the user, group, or role that granted or revoked the permission.
actadd | smallint | For internal use only.
actmod | smallint | For internal use only.
seladd | varbinary(4000) | For internal use only.
selmod | varbinary(4000) | For internal use only.
updadd | varbinary(4000) | For internal use only.
updmod | varbinary(4000) | For internal use only.
refadd | varbinary(4000) | For internal use only.
refmod | varbinary(4000) | For internal use only.


sysprocesses

The sysprocesses table holds information about processes running on Microsoft® SQL Server™. These processes can be client processes or system processes. sysprocesses is stored only in the master database.

Column name | Data type | Description
spid | smallint | SQL Server process ID.
kpid | smallint | Microsoft Windows NT® thread ID.
blocked | smallint | Process ID (spid) of a blocking process.
waittype | binary(2) | Reserved.
waittime | int | Current wait time in milliseconds. Is 0 when the process is not waiting.
lastwaittype | nchar(32) | A string indicating the name of the last or current wait type.
waitresource | nchar(32) | Textual representation of a lock resource.
dbid | smallint | ID of the database currently being used by the process.
uid | smallint | ID of the user who executed the command.
cpu | int | Cumulative CPU time for the process. The entry is updated only for processes performed on behalf of Transact-SQL statements executed when SET STATISTICS TIME ON has been activated in the same session. The cpu column is updated when a query has been executed with SET STATISTICS TIME ON. 0 is returned when SET STATISTICS TIME is OFF.
physical_io | int | Cumulative disk reads and writes for the process.
memusage | int | Number of pages in the procedure cache that are currently allocated to this process. A negative number indicates that the process is freeing memory allocated by another process.
login_time | datetime | Time at which a client process logged into the server. For system processes, the time at which SQL Server startup occurred is stored.
last_batch | datetime | Last time a client process executed a remote stored procedure call or an EXECUTE statement. For system processes, the time at which SQL Server startup occurred is stored.
ecid | smallint | Execution context ID used to uniquely identify the subthreads operating on behalf of a single process.
open_tran | smallint | Number of open transactions for the process.
status | nchar(30) | Process ID status (for example, running, sleeping, and so on).
sid | binary(85) | Globally unique identifier (GUID) for the user.
hostname | nchar(128) | Name of the workstation.
program_name | nchar(128) | Name of the application program.
hostprocess | nchar(8) | Workstation process ID number.
cmd | nchar(16) | Command currently being executed.
nt_domain | nchar(128) | Windows NT domain for the client (if using Windows NT Authentication) or a trusted connection.
nt_username | nchar(128) | Windows NT username for the process (if using Windows NT Authentication) or a trusted connection.
net_address | nchar(12) | Assigned unique identifier for the network interface card on each user’s workstation. When the user logs in, this identifier is inserted in the net_address column.
net_library | nchar(12) | Column in which the client’s network library is stored. Every client process comes in on a network connection. Network connections have a network library associated with them that allows them to make the connection.
loginame | nchar(128) | Login name.
suid | smallint | Server user ID of user who executed command.


sysprotects

Contains information about permissions that have been applied to security accounts with the GRANT and DENY statements. This table is stored in each database.

Column name | Data type | Description
id | int | ID of object to which these permissions apply.
uid | smallint | ID of user or group to which these permissions apply.
action | tinyint | Can have one of these permissions: 26 = REFERENCES 193 = SELECT 195 = INSERT 196 = DELETE 197 = UPDATE 198 = CREATE TABLE 203 = CREATE DATABASE 207 = CREATE VIEW 222 = CREATE PROCEDURE 224 = EXECUTE 228 = BACKUP DATABASE 233 = CREATE DEFAULT 235 = BACKUP LOG 236 = CREATE RULE
protecttype | tinyint | Can have these values: 204 = GRANT_W_GRANT 205 = GRANT 206 = REVOKE
columns | varbinary(4000) | Bitmap of columns to which these SELECT or UPDATE permissions apply. Bit 0 indicates all columns; bit 1 means permissions apply to that column and NULL means no information.
grantor | smallint | User ID of the user who issued the GRANT or REVOKE permissions.


syspublications

Contains one row for each publication defined in the database. This table is stored in the published database.

Column name | Data type | Description
description | nvarchar(255) | Descriptive entry for the publication.
name | sysname | Unique name associated with the publication.
pubid | int | Identity column providing a unique ID for the publication.
repl_freq | tinyint | Replication frequency: 0 = Transaction based 1 = Scheduled table refresh
status | tinyint | Status: 0 = Inactive 1 = Active
sync_method | tinyint | Synchronization method: 0 = Native bulk copy program (bcp utility) 1 = Character bulk copy
snapshot_jobid | binary(16) | Scheduled task ID.
independent_ agent | bit | Publication attribute.
immediate_sync | bit | Indicates whether the synchronization files are created or re-created each time the Snapshot Agent runs.
enabled_for_ internet | bit | Indicates whether the synchronization files for the publication are exposed to the Internet through FTP and other services.
allow_push | bit | Indicates whether push subscriptions are allowed on the publication.
allow_pull | bit | Indicates whether pull subscriptions are allowed on the publication.
allow_ anonymous | bit | Indicates whether anonymous subscriptions are allowed on the publication.
immediate_ sync_ready | bit | Indicates whether the Snapshot Agent is completed one time for the immediate update publication. It has no definition for a non- immediate update publication.
allow_sync_tran | bit | Publication attribute.
autogen_sync_ procs | bit | Publication attribute.
retention | int | Retention period, in days.


sysreferences

Contains mappings of FOREIGN KEY constraint definitions to the referenced columns. This table is stored in each database.

Column name | Data type | Description
constid | int | ID of the FOREIGN KEY constraint
fkeyid | int | ID of the referencing table
rkeyid | int | ID of the referenced table
rkeyindid | smallint | Index ID of the unique index on the referenced table covering the referenced key-columns
keycnt | smallint | Number of columns in the key
forkeys | varbinary(32) | For internal use only
refkeys | varbinary(32) | For internal use only
fkeydbid | smallint | Reserved
rkeydbid | smallint | Reserved
fkey1 | smallint | Column ID of the referencing column
fkey2 | smallint | Column ID of the referencing column
fkey3 | smallint | Column ID of the referencing column
fkey4 | smallint | Column ID of the referencing column
fkey5 | smallint | Column ID of the referencing column
fkey6 | smallint | Column ID of the referencing column
fkey7 | smallint | Column ID of the referencing column
fkey8 | smallint | Column ID of the referencing column
fkey9 | smallint | Column ID of the referencing column
fkey10 | smallint | Column ID of the referencing column
fkey11 | smallint | Column ID of the referencing column
fkey12 | smallint | Column ID of the referencing column
fkey13 | smallint | Column ID of the referencing column
fkey14 | smallint | Column ID of the referencing column
fkey15 | smallint | Column ID of the referencing column
fkey16 | smallint | Column ID of the referencing column
rkey1 | smallint | Column ID of the referencing column
rkey2 | smallint | Column ID of the referencing column
rkey3 | smallint | Column ID of the referencing column
rkey4 | smallint | Column ID of the referencing column
rkey5 | smallint | Column ID of the referencing column
rkey6 | smallint | Column ID of the referencing column
rkey7 | smallint | Column ID of the referencing column
rkey8 | smallint | Column ID of the referencing column
rkey9 | smallint | Column ID of the referencing column
rkey10 | smallint | Column ID of the referencing column
rkey11 | smallint | Column ID of the referencing column
rkey12 | smallint | Column ID of the referencing column
rkey13 | smallint | Column ID of the referencing column
rkey14 | smallint | Column ID of the referencing column
rkey15 | smallint | Column ID of the referencing column
rkey16 | smallint | Column ID of the referencing column


sysremotelogins

Contains one row for each remote user who is allowed to call remote stored procedures on Microsoft® SQL Server™.

Column name | Data type | Description
remoteserverid | smallint | Remote server identification.
remoteusername | nvarchar(128) | User’s login name on a remote server.
suid | smallint | Local server user ID.
status | smallint | Bitmap of options.
sid | varbinary(85) | Microsoft Windows NT® user security ID.
changedate | datetime | Date and time the remote user was added.


sysreplicationalerts

Contains additional information about the conditions causing a replication alert to fire. This table is stored in the master database.

Column name | Data type | Description
alert_id | int | ID of the alert.
status | int | User-defined value. Can be: 0 = Unserviced 1 = Serviced
agent_type | int | Type of agent: 1 = Snapshot Agent 2 = Log Reader Agent 3 = Distribution Agent 4 = Merge Agent
agent_id | int | Agent ID from the tables MSsnapshot_agent, MSlogreader_agent, MSdistribution_agent, or MSmerge_agent.
error_id | int | ID of the error stored in MSrepl_errors.
alert_error_code | int | Message ID of the alert raised when logging this record.
time | datetime | Time the record was inserted.
publisher | sysname | Name of the Publisher associated with the agent that fired this alert.
publisher_db | sysname | Publisher database associated with the agent that fired this alert.
publication | sysname | Publication associated with the agent that fired this alert.
publication_type | int | Type of publication: 0 = Snapshot 1 = Transactional 2 = Merge
subscriber | sysname | Name of the Subscriber associated with the agent that fired this alert.
subscriber_db | sysname | Name of the Subscriber database associated with the agent that fired this alert.
article | sysname | Name of the article associated with the agent that fired this alert.
destination_object | sysname | Name of the subscription table associated with the alert.
source_object | sysname | Name of the published table associated with the alert.
alert_error_text | ntext | Text of the alert.


sysservers

Contains one row for each server that Microsoft® SQL Server™ can access as an OLE DB data source.

Column name | Data type | Description
srvid | smallint | ID (for local use only) of the remote server.
srvstatus | smallint | Bitmap of options.
srvname | sysname | Name of the server.
srvproduct | nvarchar(128) | Product name for the remote server.
providername | nvarchar(128) | OLE DB provider name for access to this server.
datasource | nvarchar(4000) | OLE DB data source value.
location | nvarchar(4000) | OLE DB location value.
providerstring | nvarchar(4000) | OLE DB provider string value.
schemadate | datetime | Date this row was last updated.
topologyx | int | Used by the SQL Server Enterprise Manager server topology diagram.
topologyy | int | Used by the SQL Server Enterprise Manager server topology diagram.
catalog | sysname | Catalog that is used when making a connection to an OLE DB provider.
srvnetname | char | Reserved (currently the same as the srvname).


syssubscriptions

Contains one row for each subscription in the database. This table is stored in the master database and the published database.

Column name | Data type | Description
artid | int | Unique ID of an article.
srvid | smallint | Server ID of the Subscriber.
dest_db | sysname | Name of the destination database.
status | tinyint | Status: 0 = Inactive 1 = Subscribed 2 = Active
sync_type | tinyint | Type of synchronization: 0 = Manual 1 = Automatic 2 = None
login_name | sysname | Login name used when adding the subscription.
subscription_type | int | Type of subscription: 0 = Push 1 = Pull
distribution_jobid | binary(16) | Job ID of the Distribution Agent.
timestamp | timestamp | Time subscription was created.
update_mode | tinyint | Update mode: 0 = Read only 1 = Immediate-updating
autogen_sync_ triggers | bit | Subscription attribute.


systargetservergroupmembers

Records which target servers are currently enlisted in this multiserver group.

Column name | Data type | Description
servergroup_id | int | Server group ID
server_id | int | Server ID


systargetservergroups

Records which target server groups are currently enlisted in this multiserver environment.

Column name | Data type | Description
servergroup_id | int | Server group ID
name | sysname | Server group name


systargetservers

Records which target servers are currently enlisted in this multiserver operation domain.

Column name | Data type | Description
server_id | int | Server ID.
server_name | nvarchar(30) | Server name.
location | nvarchar(200) | Location of the specified target server.
time_zone_ adjustment | int | Time adjustment interval, in hours, from Greenwich mean time (GMT).
enlist_date | datetime | Date and time that the specified target server was enlisted.
last_poll_date | datetime | Date and time that the specified target server last polled the multiserver’s sysdownloadlist system table for jobs to run.
status | int | Status of the target server: 1 = Normal 2 = Re-sync Pending 4 = Suspected Offline
local_time_at_last_poll | datetime | Date and time the target server was last polled for job operations.
enlisted_by_nt_ user | nvarchar(100) | Username of the person executing sp_msx_enlist on the target server.
poll_internal | int | Number of seconds to elapse before the target server polls the master server for new download instructions.


systaskids

Contains a mapping of tasks created in earlier versions of Microsoft® SQL Server™ to SQL Server Enterprise Manager jobs in the current version. This table is stored in the msdb database.

Column name | Data type | Description
task_id | int | ID of the task
job_id | uniqueidentifier | ID of the job to which the task is mapped


systypes

Contains one row for each system-supplied and each user-defined data type. This table is stored in each database.

These are the system-supplied data types and their ID numbers.

Column name | Data type | Description
name | sysname | Data type name.
xtype | tinyint | Physical storage type.
status | tinyint | For internal use only.
xusertype | smallint | Extended user type.
length | smallint | Physical length of data type.
xprec | tinyint | Internal precision, as used by server. (Not to be used in queries.)
xscale | tinyint | Internal scale, as used by server. (Not to be used in queries.)
tdefault | int | ID of stored procedure that contains integrity checks for this data type.
domain | int | ID of stored procedure that contains integrity checks for this data type.
uid | smallint | User ID of data type creator.
reserved | smallint | For internal use only.
usertype | smallint | User type ID.
variable | bit | Variable-length data type is 1; otherwise, 0.
allownulls | bit | Indicates the default nullability for this data type. If nullability is specified with CREATE or ALTER TABLE, then that value overrides the default nullability for this data type.
type | tinyint | Physical storage data type.
printfmt | varchar(255) | Reserved.
prec | smallint | Level of precision for this data type.
scale | tinyint | Scale for this data type (based on precision).


sysusers

Contains one row for each Microsoft® Windows NT® user, Windows NT group, Microsoft SQL Server™ user, or SQL Server role in the database.

Column name | Data type | Description
uid | smallint | User ID, unique in this database. 1 is the database owner.
status | smallint | For internal use only.
name | sysname | Username or group name, unique in this database.
sid | varbinary(85) | Security identifier for this entry.
roles | varbinary(2048) | For internal use only.
createdate | datetime | Date the account was added.
updatedate | datetime | Date the account was last changed.
altuid | smallint | For internal use only.
password | varbinary(256) | For internal use only.
suid | smallint | Server user ID, copied from syslogins. A suid of 1 is the system administrator; -1 is a guest account.
gid | smallint | Group ID to which this user belongs. If uid = gid, this entry defines a group. The public role has a suid equal to -2. All other roles have a suid equal to -gid.
environ | varchar(255) | Reserved.
hasdbaccess | int | 1, if the account has database access.
islogin | int | 1, if the account is a Windows NT group, Windows NT user, or SQL Server user with a login account.
isntname | int | 1, if the account is a Windows NT group or Windows NT user.
isntgroup | int | 1, if the account is a Windows NT group.
isntuser | int | 1, if the account is a Windows NT user.
issqluser | int | 1, if the account is a SQL Server user.
isaliased | int | 1, if the account is aliased to another user.
issqlrole | int | 1, if the account is a SQL Server role.
isapprole | int | 1, if the account is an application role.


SYSTEM_USER

Allows a system-supplied value for the current system username to be inserted into a table when no default value is specified.

Syntax

SYSTEM_USER

Remarks

Use the SYSTEM_USER niladic function with DEFAULT constraints in either the CREATE TABLE or ALTER TABLE statements, or use as any standard function.

If the current user is logged in to Microsoft® SQL Server™ using Microsoft Windows NT® Authentication, SYSTEM_USER returns the Windows NT login identification name, for example, DOMAIN\user_login_name. However, if the current user is logged in to SQL Server using SQL Server Authentication, SYSTEM_USER returns the SQL Server login identification name, for example, sa for a user logged in as sa.

Examples
A. Use SYSTEM_USER to return the current system username

This example declares a char variable, puts the current value of SYSTEM_USER into the variable, and then prints the variable.

DECLARE @sys_usr char(30)

SET @sys_usr = SYSTEM_USER

SELECT 'The current system user is: '+ @sys_usr

GO

Here is the result set:

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

The current system user is: sa

(1 row(s) affected)

B. Use SYSTEM_USER with DEFAULT constraints

This example creates a table using SYSTEM_USER as a DEFAULT constraint for the receptionist for a patient row.

USE pubs

GO

CREATE TABLE appointments2

(

 patient_id int IDENTITY(2000, 1) NOT NULL,

 doctor_id  int NOT NULL,

 appt_date datetime NOT NULL DEFAULT GETDATE(),

 receptionist varchar(30) NOT NULL DEFAULT SYSTEM_USER

)

GO

INSERT appointments2 (doctor_id)

VALUES (151)

INSERT appointments2 (doctor_id, appt_date)

VALUES (293, '5/15/98')

INSERT appointments2 (doctor_id, appt_date)

VALUES (27882, '6/20/98')

INSERT appointments2 (doctor_id)

VALUES (21392)

INSERT appointments2 (doctor_id, appt_date)

VALUES (24283, '11/03/98')

GO

This is the query to select all the information from the appointments2 table:

SELECT *

FROM appointments2

ORDER BY doctor_id

GO

Here is the result set:

patient_id  doctor_id   appt_date                receptionist

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

2000        151         Mar 4 1998 10:36AM       sa

2001        293         May 15 1998 12:00AM      sa

2003        21392       Mar 4 1998 10:36AM       sa

2004        24283       Nov 3 1998 12:00AM       sa

2002        27882       Jun 20 1998 12:00AM      sa

(5 row(s) affected)

See Also
ALTER TABLE | SESSION_USER
CREATE TABLE | USER
CURRENT_TIMESTAMP | System Functions
CURRENT_USER |


TAN

Returns the tangent of the input expression.

Syntax

TAN(float_expression)

Arguments
float_expression
Is an expression of type float or real, interpreted as number of radians.
Return Types

float

Examples

This example returns the tangent of PI()/2.

SELECT TAN(PI()/2)

Here is the result set:

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

1.6331778728383844E+16

See Also

Mathematical Functions


text

For information about the text data type, see ntext, text, and image.

See Also
Data Types


TEXTPTR

Returns the text-pointer value that corresponds to a text, ntext, or image column in varbinary format. The text pointer is checked to ensure that it points to the first text page. The retrieved text pointer value can be used in READTEXT, WRITETEXT, and UPDATE statements.

Syntax

TEXTPTR(column)

Arguments
column
Is the text, ntext, or image column to be used.
Return Types

varbinary

Remarks

If a text, ntext, or image column has not been initialized by an INSERT or UPDATE statement, TEXTPTR returns a null pointer. Use TEXTVALID to check whether a text pointer exists. You cannot use UPDATETEXT, WRITETEXT, or READTEXT without a valid text pointer.

These functions and statements are also useful with text, ntext, and image data.

Function or statement | Description
PATINDEX('%pattern%', expression) | Returns the character position of a given character string in text or ntext columns.
DATALENGTH(expression) | Returns the length of data in text, ntext, and image columns.
SET TEXTSIZE | Returns the limit, in bytes, of the text, ntext, or image data to be returned with a SELECT statement.
SUBSTRING(text_column, start, length) | Returns a varchar string specified by the given start offset and length. The length should be less than 8 KB.

Examples
A. Use TEXTPTR

This example uses the TEXTPTR function to locate the image column logo associated with New Moon Books in the pub_info table of the pubs database. The text pointer is put into a local variable @ptrval.

USE pubs

GO

DECLARE @ptrval varbinary(16)

SELECT @ptrval = TEXTPTR(logo)

FROM pub_info pr, publishers p

WHERE p.pub_id = pr.pub_id

    AND p.pub_name = 'New Moon Books'

GO

B. Return text data

This example selects the pub_id column and the 16-byte text pointer of the pr_info column from the pub_info table.

USE pubs

GO

SELECT pub_id, TEXTPTR(pr_info)

FROM pub_info

ORDER BY pub_id

GO

Here is the result set:

pub_id

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

0736   0x6c0000000000feffb801000001000100

0877   0x6d0000000000feffb801000001000300

1389   0x6e0000000000feffb801000001000500

1622   0x700000000000feffb801000001000900

1756   0x710000000000feffb801000001000b00

9901   0x720000000000feffb801000001000d00

9952   0x6f0000000000feffb801000001000700

9999   0x730000000000feffb801000001000f00

(8 row(s) affected)

This example shows how to return the first 8,000 bytes of text without using TEXTPTR.

USE pubs

GO

SET TEXTSIZE 8000

SELECT pub_id, pr_info

FROM pub_info

ORDER BY pub_id

GO

Here is the result set:

pub_id pr_info

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

0736   New Moon Books (NMB) has just released another top ten publication. With the latest publication this makes NMB the hottest new publisher of the year!

0877   This is sample text data for Binnet & Hardley, publisher 0877 in the pubs database. Binnet & Hardley is located in Washington, D.C.

This is sample text data for Binnet & Hardley, publisher 0877 in the pubs database. Binnet & Hardley is located in Washi

1389   This is sample text data for Algodata Infosystems, publisher 1389 in the pubs database. Algodata Infosystems is located in Berkeley, California.

…

9999   This is sample text data for Lucerne Publishing, publisher 9999 in the pubs database. Lucerne publishing is located in Paris, France.

This is sample text data for Lucerne Publishing, publisher 9999 in the pubs database. Lucerne publishing is located in

(8 row(s) affected)

C. Return specific text data

This example locates the text column (pr_info) associated with pub_id 0736 in the pub_info table of the pubs database. It first declares the local variable @val. The text pointer (a long binary string) is then put into @val and supplied as a parameter to the READTEXT statement, which returns 10 bytes starting at the fifth byte (offset of 4).

USE pubs

GO

DECLARE @val varbinary(16)

SELECT @val = TEXTPTR(pr_info)

FROM pub_info

WHERE pub_id = '0736'

READTEXT pub_info.pr_info @val 4 10

GO

Here is the result set:

(1 row(s) affected)

pr_info

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

Moon Books

See Also
DATALENGTH | UPDATETEXT
PATINDEX | WRITETEXT
READTEXT | Text and Image Functions
SET TEXTSIZE |


TEXTVALID

A text, ntext, or image function that checks whether a given text pointer is valid.

Syntax

TEXTVALID('table.column', text_ ptr)

Arguments
table
Is the name of the table to be used.
column
Is the name of the column to be used.
text_ptr
Is the text pointer to be checked.
Return Types

int

Remarks

Returns 1 if the pointer is valid and 0 if the pointer is invalid. Note that the identifier for the text column must include the table name. If a text, ntext, or image column has not been initialized by an INSERT or UPDATE statement, TEXTPTR returns a null pointer. Use TEXTVALID to check whether a text pointer exists. You cannot use UPDATETEXT, WRITETEXT, or READTEXT without a valid text pointer.

These functions and statements are also useful with text, ntext, and image data.

Function or statement | Description
PATINDEX(‘%pattern%’, expression) | Returns the character position of a given character string in text and ntext columns.
DATALENGTH(expression) | Returns the length of data in text, ntext, and image columns.
SET TEXTSIZE | Returns the limit, in bytes, of the text, ntext, or image data to be returned with a SELECT statement.

Examples

This example reports whether a valid text pointer exists for each value in the logo column of the pub_info table.

USE pubs

GO

SELECT pub_id, 'Valid (if 1) Text data'

    = TEXTVALID ('pub_info.logo', TEXTPTR(logo))

FROM pub_info

ORDER BY pub_id

GO

Here is the result set:

pub_id Valid (if 1) Text data

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

0736   1

0877   1

1389   1

1622   1

1756   1

9901   1

9952   1

9999   1

(8 row(s) affected)

See Also
DATALENGTH | TEXTPTR
PATINDEX | Text and Image Functions
SET TEXTSIZE |


timestamp

A database-wide unique number. The storage size is 8 bytes.

Remarks

A table can have only one timestamp column. The value in the timestamp column is updated every time a row containing a timestamp column is inserted or updated. This property makes a timestamp column a poor candidate for keys, especially primary keys. Any update made to the row changes the timestamp value, thereby changing the key value. If the column is in a primary key, the old key value is no longer valid, and foreign keys referencing the old value are no longer valid. If the table is referenced in a dynamic cursor, all updates change the position of the rows in the cursor. If the column is in an index key, all updates to the data row also generate updates of the index.

The value of a timestamp column is unique within a database.

A nonnullable timestamp column is semantically equivalent to a binary(8) column. A nullable timestamp column is semantically equivalent to a varbinary(8) column.

See Also
ALTER TABLE | DELETE
CAST and CONVERT | INSERT
CREATE TABLE | SET @local_variable
Data Types | UPDATE
DECLARE @local_variable |


tinyint

For information about the tinyint data type, see int, smallint, and tinyint.

See Also
Data Types


Trace Flags

Trace flags are used to temporarily set specific server characteristics or to switch off a particular behavior. For example, if trace flag 8783 is set when Microsoft® SQL Server™ starts, SQL Server honors the SET ROWCOUNT ON statement for all DELETE, INSERT, and UPDATE statements. Trace flags are often used to diagnose performance issues or to debug stored procedures or complex computer systems.

These trace flags are available in Microsoft® SQL Server™.

Trace flag | Description
106 | Disables line number information for syntax errors.
107 | Interprets numbers with a decimal point as float instead of decimal.
206 | Provides backward compatibility for the SETUSER statement. For more information, see SETUSER.
237 | Disables the requirement for REFERENCES permissions to create a foreign key on a table that is not owned by the key creator, and, when disabled, ensures SQL-92 standard behavior. When enabled, this flag needs only SELECT permissions to ensure SQL Server behavior.
243 Provides backward compatibility for nullability behavior. When set, SQL Server has the same nullability violation behavior as that of a version 4.2 server:

· Processing of the entire batch is terminated if the nullability error (inserting NULL into a NOT NULL field) can be detected at compile time.

· Processing of the offending row is skipped, but the command continues if the nullability violation is detected at run time.

The behavior of SQL Server is now more consistent because nullability checks are made at run time and a nullability violation results in the command terminating and the batch or transaction process continuing.

244 | Disables checking for allowed interim constraint violations. By default, SQL Server checks for and allows interim constraint violations. An interim constraint violation is caused by a change that removes the violation such that the constraint is met, all within a single statement and transaction. SQL Server checks for interim constraint violations for self-referencing DELETE statements, INSERT statements based on a SELECT, and multirow UPDATE statements. This checking requires more work tables. With this trace flag you can disallow interim constraint violations, thus requiring fewer work tables.
260 | Prints versioning information about extended stored procedure dynamic-link libraries (DLLs).
325 | Prints information about the cost of using a nonclustered index or a sort to process an ORDER BY clause.
326 | Prints information about the estimated and actual cost of sorts.
330 | Enables full output when using the SET SHOWPLAN option, which gives detailed information about joins.
506 Enforces SQL-92 standards regarding null values for comparisons between variables and parameters. Any comparison of variables and parameters that contain a NULL always results in a NULL.

This flag is disabled if ANSI_NULLS is enabled with a setting of TRUE.

1204 | Returns the type of locks participating in the deadlock and the current command affected.
1205 | Returns more detailed information about the command being executed at the time of a deadlock.
1609 | Turns on the unpacking and checking of remote procedure call (RPC) information with the execution of sp_sqlexec in Open Data Services. Used only when applications depend on the old behavior. The application should be changed to EXECUTE sql_string rather than sp_sqlexec.
1704 | Prints information when a temporary table is created or dropped.
2701 | Sets the @@ERROR system function to 50000 for RAISERROR messages with severity levels of 10 or less. When disabled, sets the @@ERROR system function to 0 for RAISERROR messages with severity levels of 10 or less.
3205 | By default, if a tape drive supports hardware compression, either the DUMP or BACKUP statement uses it. With this trace flag, you can disable hardware compression for tape drivers. This is useful when you want to exchange tapes with other sites or tape drives that do not support compression.
3604 | Sends trace output to the client. Used only when setting trace flags with DBCC TRACEON and DBCC TRACEOFF.
3605 | Sends trace output to the error log. (If you start SQL Server from the command prompt, the output also appears on the screen.)
3640 | Eliminates the sending of DONE_IN_PROC messages to the client for each statement in a stored procedure. This is similar to the session setting of SET NOCOUNT, but when set as a trace flag, every client session is handled this way.
4022 | Bypasses automatically started procedures.
4030 | Prints both a byte and ASCII representation of the receive buffer. Used when you want to see what queries a client is sending to SQL Server. You can use this trace flag if you experience a protection violation and want to determine which statement caused it. Typically, you can set this flag globally or use SQL Server Enterprise Manager. You can also use DBCC INPUTBUFFER.
4031 | Prints both a byte and ASCII representation of the send buffers (what SQL Server sends back to the client). You can also use DBCC OUTPUTBUFFER.
4032 | Prints only an ASCII representation of the receive buffer. Usually used in place of trace flag 4030 (if trace output speed is important) when you want to see what queries a client is sending to SQL Server.
7501 | Available only in Microsoft SQL Server 6.5 and earlier versions. Dynamic cursors are used by default on forward-only cursors. Dynamic cursors are faster than in earlier versions and no longer require unique indexes. This flag disables the dynamic cursor enhancements and reverts to version 6.0 behavior.
7502 | Available only in Microsoft SQL Server 6.5 and earlier versions. Disables the caching of cursor plans for extended stored procedures.
7505 | Enables version 6.x handling of return codes when calling dbcursorfetchex and the resulting cursor position follows the end of the cursor result set.
8783 | Allows DELETE, INSERT, and UPDATE statements to honor the SET ROWCOUNT ON setting when enabled.

Examples
A. Set trace flags using DBCC TRACEON

This example turns on trace flag 8783 by using DBCC TRACEON.

DBCC TRACEON (8783)

B. Set trace flags at the command prompt

This examples turns on trace flag 8783 at the command prompt.

sqlservr /dc:\mssql7\data\master.dat /T8783

Data Types | EXECUTE
DBCC INPUTBUFFER | SELECT
DBCC OUTPUTBUFFER | SET NOCOUNT
DBCC TRACEOFF | sp_dboption
DBCC TRACEON |


Transactions

A transaction is a single unit of work. If a transaction is successful, all of the data modifications made during the transaction are committed and become a permanent part of the database. If a transaction encounters errors and must be canceled or rolled back, then all of the data modifications are erased.

Microsoft® SQL Server™ operates in three transaction modes:

Autocommit transactions
Each individual statement is a transaction.
Explicit transactions
Each transaction is explicitly started with the BEGIN TRANSACTION statement and explicitly ended with a COMMIT or ROLLBACK statement.
Implicit transactions
A new transaction is implicitly started when the prior transaction completes, but each transaction is explicitly completed with a COMMIT or ROLLBACK statement.
See Also
BEGIN DISTRIBUTED TRANSACTION | ROLLBACK WORK
BEGIN TRANSACTION | SAVE TRANSACTION
COMMIT TRANSACTION | SET IMPLICIT_TRANSACTIONS
COMMIT WORK | @@TRANCOUNT
ROLLBACK TRANSACTION |


TRIGGER_NESTLEVEL

Returns the number of triggers executed for the UPDATE, INSERT, or DELETE statement that fired the trigger. TRIGGER_NESTLEVEL is used in triggers to determine the current level of nesting.

Syntax

TRIGGER_NESTLEVEL( [ object_id ] )

Arguments
object_id
Is the object ID of a trigger. If object_id is specified, the number of times the specified trigger has been executed for the statement is returned. If object_id is not specified, the number of times all triggers have been executed for the statement is returned.

When object_id is omitted (this is different from a null value) TRIGGER_NESTLEVEL returns the number of triggers on the call stack, including itself. Omission of object_id can occur when a trigger executes commands causing another trigger to be fired or creates a succession of firing triggers.

Remarks

TRIGGER_NESTLEVEL returns 0 if it is executed outside of a trigger and object_id is not NULL.

TRIGGER_NESTLEVEL optionally receives an object ID as its argument. When object_id is explicitly specified as NULL or an invalid object id is referenced, a value of NULL is returned regardless of whether TRIGGER_NESTLEVEL was used within or external to a trigger.

Examples
A. Test nesting level of a specific trigger

IF ( (SELECT trigger_nestlevel( object_ID('xyz') ) ) > 5 )

    RAISERROR('Trigger xyz nested more than 5 levels.',16,-1)

B. Test nesting level of all triggers executed

IF ( (SELECT trigger_nestlevel() ) > 5 )

    RAISERROR

        ('This statement nested over 5 levels of triggers.',16,-1)

See Also

CREATE TRIGGER


TRUNCATE TABLE

Removes all rows from a table without logging the individual row deletes.

Syntax

TRUNCATE TABLE name

Arguments
name
Is the name of the table to truncate or remove all rows from.
Remarks

TRUNCATE TABLE is functionally identical to DELETE statement with no WHERE clause: both remove all rows in the table. But TRUNCATE TABLE is faster and uses fewer system and transaction log resources than DELETE.

The DELETE statement removes rows one at a time and records an entry in the transaction log for each deleted row. TRUNCATE TABLE removes the data by deallocating the data pages used to store the table’s data, and only the page deallocations are recorded in the transaction log. This means that DELETE statements can be rolled back, but TRUNCATE TABLE cannot.

TRUNCATE TABLE removes all rows from a table, but the table structure and its columns, constraints, indexes and so on remain. The counter used by an identity for new rows is reset to the seed for the column. If you want to retain the identity counter, use DELETE instead. If you want to remove table definition and its data, use the DROP TABLE statement.

You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint; instead, use DELETE statement without a WHERE clause. Because TRUNCATE TABLE is not logged, it cannot activate a trigger.

Examples

This example removes all data from the authors table.

TRUNCATE TABLE authors

Permissions

TRUNCATE TABLE permissions default to the table owner and are not transferable.

See Also
DELETE DROP TABLE


TYPEPROPERTY

Returns information about a data type.

Syntax

TYPEPROPERTY( type, property )

Arguments
type
Is the name of the data type.
property
Is the type of information to be returned for the data type, and can be one of these values.

Property Description Value returned
Precision Precision for the data type. The number of digits or characters.

NULL = Data type not found.
Scale Scale for the data type. The number of decimal places for the
data type.

NULL = Data type is not numeric or
not found.
AllowsNull Data type allows null values. 1 = True
0 = False
NULL = Data type not found.
UsesAnsiTrim ANSI padding setting was ON when the data type was created. 1 = True
0 = False
NULL = Data type not found, or it is
not a binary or string data type.

Return Types

int

Example

This example returns the precision or number of digits for the integer data type.

SELECT TYPEPROPERTY( 'tinyint', 'PRECISION')

See Also
COLUMNPROPERTY | Metadata Functions
OBJECTPROPERTY |


UNICODE

Returns the integer value, as defined by the Unicode standard, for the first character of the input expression.

Syntax

UNICODE('ncharacter_expression')

Arguments
'ncharacter_expression'
Is an nchar or nvarchar expression.
Return Types

int

Examples
A. Use UNICODE and NCHAR

This example uses the UNICODE and NCHAR functions to print the UNICODE value of the first character of the Åkergatan 24-character string, and to print the actual first character, Å.

DECLARE @nstring nchar(12)

SET @nstring = N'Åkergatan 24'

SELECT UNICODE(@nstring), NCHAR(UNICODE(@nstring))

Here is the result set:

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

197         Å

B. Use SUBSTRING, UNICODE, and CONVERT

This example uses the SUBSTRING, UNICODE, and CONVERT functions to print the character number, the Unicode character, and the UNICODE value of each of the characters in the string Åkergatan 24.

-- The @position variable holds the position of the character currently

-- being processed. The @nstring variable is the Unicode character

-- string to process.

DECLARE @position int, @nstring nchar(12)

-- Initialize the current position variable to the first character in

-- the string.

SET @position = 1

-- Initialize the character string variable to the string to process.

-- Notice that there is an N before the start of the string, which

-- indicates that the data following the N is Unicode data.

SET @nstring = N'Åkergatan 24'

-- Print the character number of the position of the string you are at,

-- the actual Unicode character you are processing, and the UNICODE

-- value for this particular character.

PRINT 'Character #' + ' ' + 'Unicode Character' + ' ' + 'UNICODE Value'

WHILE @position <= DATALENGTH(@nstring)

-- While these are still characters in the character string,

    BEGIN

    SELECT @position,

        CONVERT(char(17), SUBSTRING(@nstring, @position, 1)),

        UNICODE(SUBSTRING(@nstring, @position, 1))

    SELECT @position = @position + 1

    END

Here is the result set:

Character # Unicode Character UNICODE Value

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

1           Å                 197

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

2           k                 107

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

3           e                 101

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

4           r                 114

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

5           g                 103

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

6           a                 97

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

7           t                 116

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

8           a                 97

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

9           n                 110

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

10                            32

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

11          2                 50

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

12          4                 52

See Also
Data Types | String Functions
NCHAR |


UNION

Combines the results of two or more queries into a single result set consisting of all the rows belonging to all queries in the union. For more information, see SELECT.


uniqueidentifier

A globally unique identifier (GUID).

Remarks

A column or local variable of uniqueidentifier data type can be initialized to a value in two ways:

  • Using the NEWID function.
  • Converting from a string constant in the following form (xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, in which each x is a hexadecimal digit in the range 0-9 or a-f). For example, 6F9619FF-8B86-D011-B42D-00C04FC964FF is a valid uniqueidentifier value.

Comparison operators can be used with uniqueidentifier values. However, ordering is not implemented by comparing the bit patterns of the two values. When using uniqueidentifier data, the only operations allowed are the equality comparison operators (= and <>) and the IS NULL and IS NOT NULL operators. No other inequality comparison or arithmetic operators are allowed. All column constraints and properties except IDENTITY are allowed on the uniqueidentifier data type.

See Also
ALTER TABLE | DELETE
CAST and CONVERT | INSERT
CREATE TABLE | NEWID
Data Types | SET @local_variable
DECLARE @local_variable | UPDATE


UPDATE

Changes existing data in a table.

Syntax

UPDATE
{
table_name [ [AS] table_alias] WITH ( <table_hint_limited> […n])
| view_name [ [AS] table_alias]
 | rowset_function_limited
}
SET
{column_name = {expression | DEFAULT | NULL}
| @variable = expression
| @variable = column = expression } [,…n]

{{[FROM {<table_source>} [,…n] ]

[WHERE
<search_condition>] }
|
[WHERE CURRENT OF
{ { [GLOBAL] cursor_name } | cursor_variable_name}
] }
[OPTION (<query_hint> [,…n] )]

<table_source> ::=
 table_name [ [AS] table_alias ] [ WITH ( <table_hint> [,…n]) ]
| view_name [ [AS] table_alias ]
| rowset_function [ [AS] table_alias ]
| derived_table [AS] table_alias [ (column_alias [,…n] ) ]
| <joined_table>

<joined_table> ::=
<table_source> <join_type> <table_source> ON <search_condition>
| <table_source> CROSS JOIN <table_source>
| <joined_table>

<join_type> ::=
[ INNER | { { LEFT | RIGHT | FULL } [OUTER] } ]
[ <join_hint> ]
JOIN

<table_hint_limited> ::=
{ INDEX(index_val [,…n])
| FASTFIRSTROW
| HOLDLOCK
| PAGLOCK
| READCOMMITTED
| REPEATABLEREAD
| ROWLOCK
| SERIALIZABLE
| TABLOCK
| TABLOCKX
}

<table_hint> ::=
{ INDEX(index_val [,…n])
| FASTFIRSTROW
| HOLDLOCK
| NOLOCK
| PAGLOCK
| READCOMMITTED
| READPAST
| READUNCOMMITTED
| REPEATABLEREAD
| ROWLOCK
| SERIALIZABLE
| TABLOCK
| TABLOCKX
| UPDLOCK
}

<query_hint> ::=
{ { HASH | ORDER } GROUP
| { CONCAT | HASH | MERGE } UNION
| {LOOP | MERGE | HASH} JOIN
| FAST number_rows
| FORCE ORDER
| ROBUST PLAN
| KEEP PLAN
}

Arguments
table_name [ [AS] table_alias ]
Is the name and optional alias of the table to update. The name can be qualified with the linked server, database, and owner name if the table is not in the current server or database, or is not owned by the current user.
WITH (<table_hint_limited> […n])
Specifies one or more table hints that are allowed for a target table. The WITH keyword and the parentheses are required. READPAST, NOLOCK, READUNCOMMITTED, and UPDLOCK are not allowed. For information about table hints, see FROM.
view_name [ [AS] table_alias ]
Is the name and optional alias of the view to update. The view referenced by view_name must be updatable. The modifications made by the UPDATE statement cannot affect more than one of the base tables referenced in the FROM clause of the view. For more information on updatable views, see CREATE VIEW.
rowset_function_limited
Is either the OPENQUERY or OPENROWSET function, subject to provider capabilities. For more information about the rowset functions, see OPENQUERY and OPENROWSET.
SET
Specifies the list of column or variable names to be updated.
column_name
Is a column that contains the data to be changed. column_name must reside in the table or view specified in the UPDATE clause. Identity columns cannot be updated.

If a qualified column name is specified, the qualifier must match the table or view name in the UPDATE clause. For example, this is valid:

UPDATE authors
    SET authors.au_fname = 'Annie'
    WHERE au_fname = 'Anne'

A table alias specified in a FROM clause cannot be used as a qualifier in SET column_name. For example, this is not valid:

UPDATE titles
    SET t.ytd_sales = t.ytd_sales + s.qty
    FROM titles t, sales s
    WHERE t.title_id = s.title_id
    AND s.ord_date = (SELECT MAX(sales.ord_date) FROM sales)

To make the example work, remove the t. alias from the column name.

UPDATE titles
    SET ytd_sales = t.ytd_sales + s.qty
    FROM titles t, sales s
    WHERE t.title_id = s.title_id
    AND s.ord_date = (SELECT MAX(sales.ord_date) FROM sales)

expression
Is a variable, literal value, expression, or a parenthesized subSELECT statement that returns a single value. The value returned by expression replaces the existing value in column_name or @variable.
DEFAULT
Specifies that the default value defined for the column is to replace the existing value in the column. This can also be used to change the column to NULL if the column has no default and is defined to allow null values.
@variable
Is a declared variable that is set to the value returned by expression.

SET @variable = column = expression sets the variable to the same value as the column. This differs from SET @variable = column, column = expression, which sets the variable to the pre-update value of the column.

FROM <table_source>
Specifies that a table is used to provide the criteria for the update operation. For more information, see FROM.
table_name [[AS] table_alias ]
Is the name of a table to provide criteria for the update operation.

If the table being updated is the same as the table in the FROM clause, and there is only one reference to the table in the FROM clause, table_alias may or may not be specified. If the table being updated appears more than one time in the FROM clause, one (and only one) reference to the table must not specify a table alias. All other references to the table in the FROM clause must include a table alias.

view_name [[AS] table_alias ]
Is the name of a view to provide criteria for the update operation.
WITH (<table_hint> […n])
Specifies one or more table hints for a source table. For information about table hints, see FROM.
rowset_function [ [AS] table_alias ]
Is the name of any rowset function and an optional alias. For information about a list of rowset functions, see Rowset Functions.
derived_table
Is a subquery that retrieves rows from the database. derived_table is used as input to the outer query.
column_alias
Is an optional alias to replace a column name in the result set. Include one column alias for each column in the select list, and enclose the entire list of column aliases in parentheses.
<joined_table>
Is a result set that is the product of two or more tables, for example:

FROM tab1 LEFT OUTER JOIN tab1.c3 = tab2.c3
    RIGHT OUTER JOIN tab3 LEFT OUTER JOIN tab4
        ON tab3.c1
    ON tab2.c3 = tab4.c3

For multiple CROSS joins, use parentheses to change the natural order of the joins.

<join_type>
Specifies the type of join operation.
INNER
Specifies that all matching pairs of rows are returned. Discards unmatched rows from both tables. This is the default if no join type is specified.
LEFT [OUTER]
Specifies that all rows from the left table not meeting the specified condition are included in the result set in addition to all rows returned by the inner join. Output columns from the left table are set to NULL.
RIGHT [OUTER]
Specifies that all rows from the right table not meeting the specified condition are included in the result set in addition to all rows returned by the inner join. Output columns from the right table are set to NULL.
FULL [OUTER]
If a row from either the left or right table does not match the selection criteria, specifies the row be included in the result set, and output columns that correspond to the other table be set to NULL. This is in addition to all rows usually returned by the inner join.
<join_hint>
Specifies a join hint or execution algorithm. If <join_hint> is specified, INNER, LEFT, RIGHT, or FULL must also be explicitly specified. For more information about joint hints, see FROM.
JOIN
Indicates that the specified tables or views should be joined.
ON <search_condition>
Specifies the condition on which the join is based. The condition can specify any predicate, although columns and comparison operators are often used, for example:

FROM Suppliers JOIN Products
    ON (Suppliers.SupplierID = Products.SupplierID)

When the condition specifies columns, the columns do not have to have the same name or same data type; however, if the data types are not identical, they must be either compatible or types that Microsoft® SQL Server™ can implicitly convert. If the data types cannot be implicitly converted, the condition must explicitly convert the data type using the CAST function.

For more information about search conditions and predicates, see Search Condition.

CROSS JOIN
Specifies the cross-product of two tables. Returns the same rows as if the tables to be joined were simply listed in the FROM clause and no WHERE clause was specified.
WHERE
Specifies the conditions that limit the rows that are updated. There are two forms of update based on which form of the WHERE clause is used:
  • Searched updates specify a search condition to qualify the rows to delete.
  • Positioned updates use the CURRENT OF clause to specify a cursor. The update operation occurs at the current position of the cursor.
<search_condition>
Specifies the condition to be met for the rows to be updated. The search condition can also be the condition upon which a join is based. There is no limit to the number predicates that can be included in a search condition. For more information about predicates and search conditions, see Search Condition.
CURRENT OF
Specifies that the update is performed at the current position of the specified cursor.
GLOBAL
Specifies that cursor_name refers to a global cursor.
cursor_name
Is the name of the open cursor from which the fetch should be made. If both a global and a local cursor exist with cursor_name as their name, cursor_name refers to the global cursor if GLOBAL is specified. If GLOBAL is not specified, cursor_name refers to the local cursor. The cursor must allow updates.
cursor_variable_name
Is the name of a cursor variable. cursor_variable_name must reference a cursor that allows updates.
OPTION (<query_hint> [,…n] )
Specifies that optimizer hints are used to customize SQL Server’s processing of the statement.
{HASH | ORDER} GROUP
Specifies that the aggregations specified in the GROUP BY or COMPUTE clause of the query should use hashing or ordering.
{LOOP | MERGE | HASH |} JOIN
Specifies that all join operations are performed by loop join, merge join, or hash join in the whole query. If more than one join hint is specified, the query optimizer selects the least expensive join strategy for the allowed ones. If, in the same query, a join hint is also specified for a specific pair of tables, it takes precedence in the joining of the two tables.
{MERGE | HASH | CONCAT} UNION
Specifies that all UNION operations should be performed by merging, hashing, or concatenating UNION sets. If more than one UNION hint is specified, the query optimizer selects the least expensive strategy from those hints specified.

Note If a join hint is also specified for any particular pair of joined tables in the FROM clause, it takes precedence over any join hint specified in the OPTION clause.

FAST number_rows
Specifies that the query is optimized for fast retrieval of the first number_rows (a nonnegative integer). After the first number_rows are returned, the query continues execution and produces its full result set.
FORCE ORDER
Specifies that the join order indicated by the query syntax should be preserved during query optimization.
ROBUST PLAN
Forces the query optimizer to attempt a plan that works for the maximum potential row size at the expense of performance. If no such plan is possible, the query optimizer returns an error rather than deferring error detection to query execution. Rows may contain variable-length columns; SQL Server allows rows to be defined whose maximum potential size is beyond the ability of SQL Server to process them. Usually, despite the maximum potential size, an application stores rows that have actual sizes within the limits that SQL Server can process. If SQL Server encounters a row that is too long, an execution error is returned.
KEEP PLAN
Forces the query optimizer to relax the estimated recompile threshold for a query. The estimated recompile threshold is the point at which a query is automatically recompiled when the estimated number of indexed column changes (update, delete or insert) have been made to a table. Specifying KEEP PLAN ensures that a query will not be recompiled as frequently when there are multiple updates to a table.
Remarks

If an update to a row violates a constraint or rule, if it violates the NULL setting for the column, or if the new value is an incompatible data type, the statement is canceled, an error is returned, and no records are updated.

When an UPDATE statement encounters an arithmetic error (overflow, divide by zero, or a domain error) during expression evaluation the update is not performed. The remainder of the batch is not executed, and an error message is returned.

If an update to a column or columns participating in a clustered index causes the size of the clustered index and the row to exceed 8,092 bytes, the update fails and an error message is returned.

If an update query could alter more than one row while updating both the clustering key and one or more text, image, or Unicode columns, the update operation fails and SQL Server returns an error message.

Modifying a text, ntext, or image column with UPDATE initializes the column, assigns a valid text pointer to it, and allocates at least one data page unless updating the column with NULL.

Note The UPDATE statement is logged. If you are replacing or modifying large blocks of text, ntext, or image data, use the WRITETEXT or UPDATETEXT statement instead of the UPDATE statement. The WRITETEXT and UPDATETEXT statements (by default) are not logged.

All char and nchar columns are right-padded to the defined length.

If ANSI_PADDING is set OFF, all trailing spaces are removed from data inserted into varchar and nvarchar columns, except in strings containing only spaces. These strings are truncated to an empty string. If ANSI_PADDING is set ON, trailing spaces are inserted. The Microsoft SQL Server ODBC driver and OLE DB Provider for SQL Server automatically set ANSI_PADDING ON for each connection. This can be configured in ODBC data sources or by setting connection attributes or properties.

A positioned update using a WHERE CURRENT OF clause updates the single row at the current position of the cursor. This can be more accurate than a searched update that uses a WHERE <search_condition> clause to qualify the rows to be updated. A searched update modifies multiple rows when the search condition does not uniquely identify a single row.

The results of an UPDATE statement are undefined if the statement includes a FROM clause that is not specified in such a way that only one value is available for each column occurrence that is updated (in other words, if the UPDATE statement is not deterministic). For example, given the UPDATE statement in the following script, both rows in table s meet the qualifications of the FROM clause in the UPDATE statement, but it is undefined which row from s is used to update the row in table t:

CREATE TABLE s (ColA INT, ColB DECIMAL(10,3))

GO

CREATE TABLE t (ColA INT PRIMARY KEY, ColB DECIMAL(10,3))

GO

INSERT INTO s VALUES(1, 10.0)

INSERT INTO s VALUES(1, 20.0)

INSERT INTO t VALUES(1, 0.0)

GO

UPDATE t

SET t.ColB = t.ColB + s.ColB

FROM t INNER JOIN s ON (t.ColA = s.ColA)

GO

The same problem can occur when combining the FROM and WHERE CURRENT OF clauses. In this example, both rows in table t2 meet the qualifications of the FROM clause in the UPDATE statement. It is undefined which row from t2 is to be used to update the row in table t1.

CREATE TABLE t1(c1 INT PRIMARY KEY, c2 INT)

GO

CREATE TABLE t2(d1 INT PRIMARY KEY, d2 INT)

GO

INSERT INTO t1 VALUES (1, 10)

INSERT INTO t2 VALUES (1, 20)

INSERT INTO t2 VALUES (2, 30)

go

DECLARE abc CURSOR LOCAL FOR

SELECT * FROM t1

OPEN abc

FETCH abc

UPDATE t1 SET c2 = c2 + d2

FROM t2

WHERE CURRENT OF abc

GO

Setting Variables and Columns

Variable names can be used in UPDATE statements to show the old and new values affected. This should only be used when the UPDATE statement affects a single record; if the UPDATE statement affects multiple records, the variables only contain the values for one of the updated rows.

Permissions

UPDATE permissions default to members of the sysadmin fixed server role, the db_owner fixed database role, and the table owner, who can transfer permissions to other users. SELECT permissions are also required for the table being updated if the UPDATE statement contains a WHERE clause, or if expression in the SET clause uses a column in the table.

Examples
A. Use a simple UPDATE

These examples show how all rows can be affected if a WHERE clause is eliminated from an UPDATE statement.

If all the publishing houses in the publishers table move their head offices to Atlanta, Georgia, this example shows how the publishers table can updated.

UPDATE publishers

SET city = 'Atlanta', state = 'GA'

This example changes the names of all the publishers to NULL.

UPDATE publishers

SET pub_name = NULL

You can also use computed values in an update. This example doubles all prices in the titles table.

UPDATE titles

SET price = price * 2

B. Use the UPDATE statement with a WHERE clause

The WHERE clause specifies the rows to update. For example, in the unlikely event that northern California is renamed Pacifica (abbreviated PC) and the people of Oakland vote to change the name of their city to Bay City. This example shows how to update the authors table for all former Oakland residents whose addresses are now out of date.

UPDATE authors

    SET state = 'PC', city = 'Bay City'

        WHERE state = 'CA' AND city = 'Oakland'

You must write another statement to change the name of the state for residents of other northern California cities.

C. Use the UPDATE statement using information from another table

This example modifies the ytd_sales column in the titles table to reflect the most recent sales recorded in the sales table.

UPDATE titles

    SET ytd_sales = titles.ytd_sales + sales.qty

        FROM titles, sales

            WHERE titles.title_id = sales.title_id

            AND sales.ord_date = (SELECT MAX(sales.ord_date) FROM sales)

This example assumes that only one set of sales is recorded for a given title on a given date and that updates are current. If this is not the case (if more than one sale for a given title can be recorded on the same day), the example shown here does not work correctly. It executes without error, but each title is updated with only one sale, regardless of how many sales actually occurred on that day. This is because a single UPDATE statement never updates the same row twice.

In the situation in which more than one sale for a given title can occur on the same day, all the sales for each title must be aggregated together within the UPDATE statement, as shown in this example:

UPDATE titles

    SET ytd_sales =

        (SELECT SUM(qty)

            FROM sales

                WHERE sales.title_id = titles.title_id

                AND sales.ord_date IN (SELECT MAX(ord_date) FROM sales))

    FROM titles, sales

D. Use UPDATE with the TOP clause in a SELECT statement

This example updates the state column for the first 10 authors from the authors table.

UPDATE authors

SET state = 'ZZ'

FROM (SELECT TOP 10 * FROM authors ORDER BY au_lname) AS t1

WHERE authors.au_id = t1.au_id

See Also
CREATE INDEX | DELETE
CREATE TABLE | INSERT
CREATE TRIGGER | SET ROWCOUNT
Cursors | Text and Image Functions


UPDATE STATISTICS

Updates information about the distribution of key values for one or more statistics groups (collections) in the specified table. UPDATE STATISTICS is run automatically when an index is created on a table that already contains data. To create statistics on columns, see CREATE STATISTICS.

Syntax

UPDATE STATISTICS table
[
index
| (statistics_name[,…n])
 ]
[ WITH
[
[FULLSCAN]
| SAMPLE number {PERCENT | ROWS}]
]
[[,] [ALL | COLUMNS | INDEX]
[[,] NORECOMPUTE]
]

Arguments
table
Is the name of the table for which to update statistics. Table names must conform to the rules for identifiers. Because index names are not unique within each database, table must be specified. Specifying the database or table owner is optional.
index
Is the index for which statistics are being updated. Index names must conform to the rules for identifiers. If index is not specified, the distribution statistics for all indexes in the specified table are updated. To see a list of index names and descriptions, execute sp_helpindex with the table name.
statistics_name
Is the name of the statistics group (collection) to update. Statistics names must conform to the rules for identifiers. For more information about creating statistics groups, see CREATE STATISTICS.
n
Is a placeholder indicating that multiple statistics_name groups can be specified.
FULLSCAN
Specifies that all rows in table should be read to gather the statistics. FULLSCAN provides the same behavior as SAMPLE 100 PERCENT. FULLSCAN cannot be used with the SAMPLE option.
SAMPLE number {PERCENT | ROWS}
Specifies the percentage of the table or the number of rows to sample when collecting statistics for larger tables. To use the default sampling behavior for larger tables, use SAMPLE number with PERCENT or ROWS. Microsoft® SQL Server™ ensures a minimum number of values are sampled to ensure useful statistics. If the PERCENT, ROWS, or number option results in too few rows being sampled, SQL Server automatically corrects the sampling based on the number of existing rows in the table.

Note The default behavior is to perform a sample scan on the target table. SQL Server automatically computes the required sample size.

ALL | COLUMNS | INDEX
Specifies whether the UPDATE STATISTICS statement affects column statistics, index statistics, or all existing statistics. If no option is specified, the UPDATE STATISTICS statement affects all statistics. Only one type (ALL, COLUMNS, or INDEX) can be specified per UPDATE STATISTICS statement.
NORECOMPUTE
Specifies that statistics that become out of date are not automatically recomputed. Statistics become out of date depending on the number of INSERT, UPDATE, and DELETE operations performed on indexed columns. When specified, this option causes SQL Server to never automatically rebuild statistics and disables automatic statistics rebuilding. To restore automatic statistics recomputation, reissue UPDATE STATISTICS without the NORECOMPUTE option or execute sp_autostats.

Important Disabling automatic statistics recomputation can cause the SQL Server query optimizer to choose a less optimal strategy for queries that involve the specified table.

Remarks

SQL Server keeps statistics about the distribution of the key values in each index and uses these statistics to determine which index(es) to use in query processing. Users can create statistics on nonindexed columns by using the CREATE STATISTICS statement. Query optimization depends on the accuracy of the distribution steps:

  • If there is significant change in the key values in the index, rerun UPDATE STATISTICS on that index.
  • If a large amount of data in an indexed column has been added, changed, or removed (that is, if the distribution of key values has changed), or the table has been truncated using the TRUNCATE TABLE statement and then repopulated, use UPDATE STATISTICS.

To see when the statistics were last updated, use the STATS_DATE function.

Permissions

UPDATE STATISTICS permissions default to the table owner, and are not transferable.

Examples
A. Update all statistics for a single table

This example updates the distribution statistics for all indexes on the authors table.

UPDATE STATISTICS authors

B. Update only the statistics for a single index

This example updates only the distribution information for the au_id_ind index of the authors table.

UPDATE STATISTICS authors au_id_ind

C. Update statistics for specific statistics groups (collections) using 50 percent sampling

This example creates and then updates the statistics group for the au_lname and au_fname columns in the authors table.

CREATE STATISTICS anames

    ON authors (au_lname, au_fname)

    WITH SAMPLE 50 PERCENT
GO

-- Time passes. The UPDATE STATISTICS statement is then executed.

UPDATE STATISTICS authors(anames)
    WITH SAMPLE 50 PERCENT

GO

D. Update statistics for a specific statistics groups (collections) using FULLSCAN and NORECOMPUTE

This example updates the anames statistics group (collection) in the authors table, forces a full scan of all rows in the authors table, and turns off automatic statistics updating for the statistics group (collection).

UPDATE STATISTICS authors(anames)

    WITH FULLSCAN, NORECOMPUTE

GO

See Also
CREATE INDEX | Functions
CREATE STATISTICS | sp_autostats
Cursors | sp_createstats
DBCC SHOW_STATISTICS | sp_helpindex
DROP STATISTICS | sp_updatestats
EXECUTE | STATS_DATE


UPDATETEXT

Updates an existing text, ntext, or image field. Use UPDATETEXT to change only a portion of a text, ntext, or image column in place. Use WRITETEXT to update and replace an entire text, ntext, or image field.

Syntax

UPDATETEXT {table_name.dest_column_name dest_text_ptr}
{
NULL
| insert_offset
}
{
NULL
| delete_length
}
[WITH LOG]
[
inserted_data
| [{table_name.src_column_name src_text_ptr}
]

Arguments
table_name.dest_column_name
Is the name of the table and text, ntext, or image column to be updated. Table names and column names must conform to the rules for identifiers. Specifying the database name and owner names is optional.
dest_text_ptr
Is a text pointer value (returned by the TEXTPTR function) that points to the text, ntext, or image data to be updated. dest_text_ptr must be binary(16).
insert_offset
Is the zero-based starting position for the update. For text or image columns, insert_offset is the number of bytes to skip from the start of the existing column before inserting new data. For ntext columns, insert_offset is the number of characters (each ntext character uses 2 bytes). The existing text, ntext, or image data beginning at this zero-based starting position is shifted to the right to make room for the new data. A value of 0 inserts the new data at the beginning of the existing data. A value of NULL appends the new data to the existing data value.
delete_length
Is the length of data to delete from the existing text, ntext, or image column, starting at the insert_offset position. The delete_length value is specified in bytes for text and image columns and in characters for ntext columns. Each ntext character uses 2 bytes. A value of 0 deletes no data. A value of NULL deletes all data from the insert_offset position to the end of the existing text or image column.
WITH LOG
Specifies that the inserted text, ntext, or image data is logged. This option allows recovery, but it can quickly increase the size of the transaction log.

Note If the WITH LOG option is not specified, the database must have the select into/bulkcopy database option turned on.

inserted_data
Is the data to be inserted into the existing text, ntext, or image column at the insert_offset location. This is a single char, nchar, varchar, nvarchar, binary, varbinary, text, ntext, or image value. inserted_data can be a literal or a variable.
table_name.src_column_name
Is the name of the table and text, ntext, or image column used as the source of the inserted data. Table names and column names must conform to the rules for identifiers.
src_text_ptr
Is a text pointer value (returned by the TEXTPTR function) that points to a text, ntext, or image column used as the source of the inserted data.
Remarks

Newly inserted data can be a single inserted_data constant, table name, column name, or text pointer.

Update action | UPDATETEXT parameters
To replace existing data | Specify a nonnull insert_offset value, a nonzero delete_length value, and the new data to be inserted.
To delete existing data | Specify a nonnull insert_offset value and a nonzero delete_length. Do not specify new data to be inserted.
To insert new data | Specify the insert_offset value, a delete_length of 0, and the new data to be inserted.

To initialize text columns to NULL, use UPDATETEXT when the compatibility level is equal to 65. If the compatibility level is equal to 70, use WRITETEXT to initialize text columns to NULL; otherwise, UPDATETEXT initializes text columns to an empty string. For information about setting the compatibility level, see sp_dbcmptlevel.

Permissions

UPDATETEXT permissions default to those users with SELECT permissions on the specified table. Permissions are transferable when SELECT permissions are transferred.

Examples

This example puts the text pointer into the local variable @ptrval, and then uses UPDATETEXT to update a spelling error.

USE pubs

GO

EXEC sp_dboption 'pubs', 'select into/bulkcopy', 'true'

GO

DECLARE @ptrval binary(16)

SELECT @ptrval = TEXTPTR(pr_info)

    FROM pub_info pr, publishers p

        WHERE p.pub_id = pr.pub_id

        AND p.pub_name = 'New Moon Books'

UPDATETEXT pub_info.pr_info @ptrval 88 1 'b'

GO

EXEC sp_dboption 'pubs', 'select into/bulkcopy', 'false'

GO

See Also
TEXTPTR | WRITETEXT
READTEXT |


UPPER

Returns a character expression with lowercase character data converted to uppercase.

Syntax

UPPER(character_expression)

Arguments
character_expression
Is an expression of character data. character_expression can be a constant, variable, or column of either character or binary data.
Return Types

varchar

Remarks

character_expression must be of a data type that is implicitly convertible to varchar. Otherwise, use the CAST function to explicitly convert character_expression.

Examples

This example uses the UPPER and RTRIM functions to return the trimmed, uppercase author’s last name concatenated with the author’s first name.

USE pubs

GO

SELECT UPPER(RTRIM(au_lname)) + ', ' + au_fname AS Name

FROM authors

ORDER BY au_lname

GO

Here is the result set:

Name

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

BENNET, Abraham

BLOTCHET-HALLS, Reginald

CARSON, Cheryl

DEFRANCE, Michel

DEL CASTILLO, Innes

DULL, Ann

GREEN, Marjorie

GREENE, Morningstar

GRINGLESBY, Burt

HUNTER, Sheryl

KARSEN, Livia

LOCKSLEY, Charlene

MACFEATHER, Stearns

MCBADDEN, Heather

O'LEARY, Michael

PANTELEY, Sylvia

RINGER, Albert

RINGER, Anne

SMITH, Meander

STRAIGHT, Dean

STRINGER, Dirk

WHITE, Johnson

YOKOMOTO, Akiko

(23 row(s) affected)

See Also
Data Types String Functions


USE

Changes the database context to the specified database.

Syntax

USE {database}

Arguments
database
Is the name of the database to which the user context is switched. Database names must conform to the rules for identifiers.
Remarks

USE executes at both compile and execution time and takes effect immediately. Therefore, statements that appear in a batch after the USE statement are executed in the specified database.

When logging in to Microsoft® SQL Server™, users are usually connected to the master database automatically. Unless a default database has been set up for each user’s login ID, each user must execute the USE statement to change from master to another database.

To change context to a different database, a user must have a security account for that database. The database owner provides the security accounts for the database.

Permissions

USE permissions default to those users who are assigned permissions by members of the db_owner fixed database role executing sp_adduser. Users without a security account in the destination database can still be allowed access if a guest user exists in that database.

See Also
CREATE DATABASE | sp_addalias
DROP DATABASE | sp_adduser
EXECUTE | sp_defaultdb


USER

Allows a system-supplied value for the current user’s database username to be inserted into a table when no default value is specified.

Syntax

USER

Return Types

char

Remarks

USER provides the same functionality as the USER_NAME system function.

Use USER with DEFAULT constraints in either the CREATE TABLE or ALTER TABLE statements, or use as any standard function.

Examples
A. Use USER to return the current user’s database username

This example declares a variable as char, assigns the current value of USER to it, and then prints the variable with a text description.

DECLARE @usr char(30)

SET @usr = user

SELECT 'The current user’s database username is: '+ @usr

GO

Here is the result set:

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

The current user’s database username is: dbo

(1 row(s) affected)

B. Use USER with DEFAULT constraints

This example creates a table using USER as a DEFAULT constraint for the salesperson of a sales row.

USE pubs

GO

CREATE TABLE inventory2

(

 part_id int IDENTITY(100, 1) NOT NULL,

 description varchar(30) NOT NULL,

 entry_person varchar(30) NOT NULL DEFAULT USER

)

GO

INSERT inventory2 (description)

VALUES ('Red pencil')

INSERT inventory2 (description)

VALUES ('Blue pencil')

INSERT inventory2 (description)

VALUES ('Green pencil')

INSERT inventory2 (description)

VALUES ('Black pencil')

INSERT inventory2 (description)

VALUES ('Yellow pencil')

GO

This is the query to select all information from the inventory2 table:

SELECT *

FROM inventory2

ORDER BY part_id

GO

Here is the result set (note the entry-person value):

part_id     description                    entry_person

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

100         Red pencil                     dbo

101         Blue pencil                    dbo

102         Green pencil                   dbo

103         Black pencil                   dbo

104         Yellow pencil                  dbo

(5 row(s) affected)

See Also
ALTER TABLE | SESSION_USER
CREATE TABLE | SYSTEM_USER
CURRENT_TIMESTAMP | USER_NAME
CURRENT_USER | Security Functions


USER_ID

Returns a user’s database identification number.

Syntax

USER_ID(['user'])

Arguments
'user'
Is the username to be used. user is nchar. If a char value is specified, it is implicitly converted to nchar.
Return Types

int

Remarks

When user is omitted, the current user is assumed. Parentheses are required.

USER_ID can be used in the select list, in the WHERE clause, and anywhere an expression is allowed. For more information, see Expressions.

Examples

This example returns the identification number for user Harold.

SELECT USER_ID('Harold')

See Also

Security Functions


USER_NAME

Returns a user database username from a given identification number.

Syntax

USER_NAME([id])

Arguments
id
Is the identification number used to return a user’s name. id is int.
Return Types

nchar

Remarks

When id is omitted, the current user is assumed. Parentheses are required.

Examples
A. Use USER_NAME

This example returns the username for user number 13.

SELECT USER_NAME(13)

GO

B. Use USER_NAME without an ID

This example finds the name of the current user without specifying an ID.

SELECT user_name()

GO

Here is the result set (for a user who is a member of the sysadmin fixed server role):

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

dbo

(1 row(s) affected)

C. Use USER_NAME in the WHERE clause

This example finds the row in sysusers in which the name is equal to the result of applying the system function USER_NAME to user identification number 1.

SELECT name

FROM sysusers

WHERE name = USER_NAME(1)

GO

Here is the result set:

name

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

dbo

(1 row(s) affected)

See Also
ALTER TABLE | SESSION_USER
CREATE TABLE | SYSTEM_USER
CURRENT_TIMESTAMP | USER_NAME
CURRENT_USER | System Functions


VAR

Returns the statistical variance of all values in the given expression.

Syntax

VAR(expression)

Arguments
expression
Is an expression of the exact numeric or approximate numeric data type category, except for the bit data type. Aggregate functions and subqueries are not permitted.
Return Types

float

Remarks

If VAR is used on all items in a SELECT statement, each value in the result set is included in the calculation. VAR can be used with numeric columns only. Null values are ignored.

Examples

This example returns the variance for all royalty values in the titles table.

USE pubs

SELECT VAR(royalty)

FROM titles

See Also

Aggregate Functions


varbinary

For information about the varbinary data type, see binary and varbinary.

See Also
Data Types


varchar

For information about the varchar data type, see See Also

Data Types


VARP

Returns the statistical variance for the population for all values in the given expression.

Syntax

VARP(expression)

Arguments
expression
Is an expression of the exact numeric or approximate numeric data type category, except for the bit data type. Aggregate functions and subqueries are not permitted.
Return Types

float

Remarks

If VARP is used on all items in a SELECT statement, each value in the result set is included in the calculation. VARP can be used with numeric columns only. Null values are ignored.

Examples

This example returns the variance for the population for all royalty values in the titles table.

USE pubs

SELECT VARP(royalty)

FROM titles

See Also

Aggregate Functions


WAITFOR

Specifies a time, time interval, or event that triggers the execution of a statement block, stored procedure, or transaction.

Syntax

WAITFOR {DELAY 'time' | TIME 'time'}

Arguments
DELAY
Instructs Microsoft® SQL Server™ to wait until the specified amount of time has passed, up to a maximum of 24 hours.
'time'
Is the amount of time to wait. time can be specified in one of the acceptable formats for datetime data, or it can be specified as a local variable. Dates cannot be specified; therefore, the data portion of the datetime value is not allowed.
TIME
Instructs SQL Server to wait until the specified time.
Remarks

After executing the WAITFOR statement, you cannot use your connection to SQL Server until the time or event that you specified occurs.

To see the active and waiting processes, use sp_who.

Examples
A. Use WAITFOR TIME

This example executes the stored procedure update_all_stats at 10:20 P.M.

BEGIN

    WAITFOR TIME '22:20'

    EXECUTE update_all_stats

END

For more information about using this procedure to update all statistics for a database, see the examples in UPDATE STATISTICS.

B. Use WAITFOR DELAY

This example shows how a local variable can be used with the WAITFOR DELAY option. A stored procedure is created to wait for a variable amount of time and then returns information to the user as to the number of hours, minutes, and seconds that have elapsed.

CREATE PROCEDURE time_delay @@DELAYLENGTH char(9)

AS
DECLARE @@RETURNINFO        varchar(255)

BEGIN

    WAITFOR DELAY @@DELAYLENGTH

    SELECT @@RETURNINFO = 'A total time of ' +

                        SUBSTRING(@@DELAYLENGTH, 1, 3) +

                        ' hours, ' +

                        SUBSTRING(@@DELAYLENGTH, 5, 2) +

                        ' minutes, and ' +

                        SUBSTRING(@@DELAYLENGTH, 8, 2) +

                        ' seconds, ' +

                        'has elapsed! Your time is up.'

    PRINT @@RETURNINFO

END

GO

-- This next statement executes the time_delay procedure.

EXEC time_delay '000:00:10'

GO

Here is the result set:

A total time of 000 hours, 00 minutes, and 10 seconds, has elapsed! Your time is up.

See Also
Control-of-Flow Language | sp_who
datetime and smalldatetime |


WHERE

Specifies the condition for the rows returned by a query.

Syntax

WHERE <search_condition>

Arguments
<search_condition>
Defines the condition to be met for the rows to be returned. There is no limit to the number of predicates in <search_condition>.
See Also
DELETE | SELECT @local_variable
Predicate | UPDATE
Search Condition |


WHILE

Sets a condition for the repeated execution of an SQL statement or statement block. The statements are executed repeatedly as long as the specified condition is true. The execution of statements in the WHILE loop can be controlled from inside the loop with the BREAK and CONTINUE keywords.

Syntax

WHILE Boolean_expression
{sql_statement | statement_block}
[BREAK]
{sql_statement | statement_block}
[CONTINUE]

Arguments
Boolean_expression
Is an expression that returns TRUE or FALSE. If the Boolean expression contains a SELECT statement, the SELECT statement must be enclosed in parentheses.
{sql_statement | statement_block}
Is any Transact-SQL statement or statement grouping as defined with a statement block. To define a statement block, use the control-of-flow keywords BEGIN and END.
BREAK
Causes an exit from the innermost WHILE loop. Any statements appearing after the END keyword, marking the end of the loop, are executed.
CONTINUE
Causes the WHILE loop to restart, ignoring any statements after the CONTINUE keyword.
Remarks

If two or more WHILE loops are nested, the inner BREAK exits to the next outermost loop. First, all the statements after the end of the inner loop run, and then the next outermost loop restarts.

Examples
A. Use BREAK and CONTINUE with nested IF…ELSE and WHILE

In this example, if the average price is less than $30, the WHILE loop doubles the prices and then selects the maximum price. If the maximum price is less than or equal to $50, the WHILE loop restarts and doubles the prices again. This loop continues doubling the prices until the maximum price is greater than $50, and then exits the WHILE loop and prints a message.

USE pubs

GO

WHILE (SELECT AVG(price) FROM titles) < $30

BEGIN

    UPDATE titles

        SET price = price * 2

    SELECT MAX(price) FROM titles

    IF (SELECT MAX(price) FROM titles) > $50

        BREAK

    ELSE

        CONTINUE

END

PRINT 'Too much for the market to bear'

B. Using WHILE within a procedure with cursors

The following WHILE construct is a section of a procedure named count_all_rows. For this example, this WHILE construct tests the return value of @@FETCH_STATUS, a function used with cursors. Because @@FETCH_STATUS may return -2, -1, or 0, all three cases must be tested. If a row is deleted from the cursor results since the time this stored procedure was executed, that row is skipped. A successful fetch (0) causes the SELECT within the BEGIN…END loop to execute.

USE pubs

DECLARE tnames_cursor CURSOR

FOR

    SELECT TABLE_NAME

    FROM INFORMATION_SCHEMA.TABLES

OPEN tnames_cursor

DECLARE @tablename sysname

--SET @tablename = 'authors'

FETCH NEXT FROM tnames_cursor INTO @tablename

WHILE (@@FETCH_STATUS <> -1)

BEGIN

    IF (@@FETCH_STATUS <> -2)

    BEGIN

        SELECT @tablename = RTRIM(@tablename)

        EXEC ('SELECT ''' + @tablename + ''' = count(*) FROM '

                + @tablename )

        PRINT ' '

    END

    FETCH NEXT FROM tnames_cursor INTO @tablename

END

CLOSE tnames_cursor

DEALLOCATE tnames_cursor

See Also
ALTER TRIGGER | Cursors
Control-of-Flow Language | SELECT
CREATE TRIGGER |


WRITETEXT

Permits nonlogged, interactive updating of an existing text, ntext, or image column. This statement completely overwrites any existing data in the column it affects. WRITETEXT cannot be used on text, ntext, and image columns in views.

Syntax

WRITETEXT {table.column text_ptr}
[WITH LOG] {data}

Arguments
table.column
Is the name of the table and text, ntext, or image column to update. Table and column names must conform to the rules for identifiers. Specifying the database name and owner names is optional.
text_ptr
Is a value that stores the pointer to the text, ntext or image data. text_ptr must be binary(16). To create a text pointer, execute an INSERT or UPDATE statement with data that is not NULL for the text, ntext, or image column. For more information about creating a text pointer, see either INSERT or UPDATE.
WITH LOG
Logs the inserted text, ntext, or image data, which aids media recovery. Because text data quickly increases the size of the transaction log, ensure the transaction log has enough space to grow.
data
Is the actual text, ntext or image data to store. data can be a literal or a variable. The maximum length of text that can be inserted interactively with WRITETEXT is approximately 120 KB for text, ntext, and image data.
Remarks

Use WRITETEXT to replace text, ntext, and image data and UPDATETEXT to modify text, ntext, and image data. UPDATETEXT is more flexible because it changes only a portion of a text, ntext, or image column rather than the entire column.

By default, WRITETEXT is a nonlogged operation. This means text, ntext, or image data is not logged when it is written to the database; therefore, the transaction log does not fill up with the large amounts of data that often make up these data types. To use WRITETEXT in its default, nonlogged state, members of the sysadmin fixed database role must use sp_dboption to set select into/bulkcopy, which allows nonlogged data to be inserted. For more information, see sp_dboption.

For WRITETEXT to work properly, the column must already contain a valid text pointer.

Microsoft® SQL Server™ saves space by not initializing text columns when explicit or implicit null values are placed in text columns with INSERT.

The DB-Library dbwritetext and dbmoretext functions and the ODBC SQLPutData function are faster and use less dynamic memory than WRITETEXT. These functions can insert up to 2 gigabytes of text, ntext, or image data.

Caution After using the WRITETEXT statement, execute BACKUP DATABASE. After nonlogged operations occur within a database, the BACKUP LOG statement cannot be performed. For more information, see BACKUP.

To initialize text columns to NULL, use UPDATETEXT when the compatibility level is set to 65. If the compatibility level is set to 70, use WRITETEXT to initialize text columns to NULL; otherwise, UPDATETEXT initializes text columns to an empty string. For more information about compatibility levels, see sp_dbcmptlevel.

Permissions

WRITETEXT permissions default to those users with SELECT permissions on the specified table. Permissions are transferable when SELECT permissions are transferred.

Examples

This example puts the text pointer into the local variable @ptrval, and then WRITETEXT places the new text string into the row pointed to by @ptrval.

USE pubs

GO

EXEC sp_dboption 'pubs', 'select into/bulkcopy', 'true'

GO

DECLARE @ptrval binary(16)

SELECT @ptrval = TEXTPTR(pr_info)

FROM pub_info pr, publishers p

WHERE p.pub_id = pr.pub_id

    AND p.pub_name = 'New Moon Books'

WRITETEXT pub_info.pr_info @ptrval 'New Moon Books (NMB) has just released another top ten publication. With the latest publication this makes NMB the hottest new publisher of the year!'

GO

EXEC sp_dboption 'pubs', 'select into/bulkcopy', 'false'

GO

See Also
Data Types | SELECT
DECLARE @local_variable | SET
DELETE | UPDATETEXT


YEAR

Returns an integer that represents the year part of a specified date.

Syntax

YEAR( date)

Arguments
date
Is an expression of type datetime or smalldatetime.
Return Types

int

Remarks

This function is equivalent to DATEPART(yy, date).

Examples

This example returns the number of the year from the date 03/12/1998.

SELECT "Year Number" = YEAR('03/12/1998')

GO

Here is the result set:

Year Number
------------
1998

This example specifies the date as a number. Notice that Microsoft® SQL Server™ database interprets 0 as January 1, 1900.

SELECT MONTH(0), DAY(0), YEAR(0)

Here is the result set:

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

1 1 1900

See Also

Date and Time Functions


Error Messages

This section contains explanations and corrective actions for Microsoft® SQL Server™ system error messages.

Most of the messages presented here include error numbers from the sysmessages table in the master database. Others, which can occur in the SQL Server error log but are not from sysmessages, do not have error numbers. The messages with numbers appear first, in numerical order, followed by the messages without numbers, in alphabetical order.


Error Message Formatting

All of the Microsoft® SQL Server™ components can issue informational, warning, or error messages to applications. Most SQL Server messages returned to applications have these parts:

  • Error number

    A one-to-five-digit number that identifies the message. Error numbers for user-defined messages can contain more digits.

  • Description

    A Unicode string that contains information about the condition that generated the message.

  • Severity level

    A one or two-digit number that indicates the severity of the error condition.

  • State

    A one to three digit number that indicates to Microsoft support engineers and developers the location in the SQL Server code that generated the message.

  • Line number

    The line number within the batch that contains the statement that generated the message.

The error numbers, descriptions, and severity levels for most SQL Server messages are stored in master.dbo.sysmessages. The state and line numbers are generated dynamically by the code issuing the message.

Messages raised in the client Net-Libraries, the Microsoft OLE DB Provider for SQL Server, or the SQL Server ODBC driver do not have some of these messsage parts.

An example of an error message can be seen by executing the statement:

SELECT * FROM ThisObjectDoesNotExist

This statement raises an error with these parts:

Error number: 208

Severity level: 16

State: 1

Line: 1

Description: Invalid object name 'ThisObjectDoesNotExist'.

All of the data APIs used by applications to access SQL Server return the error number and description. Not all of the APIs return the severity level, state, or line number. The OLE DB Provider for SQL Server and the SQL Server ODBC driver return these parts only if an OLE DB or ODBC application has been written to use SQL Server-specific diagnostic features exposed by the provider and driver. For more information about the message parts returned by a specific API, see Error Message Formats.


Messages Returned by SQL Server 7.0 Utilities

All of the Microsoft® SQL Server™ version 7.0 utilities use ODBC except for the isql command prompt utility. This has two effects on the way error messages are displayed by the ODBC-based utilities:

  • The error messages may have leading ODBC headers built into the description. These headers identify the component raising the error. The osql command prompt utility returns the ODBC headers. SQL Server Query Analyzer defaults to removing the ODBC headers, but users can set a connection option so that these are returned.

    For example, isql returns the error 208 description as:

Invalid object name 'ThisObjectDoesNotExist'.

osql includes the ODBC headers in the description:

[Microsoft][ODBC SQL Server Driver][SQL Server]Invalid object name 'ThisObjectDoesNotExist'.

The presence of the ODBC headers in the message does not necessarily indicate that the problem is in the ODBC components. The SQL Server ODBC driver includes these headers in messages from all components. For more information about how to determine the component raising the error, see ODBC Error Message Format.

  • Errors raised within the SQL Server ODBC driver have only a description. They have no error number, state, severity level, or line number. For example, if the following statement is executed in SQL Server Query Analyzer, the SQL Server ODBC driver itself raises a syntax error:

    { CLL sp_who }

    Because the error is generated by the driver, the only message part displayed by SQL Server Query Analyzer is the description:

[Microsoft][SQL Server ODBC Driver]Syntax error or access violation


Error Message Formats

Applications can use several database or data APIs to access Microsoft® SQL Server™. Some of the APIs, such as DB-Library, are specific to SQL Server and return all parts of SQL Server messages. Other APIs, such as ADO, OLE DB, and ODBC, are not specific to a particular database. The error message definitions for these APIs may not map to all parts of SQL Server messages, although they may allow a SQL Server interface component to provide SQL Server-specific ways of returning all the parts of a message.

This documentation describes the error message format for these APIs:

  • ADO
  • OLE DB
  • ODBC
  • Embedded SQL for C (ESQL/C)
  • DB-Library


ADO Error Message Format

The ADO specification defines Error objects in an Errors collection. Each Error object holds a message from the underlying provider. ADO does not provide for provider-specific diagnostic information. ADO and the Microsoft OLE DB Provider for SQL Server map the parts of Microsoft® SQL Server™ messages into these ADO Error object properties:

  • Description

    Contains the SQL Server message description, usually from the description column in master.dbo.sysmessages.

  • SQLState

    Contains the five-character SQLSTATE code generated by the OLE DB Provider for SQL Server.

  • NativeError

    Contains the SQL Server error number. For example, if a statement raises a SQL Server error 170 (syntax error), 170 is returned in NativeError.


OLE DB Error Message Format

OLE DB applications receive Microsoft® SQL Server™ messages in two ways:

  • Call OLE DB ISQLErrorInfo::GetSQLInfo.
  • Call provider specific ISQLServerErrorInfo::GetErrorInfo.

ISQLErrorInfo::GetSQLInfo returns SQL Server error numbers from master.dbo.sysmessages as plNativeError parameter and SQLSTATE value as pbstrSQLState parameter. These SQLSTATE codes are not related to any of the parts of a SQL Server message. The Microsoft® SQL Server™ OLE DB provider generates the appropriate SQLSTATE code anytime it returns a message to an application. The SQLSTATE codes generated by Microsoft OLE DB provider are same as the five-character SQLState codes defined in the ODBC specification. For ISQLErrorInfo::GetSQLInfo, pbstrSQLState may be null when the error is not produced by SQL Server.

Both Microsoft OLE DB provider for SQL Server and OLE DB provider for ODBC support ISQLErrorInfo.

The provider-specific ISQLServerErrorInfo interface returns more detail about a SQL Server error. The ISQLServerErrorInfo interface exposes one member function, GetErrorInfo. The function returns a pointer to a pointer to an SSERRORINFO structure and a pointer to a string buffer. The pointer to pointer to SSERRORINFO structure is null when the error is not produced by SQL Server.

The SQL Server message parts map to members of SSERRORINFO structure as described below:

  • pwszMessage

    Contains SQL Server error description.

  • lNative

    Contains SQL Server error number.

  • bState

    Contains SQL Server error state

  • bClass

    Contains severity of SQL Server error condition

  • wLineNumber

    Contains line number of the stored procedure on which the error occurred


ODBC Error Message Format

ODBC drivers return messages to applications as diagnostic records. An application can call the SQLGetDiagRec and SQLGetDiagField functions to retrieve these diagnostic records. The Microsoft® SQL Server™ ODBC driver maps SQL Server message parts into these standard ODBC diagnostic record fields:

SQLSTATE .
The ODBC specification defines a set of five-character codes called SQLSTATE codes that identify the conditions generating the message. These SQLSTATE codes are not related to any of the parts of a SQL Server message. The SQL Server ODBC driver generates the appropriate SQLSTATE code anytime it returns a message to an application.
pfNative
The SQL Server ODBC driver returns the SQL Server error number as the ODBC pfNative field. For example, if a statement raises a SQL Server error 170 (syntax error), the ODBC driver returns 170 in pfNative.
MessageText
The SQL Server ODBC driver returns the SQL Server error description as the MessageText field in an ODBC diagnostic record. The ODBC specification defines a series of headers for the MessageText field that indicates the component that issued the message:
  • [Microsoft][ODBC Driver Manager]

    These messages are issued by the ODBC Driver Manager.

  • [Microsoft][ODBC Cursor Library]

    These messages are issued by the ODBC client cursor library.

  • [Microsoft][ODBC SQL Server Driver]

    These messages are issued by the SQL Server ODBC driver. If there are no other nodes with either the name of a Net-Library or SQL Server installation, then the message was issued by the driver.

  • [Microsoft][ODBC SQL Server Driver][Net-Libraryname]

    These messages are issued by the SQL Server Net-Library, where Net-Libraryname is the display name of a SQL Server client Net-Library (for example, Named Pipes, Shared Memory, Multiprotocol, TCP/IP Sockets, NWLink IPX/SPX, or Banyan VINES).

  • [Microsoft][ODBC SQL Server Driver][SQL Server]

    These messages are issued by SQL Server. The remainder of the error message is the description from SQL Server, usually from master.dbo.sysmessages.

The ODBC specification allows ODBC drivers to define driver-specific fields in ODBC diagnostic records. The SQL Server ODBC driver maps SQL Server message parts into these SQL Server ODBC driver-specific diagnostic fields:

SQL_DIAG_SS_SEVERITY.
Contains the SQL Server severity level.
SQL_DIAG_SS_MSGSTATE.
Contains the SQL Server state. It is not related to the ODBC SQLSTATE code.
SQL_DIAG_SS_LINE.
Contains the number of the line containing the SQL statement generating the message.
SQL_DIAG_SS_PROCNAME.
Contains the name of the stored procedure generating the message, if appropriate.
SQL_DIAG_SS_SRVNAME.
Contains the name of the server from which the message came.


Embedded SQL for C Error Message Format

The errors and messages are returned to the application in SQLCA data structure. The Microsoft® SQL Server™ message parts map to fields in SQLCA data structure as described below:

  • sqlerrmc

    Contains text of the error message.

  • sqlerrd[1]

    Contains SQL Server error number.

  • sqlerrd[2]

    Contains SQL Server severity level.

  • Sqlstate

    Contains SQLSTATE run-time error codes as defined in embedded SQL. These SQLSTATE codes are not related to any of the parts of a SQL Server message.


DB-Library Error Message Format

DB-Library returns Microsoft® SQL Server™ errors and messages to call-back functions, written by application programmer.

The application programmer uses the dberrorhandle function to give DB-Library the address of the call-back function that handles the errors. When DB-Library determines that an error has occurred, it calls the call-back function identified by dberrorhandle. DB-Library passes the SQL Server error information into the parameters of the call back function as described below:

  • severity

    Contains severity of the error.

  • dberr

    Contains SQL Server error number.

  • dberrstr

    Contains description of the SQL Server error.

The application programmer uses the dbmsghandle function to give DB-Library the address of the call-back function that handles the messages. When DB-Library receives an informational message from SQL Server, it calls the call-back function identified by dbmsghandle.

DB-Library passes the SQL Server message information into the parameters of the call-back function as described below:

  • msgno

    Contains error number identifying the message.

  • msgstate

    Contains SQL Server message state.

  • severity

    Contains severity of the error condition.

  • msgtext

    Contains description of SQL Server message.

  • srvname

    Contains server name that generated the message.

  • procname

    Contains stored procedure name that generated the message.

  • line

    Contains line number in the stored procedure or the command batch that generated the message.

DB-Library calls the application error handler and message handler functions asynchronously as packets containing messages and errors are received from the server. This means DB-Library applications may receive errors and messages in a slightly different sequence than applications using either the OLE DB Provider for SQL Server or the SQL Server ODBC Driver.


Finding Supplemental Error Message Information

Over time, more information about error messages either already documented in this section or error messages not documented in this section may become available. For current error message information, see the “SQL Server version 7.0 Updated Error Message Information” button at http://www.microsoft.com/isapi/redir.dll?prd=support&ar=sqlbook.


Variables in System Error Message Text

These variables appear in the error message text provided with the system error message descriptions.

Symbol | Meaning
%d, %ld, or %D | Decimal integer
%x | Hexadecimal number
%ls or %.*ls | Character string
%S_type | SQL Server -defined structure
%c | Single character
%lf | Double floating-point number


Error Log Messages

In reviewing the error log, you may see one or more of these messages.

Error message text | Explanation
Failed to obtain TransactionDispenserInterface: XACT_E_TMNOTAVAILABLE | This message is an informational error message indicating that the Microsoft Distributed Transaction Coordinator (MS DTC) service is either currently not running on the server, or is currently unavailable. For more information about MS DTC, see your Microsoft Distributed Transaction Coordinator documentation.
Warning: Server cursor memory usage: %d pages. If this message repeats, see the Error Log Messages topic in Troubleshooting. For example:

Warning: Server cursor memory usage: 531 pages. If this message repeats, see the Error Log Messages topic in Troubleshooting.

Either too many cursors have been created and left open, or have not been deallocated. It is recommended that a cursor be closed and deallocated as soon as it is no longer needed.

In time-critical situations, the system administrator may need to terminate those connections that have not been closing or deallocating cursors using KILL.
Warning: SQL cache memory usage: %d (pages). If this condition persists, see the Error Log Messages topic in Troubleshooting. The SQL Server cache consumes memory and holds ad hoc and prepared SQL text. This message occurs if the SQL Server cache exceeds a certain number of pages of server memory. For example, this error occurs if one or more clients are preparing large numbers of SQL statements without performing corresponding unprepare operations. This lack of corresponding unprepare operations can be due to poor application design, an application bug, or repeated creation of prepared SQL text.

This message will be printed again if server memory changes significantly and if the memory consumption of the SQL Server cache remains high.

Either warn the suspected clients that server memory is at a low level, or terminate suspected connections using KILL.

See Also
Variables in System Error Message Text


System Error Message Overview

The master..sysmessages table contains one row for each system error or warning that can be returned by SQL Server. These are the columns in the sysmessages table.

Column name | Data type | Description
error | int | Unique error number
severity | smallint | Severity level of the error
dlevel | smallint | Reserved. For internal use only
description | nvarchar(255) | Explanation of the error with placeholders for parameters
mslangid | smallint | System message group ID

These topics list all messages in master..sysmessages.


Errors 1 - 999

Error | Severity | Description
1 | 10 | Version date of last upgrade: 10/11/90.
21 | 10 | Warning: Fatal error %d occurred at %S_DATE. Note the error and time, and contact your system administrator.
102 | 15 | Incorrect syntax near '%.*ls'.
103 | 15 | The %S_MSG that starts with '%.*ls' is too long. Maximum length is %d.
104 | 15 | ORDER BY items must appear in the select list if the statement contains a UNION operator.
105 | 15 | Unclosed quote before the character string '%.*ls'.
106 | 16 | Too many table names in the query. The maximum allowable is %d.
107 | 15 | The column prefix '%.*ls' does not match with a table name or alias name used in the query.
108 | 15 | The ORDER BY position number %ld is out of range of the number of items in the select list.
109 | 15 | There are more columns in the INSERT statement than values specified in the VALUES clause. The number of values in the VALUES clause must match the number of columns specified in the INSERT statement.
110 | 15 | There are fewer columns in the INSERT statement than values specified in the VALUES clause. The number of values in the VALUES clause must match the number of columns specified in the INSERT statement.
111 | 15 | '%ls' must be the first statement in a query batch.
112 | 15 | Variables are not allowed in the %ls statement.
113 | 15 | Missing end comment mark '*/'.
114 | 15 | Browse mode is invalid for a statement that assigns values to a variable.
116 | 15 | Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
117 | 15 | The %S_MSG name '%.*ls' contains more than the maximum number of prefixes. The maximum is %d.
118 | 15 | Only members of the sysadmin role can specify the %ls option for the %ls statement.
119 | 15 | Must pass parameter number %d and subsequent parameters as '@name = value'. After the form '@name = value' has been used, all subsequent parameters must be passed in the form '@name = value'.
120 | 15 | The select list for the INSERT statement contains fewer items than the insert list. The number of SELECT values must match the number of INSERT columns.
121 | 15 | The select list for the INSERT statement contains more items than the insert list. The number of SELECT values must match the number of INSERT columns.
123 | 15 | Batch/procedure exceeds maximum length of %d characters.
124 | 15 | CREATE PROCEDURE contains no statements.
125 | 15 | Case expressions may only be nested to level %d.
128 | 15 | The name '%.*ls' is not permitted in this context. Only constants, expressions, or variables allowed here. Column names are not permitted.
129 | 15 | Fillfactor %d is not a valid percentage; fillfactor must be between 1 and 100.
130 | 16 | Cannot perform an aggregate function on an expression containing an aggregate or a subquery.
131 | 15 | The size (%d) given to the %S_MSG '%.*ls' exceeds the maximum. The largest size allowed is %d.
132 | 15 | The label '%.*ls' has already been declared. Label names must be unique within a query batch or stored procedure.
133 | 15 | A GOTO statement references the label '%.*ls' but the label has not been declared.
134 | 15 | The variable name '%.*ls' has already been declared. Variable names must be unique within a query batch or stored procedure.
135 | 15 | Cannot use a BREAK statement outside the scope of a WHILE statement.
136 | 15 | Cannot use a CONTINUE statement outside the scope of a WHILE statement.
137 | 15 | Must declare the variable '%.*ls'.
138 | 15 | Correlation clause in a subquery not permitted.
139 | 15 | Cannot assign a default value to a local variable.
140 | 15 | Can only use IF UPDATE within a CREATE TRIGGER statement.
141 | 15 | A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations.
142 | 15 | Incorrect syntax for definition of the '%ls' constraint.
143 | 15 | A COMPUTE BY item was not found in the order by list. All expressions in the compute by list must also be present in the order by list.
144 | 15 | Cannot use an aggregate or a subquery in an expression used for the group by list of a GROUP BY clause.
145 | 15 | ORDER BY items must appear in the select list if SELECT DISTINCT is specified.
146 | 15 | Could not allocate ancillary table for a subquery. Maximum number of tables in a query (%d) exceeded.
147 | 15 | An aggregate may not appear in the WHERE clause unless it is in a subquery contained in a HAVING clause or a select list, and the column being aggregated is an outer reference.
148 | 15 | Incorrect time syntax in time string '%.*ls' used with WAITFOR.
149 | 15 | Time value '%.*ls' used with WAITFOR is not a valid value. Check date/time syntax.
150 | 15 | Both terms of an outer join must contain columns.
151 | 15 | '%.*ls' is an invalid money value.
153 | 15 | Invalid usage of the option %.*ls in the %ls statement.
154 | 15 | %S_MSG is not allowed in %S_MSG.
155 | 15 | '%.*ls' is not a recognized %ls option.
156 | 15 | Incorrect syntax near the keyword '%.*ls'.
157 | 15 | An aggregate may not appear in the set list of an UPDATE statement.
159 | 15 | For DROP INDEX, you must give both the table and the index name, in the form tablename.indexname.
160 | 15 | Rule does not contain a variable.
161 | 15 | Rule contains more than one variable.
163 | 15 | The compute by list does not match the order by list.
164 | 15 | GROUP BY expressions must refer to column names that appear in the select list.
165 | 16 | Privilege %ls may not be granted or revoked.
166 | 15 | '%ls' does not allow specifying the database name as a prefix to the object name.
167 | 16 | Cannot create a trigger on a temporary object.
168 | 15 | The %S_MSG '%.*ls' is out of the range of computer representation (%d bytes).
169 | 15 | A column has been specified more than once in the order by list. Columns in the order by list must be unique.
170 | 15 | Line %d: Incorrect syntax near '%.*ls'.
171 | 15 | Cannot use SELECT INTO in browse mode.
172 | 15 | Cannot use HOLDLOCK in browse mode.
173 | 15 | The definition for column '%.*ls' must include a data type.
174 | 15 | The %ls function requires %d arguments.
177 | 15 | The IDENTITY function can only be used when the SELECT statement has an INTO clause.
178 | 15 | A RETURN statement with a return status can only be used in a stored procedure.
179 | 15 | Cannot use the OUTPUT option when passing a constant to a stored procedure.
180 | 15 | There are too many parameters in this %ls statement. The maximum number is %d.
181 | 15 | Cannot use the OUTPUT option in a DECLARE statement.
182 | 15 | Table and column names must be supplied for the READTEXT or WRITETEXT utility.
183 | 15 | The scale (%d) for column '%.*ls' must be within the range %d to %d.
185 | 15 | Data stream is invalid for WRITETEXT statement in bulk form.
186 | 15 | Data stream missing from WRITETEXT statement.
188 | 15 | Cannot specify a log device in a CREATE DATABASE statement without also specifying at least one non-log device.
189 | 15 | The %ls function requires %d to %d arguments.
190 | 15 | Cannot update the function '%.*ls'.
191 | 15 | Some part of your SQL statement is nested too deeply. Re-write the query or break it up into smaller queries.
192 | 16 | The scale must be less than or equal to the precision.
193 | 15 | The object or column name starting with '%.*ls' is too long. The maximum length is %d characters.
194 | 15 | A SELECT INTO statement cannot contain a SELECT statement that assigns values to a variable.
195 | 15 | '%.*ls' is not a recognized %S_MSG.
196 | 15 | SELECT INTO must be the first query in a SQL statement containing a UNION operator.
198 | 15 | Browse mode is invalid for statements containing a UNION operator.
199 | 15 | An INSERT statement cannot contain a SELECT statement that assigns values to a variable.
201 | 16 | Procedure '%.*ls' expects parameter '%.*ls', which was not supplied.
203 | 16 | The name '%.*ls' is not a valid identifier.
204 | 20 | Normalization error in node %ls.
205 | 16 | All queries in a SQL statement containing a UNION operator must have an equal number of expressions in their target lists.
206 | 16 | Operand type clash: %ls is incompatible with %ls
207 | 16 | Invalid column name '%.*ls'.
208 | 16 | Invalid object name '%.*ls'.
209 | 16 | Ambiguous column name '%.*ls'.
210 | 16 | Syntax error converting datetime from binary/varbinary string.
212 | 16 | Expression result length exceeds the maximum. %d max, %d found.
213 | 16 | Insert Error: Column name or number of supplied values does not match table definition.
214 | 16 | Cannot convert parameter '%ls' to %ls data type expected by procedure.
217 | 16 | Maximum stored procedure nesting level exceeded (limit %d).
220 | 16 | Arithmetic overflow error for data type %ls, value = %ld.
221 | 10 | FIPS Warning: Implicit conversion from %ls to %ls.
223 | 11 | Object ID %ld specified as a default for table ID %ld, column ID %d is missing or not of type default.
224 | 11 | Object ID %ld specified as a rule for table ID %ld, column ID %d is missing or not of type default.
226 | 16 | %ls statement not allowed within multi-statement transaction.
229 | 14 | %ls permission denied on object '%.*ls', database '%.*ls', owner '%.*ls'.
230 | 14 | %ls permission denied on column '%.*ls' of object '%.*ls', database '%.*ls', owner '%.*ls'.
231 | 11 | No such default. ID = %ld, database ID = %d.
232 | 16 | Arithmetic overflow error for type %ls, value = %f.
233 | 16 | The column '%.*ls' in table '%.*ls' cannot be null.
234 | 16 | There is insufficient result space to convert a money value to %ls.
235 | 16 | Cannot convert a char value to money. The char value has incorrect syntax.
236 | 16 | The conversion from char data type to money resulted in a money overflow error.
237 | 16 | There is insufficient result space to convert a money value to %ls.
238 | 16 | There is insufficient result space to convert the %ls value (= %d) to the money data type.
241 | 16 | Syntax error converting datetime from character string.
242 | 16 | The conversion of a char data type to a datetime data type resulted in an out of range datetime value.
243 | 16 | Type %.*ls is not a defined system type.
244 | 16 | The conversion of the %ls value '%.*ls' overflowed an %hs column. Use a larger integer column.
245 | 16 | Syntax error converting the %ls value '%.*ls' to a column of data type %ls.
248 | 16 | The conversion of the %ls value '%.*ls' overflowed an int column. Maximum integer value exceeded.
251 | 16 | Could not allocate ancillary table for query optimization. Maximum number of tables in a query (%d) exceeded.
252 | 16 | Cannot group by a bit column.
256 | 16 | The data type %ls is invalid for the %ls function. Allowed types are: char/varchar, nchar/nvarchar, and binary/varbinary.
257 | 16 | Implicit conversion from data type %ls to %ls is not allowed. Use the CONVERT function to run this query.
259 | 16 | Ad hoc updates to system catalogs are not enabled. The system administrator must reconfigure SQL Server to allow this.
260 | 16 | Disallowed implicit conversion from data type %ls to data type %ls, table '%ls', column '%ls'. Use the CONVERT function to run this query.
261 | 16 | '%.*ls' is not a recognized function.
262 | 16 | %ls permission denied, database '%.*ls', owner '%.*ls'.
263 | 16 | Must specify table to select from.
264 | 16 | Column name '%.*ls' appears more than once in the result column list.
266 | 16 | Transaction count after EXECUTE indicates that a COMMIT or ROLLBACK TRANSACTION statement is missing. Previous count = %ld, current count = %ld.
267 | 16 | Object '%.*ls' cannot be found.
268 | 16 | Cannot run SELECT INTO in this database. The database owner must run sp_dboption to enable this option.
270 | 16 | Table '%.*ls' cannot be modified.
271 | 16 | Column '%.*ls' cannot be modified because it is a computed column.
272 | 16 | Cannot update a timestamp column.
273 | 16 | Cannot insert a non-null value into a timestamp column. Use INSERT with a column list or with a default of NULL for the timestamp column.
278 | 16 | The text, ntext, and image data types cannot be used in a GROUP BY clause.
279 | 16 | The text, ntext, and image data types are invalid in this subquery or aggregate expression.
280 | 16 | Only text, ntext, and image data types are valid with the TEXTPTR function.
281 | 16 | %d is not a valid style number when converting from datetime to a character string.
282 | 10 | The '%.*ls' procedure attempted to return a status of NULL, which is not allowed. A status of 0 will be returned instead.
284 | 16 | Rules cannot be bound to text, ntext, or image data types.
285 | 16 | The READTEXT and WRITETEXT statements cannot be used with views.
286 | 16 | The logical tables INSERTED and DELETED cannot be updated.
287 | 16 | The %ls statement is not allowed within a trigger.
288 | 16 | The PATINDEX function operates on char, nchar, varchar, nvarchar, text, and ntext data types only.
292 | 16 | There is insufficient result space to convert a smallmoney value to %ls.
293 | 16 | Cannot convert char value to smallmoney. The char value has incorrect syntax.
294 | 16 | The conversion from char data type to smallmoney data type resulted in a smallmoney overflow error.
295 | 16 | Syntax error converting character string to smalldatetime data type.
296 | 16 | The conversion of char data type to smalldatetime data type resulted in an out of range smalldatetime value.
298 | 16 | The conversion from datetime data type to smalldatetime data type resulted in a smalldatetime overflow error.
299 | 16 | The DATEADD function was called with bad type %ls.
301 | 16 | Query contains an outer-join request that is not permitted.
303 | 16 | The table '%.*ls' is an inner member of an outer-join clause. This is not allowed if the table also participates in a regular join clause.
306 | 16 | The text, ntext, and image data types cannot be used in the WHERE, HAVING, or ON clause, except with the LIKE or IS NULL predicates.
307 | 16 | Index ID %d on table '%.*ls' (specified in the FROM clause) does not exist.
308 | 16 | Index '%.*ls' on table '%.*ls' (specified in the FROM clause) does not exist.
310 | 16 | Invalid escape sequence. Valid characters after ESC are: an ESC pair, underscore, percent sign.
311 | 16 | Cannot use text, ntext, or image columns in the 'inserted' and 'deleted' tables.
312 | 16 | Cannot reference text, ntext, or image columns in a filter stored procedure.
401 | 16 | Unimplemented statement or expression %ls.
403 | 16 | Invalid operator for data type. Operator equals %ls, type equals %ls.
409 | 16 | The %ls operation cannot take a %ls data type as an argument.
410 | 20 | COMPUTE clause #%d 'BY' expression #%d is not in the order by list.
411 | 20 | COMPUTE clause #%d, aggregate expression #%d is not in the select list.
420 | 16 | The text, ntext, and image data types cannot be used in an ORDER BY clause.
425 | 16 | Data type %ls of receiving variable is not equal to the data type %ls of column '%.*ls'.
426 | 16 | The length %d of the receiving variable is less than the length %d of the column '%.*ls'.
427 | 20 | Could not load sysprocedures entries for constraint ID %d in database ID %d.
428 | 20 | Could not find row in sysconstraints for constraint ID %d in database ID %d.
429 | 20 | Could not find new constraint ID %d in sysconstraints, database ID %d, at compile time.
430 | 20 | Could not resolve table name for object ID %d, database ID %d, when compiling foreign key.
431 | 19 | Could not bind foreign key constraint. Too many tables involved in the query.
433 | 20 | Could not find CHECK constraint for '%.*ls', although the table is flagged as having one.
436 | 20 | Could not open referenced table ID %d in database ID %d.
437 | 20 | Could not resolve the referenced column name in table ID %d.
438 | 20 | Could not resolve the referencing column name in table ID %d.
439 | 20 | Could not find FOREIGN KEY constraints for table '%.*ls' in database ID %d although the table is flagged as having them.
441 | 16 | Cannot use the '%ls' function on a remote data source.
505 | 16 | Current user account was invoked with SETUSER. Changing databases is not allowed.
506 | 16 | Invalid ESCAPE character '%.*hs' has been specified in a LIKE predicate.
507 | 16 | Invalid argument %d specified for SET ROWCOUNT.
509 | 11 | User name '%.*ls' not found.
510 | 16 | Cannot create a work table row larger than allowable maximum. Resubmit your query with the ROBUST PLAN hint.
511 | 16 | Cannot create a row of size %d which is greater than the allowable maximum of %d.
512 | 16 | Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
513 | 16 | A column insert or update conflicts with a rule imposed by a previous CREATE RULE statement. The statement was aborted. The conflict occurred in database '%.*ls', table '%.*ls', column '%.*ls'.
515 | 16 | Cannot insert the value NULL into column '%.*ls', table '%.*ls'; column does not allow nulls. %ls fails.
516 | 18 | Could not get system date/time.
517 | 16 | Adding a value to a '%ls' column caused overflow.
518 | 16 | Cannot convert data type %ls to %ls.
528 | 20 | System error detected during attempt to use the 'upsleep' system function.
529 | 16 | Explicit conversion from data type %ls to %ls is not allowed.
532 | 16 | The timestamp (changed to %S_TS) shows that the row has been updated by another user.
535 | 16 | Difference of two datetime columns caused overflow at runtime.
536 | 16 | Invalid length parameter passed to the substring function.
538 | 16 | Cannot find '%.*ls'. This language may have been dropped. Contact your system administrator.
542 | 16 | An invalid datetime value was encountered. Value exceeds the year 9999.
544 | 16 | Cannot insert explicit value for identity column in table '%.*ls' when IDENTITY_INSERT is set to OFF.
545 | 16 | Explicit value must be specified for identity column in table '%.*ls' when IDENTITY_INSERT is set to ON.
547 | 16 | %ls statement conflicted with %ls %ls constraint '%.*ls'. The conflict occurred in database '%.*ls', table '%.*ls'%ls%.*ls%ls.
548 | 16 | Cannot perform direct %ls to range maintained by replication. The conflict occurred in database '%.*ls', table '%.*ls'%ls%.*ls%ls.
550 | 16 | The attempted insert or update failed because the target view either specifies WITH CHECK OPTION or spans a view that specifies WITH CHECK OPTION and one or more rows resulting from the operation did not qualify under the CHECK OPTION constraint.
551 | 16 | The checksum has changed to %d. This shows that the row has been updated by another user.
553 | 16 | %hs over nullable side of outer join query on table '%ls'.
555 | 16 | User-defined functions are not yet enabled.
556 | 16 | INSERT EXEC failed because the stored procedure altered the schema of the target table.
601 | 12 | Could not continue scan with NOLOCK due to data movement.
602 | 21 | Could not find row in sysindexes for database ID %d, object ID %ld, index ID %d. Run DBCC CHECKTABLE on sysindexes.
604 | 21 | Could not find row in sysobjects for object ID %ld in database '%.*ls'. Run DBCC CHECKTABLE on sysobjects.
605 | 21 | Attempt to fetch logical page %S_PGID in database '%.*ls' belongs to object '%.*ls', not to object '%.*ls'.
607 | 21 | Insufficient room was allocated for search arguments in the session descriptor for object '%.*ls'. Only %d search arguments were anticipated.
615 | 21 | Could not find database table ID %d, name '%.*ls'.
617 | 20 | Descriptor for object ID %ld in database ID %d not found in the hash table during attempt to unhash it.
618 | 21 | A varno of %d was passed to the opentable system function. The largest valid value is %d.
623 | 21 | Could not retrieve row from page by RID because logical page %S_PGID is not a data page. %S_RID. %S_PAGE.
624 | 21 | Could not retrieve row from page by RID because the requested RID has a higher number than the last RID on the page. %S_RID.%S_PAGE, DBID %d.
625 | 21 | Could not retrieve row from logical page %S_PGID by RID because the entry in the offset table (%d) for that RID (%d) is less than or equal to 0.
626 | 16 | Cannot use ROLLBACK with a savepoint within a distributed transaction.
627 | 16 | Cannot use SAVE TRANSACTION within a distributed transaction.
628 | 13 | Cannot issue SAVE TRANSACTION when there is no active transaction.
635 | 20 | Process %d tried to remove DES resource lock %S_DES, which it does not hold.
637 | 20 | Index shrink program returned invalid status of 0.
639 | 21 | Could not fetch logical page %S_PGID, database ID %d. The page is not currently allocated.
644 | 21 | Could not find the index entry for RID '%.*hs' in index page %S_PGID, index ID %d, database '%.*ls'.
649 | 21 | Could not find the clustered index entry for page %S_PGID, object ID %ld, status 0x%x. Index page %S_PGID, in database '%.*ls', was searched for this entry.
650 | 16 | You can only specify the READPAST lock in the READ COMMITTED or REPEATABLE READ isolation levels.
651 | 16 | Cannot use %hs granularity hint on table '%.*ls' because locking at the specified granularity is inhibited.
652 | 16 | Index ID %d for table '%.*ls' resides on a read-only filegroup which cannot be modified.
653 | 20 | Two buffers are conflicting for the same keep slot in table '%.*ls'.
654 | 20 | No slots are free to keep buffers for table '%.*ls'.
655 | 20 | Expected to find buffer in keep slot for table '%.*ls'.
666 | 16 | Maximum system-generated unique value for a duplicate group exceeded for table ID %d, index ID %d. Dropping and re-creating the index may fix the problem; otherwise use another clustering key.
701 | 19 | There is insufficient system memory to run this query.
708 | 10 | Warning: Due to low virtual memory, special reserved memory used %d times since startup. Increase virtual memory on server.
802 | 17 | No more buffers can be stolen.
804 | 20 | Could not find buffer 0x%lx holding logical page %S_PGID in the SDES 0x%lx kept buffer pool for object '%.*ls'.
809 | 20 | Buffer 0x%lx, allocation page %S_PGID, in database '%.*ls' is not in allocation buffer pool in PSS (process status structure). Contact Technical Support.
813 | 20 | Logical page %S_PGID in database ID %d is already hashed.
816 | 20 | Process ID %d tried to remove a buffer resource lock %S_BUF that it does not hold in SDES %S_SDES. Contact Technical Support.
818 | 19 | There is no room to hold the buffer resource lock %S_BUF in SDES %S_SDES. Contact Technical Support.
821 | 20 | Could not unhash buffer at 0x%lx with a buffer page number of %S_PGID and database ID %d with HASHED status set. The buffer was not found. %S_PAGE.
822 | 21 | Could not start I/O for request %S_BLKIOPTR.
823 | 24 | I/O error %ls detected during %S_MSG of %S_BUF.
834 | 21 | The bufclean system function was called on dirty buffer (page %S_PGID, stat %#x/%#x, objid %#x, sstat%#x).
840 | 17 | Device '%.*ls' (physical name '%.*ls', virtual device number %d) is not available. Contact the system administrator for assistance.
844 | 10 | Time out occurred while waiting for buffer latch type %d, bp %#x, page %S_PGID, stat %#x, object ID %d:%d:%d, waittime %d. Continuing to wait.
845 | 17 | Time out occurred while waiting for buffer latch type %d for page %S_PGID, database ID %d, object ID %d, index ID %d.
901 | 21 | Could not find descriptor for database ID %d, object ID %ld in hash table after hashing it.
903 | 22 | Could not find row in sysindexes for clustered index on system catalog %ld in database ID %d. This index should exist in all databases. Run DBCC CHECKTABLE on sysindexes in the database.
906 | 22 | Could not locate row in sysobjects for system catalog '%.*ls' in database '%.*ls'. This system catalog should exist in all databases. Run DBCC CHECKTABLE on sysobjects in this database.
911 | 16 | Could not locate entry in sysdatabases for database '%.*ls'. No entry found with that name. Make sure that the name is entered correctly.
913 | 22 | Could not find database ID %d. Database may not be activated yet or may be in transition.
916 | 14 | Server user '%.*ls' is not a valid user in database '%.*ls'.
921 | 14 | Database '%.*ls' has not been recovered yet. Wait and try again.
922 | 14 | Database '%.*ls' is being recovered. Waiting until recovery is finished.
923 | 14 | User %d not allowed in database '%.*ls'. Only the owner can access this database.
924 | 14 | Database '%.*ls' is already open and can only have one user at a time.
925 | 19 | Maximum number of databases used for each query has been exceeded. The maximum allowed is %d.
926 | 14 | Database '%.*ls' cannot be opened. It has been marked SUSPECT by recovery. See the SQL Server errorlog for more information.
927 | 14 | Database '%.*ls' cannot be opened. It is in the middle of a restore.
929 | 20 | Attempting to close a database that is not already open. Report problem to Technical Support.
941 | 14 | Cannot open database '%.*ls'. It has not been upgraded to the latest format.
942 | 14 | Database '%.*ls' cannot be opened because it is offline.
943 | 14 | Database '%.*ls' cannot be opened because its version (%d) is later than the current server version (%d).
944 | 10 | Converting database '%.*ls' from version %d to the current version %d.
945 | 16 | Database '%.*ls' cannot be opened because some of the files could not be activated.
946 | 14 | Cannot open database '%.*ls' version %d. Upgrade the database to the latest version.
947 | 16 | Error while closing database '%.*ls' cleanly.


Errors 1000 - 1999

Error | Severity | Description
1001 | 16 | Line %d: Length or precision specification %d is invalid.
1002 | 16 | Line %d: Specified scale %d is invalid.
1003 | 15 | Line %d: %ls clause allowed only for %ls.
1005 | 15 | Line %d: Invalid procedure number (%d). Must be between 1 and 32767.
1006 | 15 | CREATE TRIGGER contains no statements.
1007 | 15 | The %S_MSG '%.*ls' is out of the range for numeric representation (maximum precision %d).
1008 | 15 | The SELECT item identified by the ORDER BY number %d contains a variable as part of the expression identifying a column position. Variables are only allowed when ordering by an expression referencing a column name.
1010 | 15 | Invalid escape character '%.*ls'.
1011 | 15 | The correlation name '%.*ls' is specified multiple times in a FROM clause.
1012 | 15 | The correlation name '%.*ls' has the same exposed name as table '%.*ls'.
1013 | 15 | Tables '%.*ls' and '%.*ls' have the same exposed names. Use correlation names to distinguish them.
1015 | 15 | An aggregate cannot appear in an ON clause unless it is in a subquery contained in a HAVING clause or select list, and the column being aggregated is an outer reference.
1016 | 15 | Outer join operators cannot be specified in a query containing joined tables.
1019 | 15 | Invalid column list after object name in GRANT/REVOKE statement.
1020 | 15 | Cannot specify column list for INSERT/DELETE/EXECUTE privileges in the GRANT/REVOKE statement.
1021 | 10 | FIPS Warning: Line %d has the non-ANSI statement '%ls'.
1022 | 10 | FIPS Warning: Line %d has the non-ANSI clause '%ls'.
1023 | 15 | Invalid parameter %d specified for %ls.
1024 | 10 | FIPS Warning: Line %d has the non-ANSI function '%ls'.
1025 | 10 | FIPS Warning: The length of identifier '%.*ls' exceeds 18.
1027 | 15 | Too many expressions are specified in the GROUP BY clause. The maximum number is %d when either CUBE or ROLLUP is specified.
1028 | 15 | The CUBE and ROLLUP options are not allowed in a GROUP BY ALL clause.
1029 | 15 | Browse mode is invalid for subqueries and derived tables.
1031 | 15 | Percent values must be between 0 and 100.
1032 | 16 | Cannot use the column prefix '%.*ls'. This must match the object in the UPDATE clause '%.*ls'.
1033 | 16 | An ORDER BY clause is invalid in views, derived tables, and subqueries unless TOP is also specified.
1035 | 15 | Incorrect syntax near '%.*ls', expected '%.*ls'.
1036 | 15 | File option %hs is required in this CREATE/ALTER DATABASE statement.
1037 | 15 | The CASCADE, WITH GRANT or AS options cannot be specified with statement permissions.
1038 | 15 | Cannot use empty object or column names. Use a single space if necessary.
1039 | 15 | SHOWPLAN is not available. Use SHOWPLAN_TEXT or SHOWPLAN_ALL instead.
1040 | 15 | Mixing old and new syntax in CREATE/ALTER DATABASE statement is not allowed.
1041 | 15 | Option %.*ls is not allowed for a LOG file.
1042 | 15 | Conflicting %ls optimizer hints specified.
1043 | 15 | '%hs' is not yet implemented.
1044 | 15 | Cannot use an existing function name to specify a stored procedure name.
1045 | 15 | Aggregates are not allowed in this context. Only scalar expressions are allowed.
1046 | 15 | Subqueries are not allowed in this context. Only scalar expressions are allowed.
1047 | 15 | Conflicting locking hints specified.
1048 | 15 | Conflicting cursor options %ls and %ls.
1049 | 15 | Mixing old and new syntax to specify cursor options is not allowed.
1050 | 15 | This syntax is only allowed within the stored procedure sp_executesql.
1051 | 15 | Cursor parameters in a stored procedure must be declared with OUTPUT and VARYING options, and they must be specified in the order CURSOR VARYING OUTPUT.
1052 | 15 | Conflicting %ls options %ls and %ls.
1053 | 15 | For DROP STATISTICS, you must give both the table and the column name in the form 'tablename.column'.
1055 | 15 | '%.*ls' is an invalid name because it contains a NULL character.
1056 | 15 | The maximum number of elements in the select list is %d and you have supplied %d.
1057 | 15 | The IDENTITY function cannot be used with a SELECT INTO statement containing a UNION operator.
1058 | 15 | Cannot specify both READ_ONLY and FOR READ ONLY on a cursor declaration.
1059 | 15 | Cannot set or reset the %ls option within a procedure.
1060 | 15 | The number of rows in the TOP clause must be an integer.
1061 | 16 | The text/ntext/image constants are not yet implemented.
1062 | 16 | The TOP N WITH TIES clause is not allowed without a corresponding ORDER BY clause.
1063 | 16 | A filegroup cannot be added using ALTER DATABASE ADD FILE. Use ALTER DATABASE ADD FILEGROUP.
1064 | 16 | A filegroup cannot be used with log files.
1065 | 15 | The NOLOCK, READUNCOMMITTED, and READPAST lock hints are only allowed in a SELECT statement.
1066 | 10 | Warning. Line %d: The option '%ls' is obsolete and has no effect.
1067 | 15 | The SET SHOWPLAN statements must be the only statements in the batch.
1068 | 16 | Only one list of index hints per table is allowed.
1069 | 16 | Index hints are only allowed in a FROM clause.
1070 | 15 | CREATE INDEX option '%.*ls' is no longer supported.
1071 | 16 | Cannot specify a JOIN algorithm with a remote JOIN.
1072 | 16 | A REMOTE hint can only be specified with an INNER JOIN clause.
1073 | 15 | '%.*ls' is not a recognized cursor option for cursor %.*ls.
1101 | 17 | Could not allocate new page for database '%.*ls'. There are no more pages available in filegroup %.*ls. Space can be created by dropping objects, adding additional files, or allowing file growth.
1102 | 22 | IAM page %S_PGID for object ID %ld is incorrect. The %S_MSG ID on page is %ld; should be %ld. The entry in sysindexes may be incorrect or the IAM page may be corrupt.
1103 | 21 | Allocation page %S_PGID in database '%.*ls' has different segment ID than that of the object which is being allocated to. Run DBCC CHECKALLOC.
1105 | 17 | Could not allocate space for object '%.*ls' in database '%.*ls' because the '%.*ls' filegroup is full.
1109 | 21 | Could not read allocation page %S_PGID because either the object ID (%ld) is not correct, or the page ID (%S_PGID) is not correct.
1201 | 20 | The page_lock system function was called with a mode %d that is not permitted.
1203 | 20 | Process ID %d attempting to unlock unowned resource %.*ls.
1204 | 19 | SQL Server has run out of LOCKS. Rerun your statement when there are fewer active users, or ask the system administrator to reconfigure SQL Server with more LOCKS.
1205 | 13 | Your transaction (process ID #%d) was deadlocked with another process and has been chosen as the deadlock victim. Rerun your transaction.
1211 | 13 | Process ID %d was chosen as the deadlock victim with P_BACKOUT bit set.
1220 | 17 | No more lock classes available from transaction.
1221 | 20 | Invalid lock class for release call.
1222 | 13 | Lock request time out period exceeded.
1501 | 20 | Sort failure.
1505 | 14 | CREATE UNIQUE INDEX aborted because a duplicate key was found. Most significant primary key is '%S_KEY'.
1507 | 10 | Warning: Deleted duplicate row. Primary key is '%S_KEY'.
1508 | 14 | CREATE INDEX aborted because a duplicate row was found. Primary key is '%S_KEY'.
1509 | 20 | Row compare failure.
1510 | 17 | Sort failed. Out of space or locks in database '%.*ls'.
1511 | 20 | Sort cannot be reconciled with transaction log.
1522 | 20 | Sort failure. Prevented overwriting of allocation page in database '%.*ls' by aborting sort.
1523 | 20 | Sort failure. Prevented incorrect extent deallocation by aborting sort.
1528 | 21 | Character data comparison failure. An unrecognized Sort-Map-Element type (%d) was found in the server-wide default sort table at SMEL entry [%d].
1529 | 21 | Character data comparison failure. A list of Sort-Map-Elements from the server-wide default sort table does not end properly. This list begins at SMEL entry [%d].
1530 | 16 | CREATE INDEX with DROP_EXISTING was aborted because a row was out of order. Most significant offending primary key is '%S_KEY'. Explicitly drop and create the index instead.
1531 | 16 | The SORTED_DATA_REORG option cannot be used for a nonclustered index if the keys are not unique within the table. CREATE INDEX was aborted because of duplicate keys. Primary key is '%S_KEY'.
1532 | 20 | New sort run starting on page %S_PGID found extent not marked as shared.
1533 | 20 | Cannot share extent %S_PGID among more than 8 sort runs.
1534 | 20 | Extent %S_PGID not found in shared extent directory.
1535 | 20 | Cannot share extent %S_PGID with shared extent directory full.
1536 | 20 | Cannot build a non-clustered index on a memory-only work table.
1537 | 20 | Cannot suspend a sort not in row input phase.
1538 | 20 | Cannot insert into a sort not in row input phase.
1540 | 16 | Cannot sort a row of size %d, which is greater than the allowable maximum of %d.
1619 | 21 | Could not open tempdb. Cannot continue.
1701 | 16 | Creation of table '%.*ls' failed because the row size would be %d, including internal overhead. This exceeds the maximum allowable table row size, %d.
1702 | 16 | CREATE TABLE failed because column '%.*ls' in table '%.*ls' exceeds the maximum of %d columns.
1703 | 17 | Could not allocate disk space for a work table in database '%.*ls'. You may be able to free up space by using BACKUP LOG, or you may want to extend the size of the database by using ALTER DATABASE.
1704 | 16 | Only members of the sysadmin role can create the system table '%.*ls'.
1705 | 16 | You must create system table '%.*ls' in the master database.
1706 | 16 | System table '%.*ls' was not created, because ad hoc updates to system catalogs are not enabled.
1708 | 10 | The total row size (%d) for table '%.*ls' exceeds the maximum number of bytes per row (%d). Rows that exceed the maximum number of bytes will not be added.
1709 | 16 | Cannot use TEXTIMAGE_ON when a table has no text, ntext, or image columns.
1750 | 10 | Could not create constraint. See previous errors.
1752 | 16 | Could not create DEFAULT for column '%.*ls' as it is not a valid column in the table '%.*ls'.
1753 | 16 | Column '%.*ls.%.*ls' is not the same length as referencing column '%.*ls.%.*ls' in foreign key '%.*ls'.
1754 | 16 | Defaults cannot be created on columns with an IDENTITY attribute. Table '%.*ls', column '%.*ls'.
1755 | 16 | Defaults cannot be created on columns of data type timestamp. Table '%.*ls', column '%.*ls'.
1756 | 10 | Skipping FOREIGN KEY constraint '%.*ls' definition for temporary table.
1759 | 16 | Invalid column '%.*ls' specified in constraint definition.
1760 | 16 | Constraints of type %ls cannot be created on columns of type %ls.
1763 | 16 | Cross-database foreign key references are not supported. Foreign key '%.*ls'.
1766 | 16 | Foreign key references to temporary tables are not supported. Foreign key '%.*ls'.
1767 | 16 | Foreign key '%.*ls' references invalid table '%.*ls'.
1768 | 16 | Foreign key '%.*ls' references object '%.*ls' which is not a user table.
1769 | 16 | Foreign key '%.*ls' references invalid column '%.*ls' in referencing table '%.*ls'.
1770 | 16 | Foreign key '%.*ls' references invalid column '%.*ls' in referenced table '%.*ls'.
1772 | 16 | Foreign key '%.*ls' defines an invalid relationship between a user table and system table.
1773 | 16 | Foreign key '%.*ls' has implicit reference to object '%.*ls' which does not have a primary key defined on it.
1774 | 16 | The number of columns in the referencing column list for foreign key '%.*ls' does not match those of the primary key in the referenced table '%.*ls'.
1776 | 16 | There are no primary or candidate keys in the referenced table '%.*ls' that match the referencing column list in the foreign key '%.*ls'.
1777 | 14 | User does not have correct permissions on referenced table '%.*ls' to create foreign key '%.*ls'.
1778 | 16 | Column '%.*ls.%.*ls' is not the same data type as referencing column '%.*ls.%.*ls' in foreign key '%.*ls'.
1779 | 16 | Table '%.*ls' already has a primary key defined on it.
1780 | 20 | Could not find column ID %d in syscolumns for object ID %d in database ID %d.
1781 | 16 | Column already has a DEFAULT bound to it.
1801 | 16 | Database '%.*ls' already exists.
1802 | 11 | CREATE DATABASE failed. Some file names listed could not be created. Check previous errors.
1803 | 17 | CREATE DATABASE failed. Could not allocate enough disk space for a new database on the named disks. Total space allocated must be at least %d MB to a accommodate copy of the model database.
1804 | 10 | There is no disk named '%.*ls'. Checking other disk names.
1805 | 10 | The CREATE DATABASE process is allocating %.2f MB on disk '%.*ls'.
1807 | 17 | Could not obtain exclusive lock on database '%.*ls'. Retry the operation later.
1808 | 21 | Default devices are not supported.
1811 | 16 | '%.*ls' is the wrong type of device for CREATE DATABASE or ALTER DATABASE. Check sysdevices. The statement is aborted.
1813 | 16 | Could not open new database '%.*ls'. CREATE DATABASE is aborted.
1814 | 10 | Could not create tempdb. If space is low, extend the amount of space and restart.
1816 | 16 | Could not attach the database because the character set, sort order, or Unicode collation for the database differs from this server.
1817 | 10 | Warning: %ls %ld in database differs from server %ls of %ld.
1818 | 16 | Primary log file '%ls' is missing and the database was not cleanly shut down so it cannot be rebuilt.
1819 | 10 | Could not create default log file because the name was too long.
1820 | 16 | Disk '%.*ls' is already completely used by other databases. It can be expanded with DISK RESIZE.
1826 | 16 | User-defined filegroups are not allowed on '%hs'.
1827 | 16 | CREATE/ALTER DATABASE failed because the resulting cumulative database size would exceed your licensed limit of %d MB per %S_MSG.
1828 | 16 | The file named '%.*ls' is already in use. Choose another name.
1829 | 16 | The FOR ATTACH option requires that at least the primary file be specified.
1830 | 16 | The files '%.*ls' and '%.*ls' are both primary files. A database can only have one primary file.
1831 | 10 | Successfully %ls database '%.*ls'.
1832 | 20 | Could not attach database '%.*ls' to file '%.*ls'.
1901 | 16 | Column '%.*ls'. Cannot create index on a column of bit data type.
1902 | 16 | Cannot create more than one clustered index on table '%.*ls'. Drop the existing clustered index '%.*ls' before creating another.
1903 | 16 | %d is the maximum allowable size of an index. The composite index specified is %d bytes.
1904 | 16 | Cannot specify more than %d column names for index key list. %d specified.
1905 | 21 | Could not find 'zero' row for index '%.*ls' the table in sysindexes.
1906 | 11 | Cannot create an index on table '%.*ls', because this table does not exist in database '%.*ls'.
1909 | 16 | Cannot use duplicate column names in index key list. Column name '%.*ls' listed more than once.
1910 | 16 | Cannot create more than %d indexes or column statistics on one table.
1911 | 16 | Column name '%.*ls' does not exist in the target table.
1913 | 16 | There is already an index on table '%.*ls' named '%.*ls'.
1914 | 16 | Cannot create index on object '%.*ls' because it is not a user table.
1915 | 16 | Only members of the sysadmin role or the owner of table '%.*ls' can create an index on it.
1916 | 16 | CREATE INDEX options %ls and %ls are mutually exclusive.
1918 | 10 | Index (ID = %d) is being rebuilt.
1919 | 16 | Column '%.*ls'. Cannot create index on a column of text, ntext, or image data type.
1920 | 10 | Skipping rebuild of index ID %d, which is on a read-only filegroup.
1921 | 16 | Invalid filegroup '%.*ls' specified.
1922 | 16 | Filegroup '%.*ls' has no files assigned to it. Tables, indexes, and text, ntext, and image columns cannot be created on this filegroup.
1923 | 10 | The clustered index has been dropped.
1924 | 16 | Filegroup '%.*ls' is read-only.
1925 | 16 | Cannot convert a clustered index to a non-clustered index using the DROP_EXISTING option.
1926 | 16 | Cannot create a clustered index because non-clustered index ID %d is on a read-only filegroup.
1927 | 16 | There are already statistics on table '%.*ls' named '%.*ls'.
1928 | 16 | Cannot create statistics on table '%.*ls' because this table does not exist in database '%.*ls'.
1929 | 16 | Cannot create statistics on table '%.*ls' because it is not a user table.
1930 | 16 | Only the owner of table '%.*ls' or a member of the sysadmin fixed server role can create statistics on it.


Errors 2000 - 2999

Error | Severity | Description
2001 | 10 | Cannot use duplicate parameter names. Parameter name '%.*ls' listed more than once.
2004 | 16 | Procedure '%.*ls' has already been created with group number %d. Create procedure with an unused group number.
2007 | 11 | Cannot add rows to sysdepends for the current stored procedure because it depends on the missing object '%.*ls'. The stored procedure will still be created.
2008 | 16 | The object '%.*ls' is not a procedure so you cannot create another procedure under that group name.
2009 | 10 | Procedure '%.*ls' was created despite delayed name resolution warnings (if any).
2010 | 16 | Cannot use ALTER %ls with %.*ls because %.*ls is a %S_MSG.
2106 | 11 | Cannot create a trigger on table '%.*ls', because this table does not exist in database '%.*ls'.
2108 | 16 | Cannot create a trigger on table '%.*ls' because you can only create a trigger on a table in the current database.
2109 | 16 | Cannot create a trigger on table '%.*ls' that accesses 'inserted' or 'deleted' because the table was created with the no_log option.
2110 | 16 | Cannot alter trigger '%.*ls' for table '%.*ls' because this trigger does not belong to this table.
2501 | 16 | Could not find table named '%.*ls'. Check sysobjects.
2502 | 16 | Could not start transaction.
2503 | 10 | Successfully deleted the physical file '%ls'.
2504 | 16 | Could not delete the physical file '%ls'. The DeleteFile system function returned error %ls.
2505 | 16 | The device '%.*ls' does not exist. Use sp_helpdevice to show available devices.
2511 | 16 | Table Corrupt: Object ID %d, Index ID %d. Keys out of order on page %S_PGID, slots %d and %d.
2513 | 16 | Table Corrupt: Object ID %ld (object '%.*ls') does not match between '%.*ls' and '%.*ls'.
2514 | 16 | Table Corrupt: Data type %ld (type '%.*ls') does not match between '%.*ls' and '%.*ls'.
2520 | 16 | Could not find database '%.*ls'. Check sysdatabases.
2521 | 16 | Could not find database ID %d. Check sysdatabases.
2526 | 16 | Incorrect DBCC statement. Check the documentation for the correct DBCC syntax and options.
2528 | 10 | DBCC execution completed. If DBCC printed error messages, contact your system administrator.
2532 | 16 | DBCC SHRINKFILE could not shrink file %ls. Log files are not supported.
2535 | 16 | Table Corrupt: Page %S_PGID is allocated to object ID %d, index ID %d, not to object ID %d, index ID %d found in page header.
2536 | 10 | DBCC results for '%.*ls'.
2538 | 10 | Allocation page %S_PGID. Number of extents = %ld, used pages = %ld, referenced pages = %ld.
2539 | 10 | Total number of extents = %ld, used pages = %ld, referenced pages = %ld in this database.
2540 | 10 | The system cannot self repair this error.
2541 | 10 | DBCC UPDATEUSAGE: sysindexes row updated for table '%.*ls' (index ID %ld):
2542 | 10 | DATA pages: Changed from (%ld) to (%ld) pages.
2543 | 10 | USED pages: Changed from (%ld) to (%ld) pages.
2544 | 10 | RSVD pages: Changed from (%ld) to (%ld) pages.
2545 | 10 | ROWS count: Changed from (%I64d) to (%I64d) rows.
2557 | 16 | Only the owner of object '%.*ls' can run DBCC %ls on it.
2560 | 16 | Parameter %d is incorrect for this DBCC statement.
2562 | 16 | '%ls' cannot access object '%.*ls' because it is not a table.
2566 | 14 | DBCC DBREINDEX cannot be used on system tables.
2568 | 16 | Page %S_PGID is out of range for this database or is in a log file.
2571 | 10 | Only members of the sysadmin role can use the DBCC statement %.*ls.
2573 | 16 | Database '%.*ls' is not marked suspect. You cannot drop it with DBCC.
2574 | 10 | Object ID %d, index ID %d: Page %S_PGID is empty. This is not permitted at level %d of the B-tree.
2583 | 16 | An incorrect number of parameters were given to the DBCC statement.
2588 | 16 | Page %S_PGID was expected to be the first page of a text, ntext, or image value.
2591 | 16 | Could not find row in sysindexes with index ID %d for table '%.*ls'.
2592 | 10 | %ls index successfully restored for object '%.*ls' in database '%.*ls'.
2593 | 10 | There are %I64d rows in %ld pages for object '%.*ls'.
2594 | 16 | Invalid index ID (%d) specified.
2595 | 16 | Database '%.*ls' must be set to single user mode before executing this statement.
2597 | 16 | The database is not open. Execute a 'USE %.*ls' statement and rerun the DBCC statement.
2598 | 16 | Clustered indexes on sysobjects and sysindexes cannot be re-created.
2601 | 14 | Cannot insert duplicate key row in object '%.*ls' with unique index '%.*ls'.
2603 | 21 | No space left on logical page %S_PGID of index ID %d for object '%.*ls' when inserting row on an index page. This situation should have been handled while traversing the index.
2617 | 20 | Buffer holding logical page %S_PGID not found in keep pool in SDES for object '%.*ls'. Contact Technical Support.
2624 | 21 | Could not insert into table %S_DES because row length %d is less than the minimum length %d.
2627 | 14 | Violation of %ls constraint '%.*ls'. Cannot insert duplicate key in object '%.*ls'.
2701 | 10 | Database name '%.*ls' ignored, referencing object in tempdb.
2702 | 16 | Database '%.*ls' does not exist.
2705 | 16 | Column names in each table must be unique. Column name '%.*ls' in table '%.*ls' is specified more than once.
2706 | 11 | Table '%.*ls' does not exist.
2710 | 16 | You are not the owner specified for the object '%.*ls' in this statement (CREATE, ALTER, TRUNCATE, UPDATE STATISTICS or BULK INSERT).
2714 | 16 | There is already an object named '%.*ls' in the database.
2715 | 16 | Column or parameter #%d: Cannot find data type %.*ls.
2716 | 16 | Column or parameter #%d: Cannot specify a column width on data type %.*ls.
2717 | 16 | Column or parameter #%d: Specified column width too large for data type %.*ls.
2718 | 16 | Column or parameter #%d: Cannot specify null values on a column of data type bit.
2721 | 11 | Could not find a default segment to create the table on. Ask your system administrator to specify a default segment in syssegments.
2724 | 10 | Parameter '%.*ls' has an invalid data type.
2727 | 11 | Cannot find index '%.*ls'.
2729 | 16 | Procedure '%.*ls' group number 1 already exists in the database. Choose another procedure name.
2730 | 11 | Cannot create procedure '%.*ls' with a group number of %d because a procedure with the same name and a group number of 1 does not currently exist in the database. Must execute CREATE PROCEDURE '%.*ls';1 first.
2732 | 16 | User error number %ld is invalid. The number must be between %ld and %ld.
2734 | 16 | The user name '%.*ls' does not exist in sysusers.
2736 | 16 | Owner name specified is a group name. Objects cannot be owned by groups.
2737 | 16 | Message passed to %hs must be of type char, varchar, nchar, or nvarchar.
2738 | 16 | A table can only have one timestamp column. Because table '%.*ls' already has one, the column '%.*ls' cannot be added.
2739 | 16 | The text, ntext, and image data types are invalid for local variables.
2740 | 16 | SET LANGUAGE failed because '%.*ls' is not an official language name or a language alias on this SQL Server.
2741 | 16 | SET DATEFORMAT date order '%.*ls' is invalid.
2742 | 16 | SET DATEFIRST %d is out of range.
2743 | 16 | %ls statement requires %S_MSG parameter.
2744 | 16 | Multiple identity columns specified for table '%.*ls'. Only one identity column per table is allowed.
2745 | 10 | Process ID %d has raised user error %d, severity %d. SQL Server is terminating this process.
2746 | 16 | Cannot specify user error format string with a length exceeding %d bytes.
2747 | 16 | Too many substitution parameters for RAISERROR. Cannot exceed %d substitution parameters.
2748 | 16 | Cannot specify %ls data type (RAISERROR parameter %d) as a substitution parameter for RAISERRROR.
2749 | 16 | Identity column '%.*ls' must be of data type int, smallint, tinyint, or decimal or numeric with scale of 0, and constrained to be nonnullable.
2750 | 16 | Column or parameter #%d: Specified column precision %d is greater than the maximum precision of %d.
2751 | 16 | Column or parameter #%d: Specified column scale %d is greater than the specified precision of %d.
2752 | 16 | Identity column '%.*ls' contains invalid SEED.
2753 | 16 | Identity column '%.*ls' contains invalid INCREMENT.
2754 | 16 | Error severity levels greater than %d can only be specified by members of the sysadmin role, using the WITH LOG option.
2755 | 16 | SET DEADLOCK_PRIORITY option '%.*ls' is invalid.
2756 | 16 | Invalid value %d for state. Valid range is from %d to %d.
2757 | 16 | RAISERROR failed due to invalid parameter substitution(s) for error %d, severity %d, state %d.
2758 | 16 | %hs could not locate entry for error %d in sysmessages.
2759 | 0 | CREATE SCHEMA failed due to previous errors.
2760 | 16 | Specified owner name '%.*ls' either does not exist or you do not have permission to use it.
2761 | 16 | The ROWGUIDCOL property can only be specified on the uniqueidentifier data type.
2762 | 16 | sp_setapprole was not invoked correctly. Refer to the documentation for more information.
2763 | 16 | Could not find application role '%.*ls'.
2764 | 16 | Incorrect password supplied for application role '%.*ls'.
2765 | 15 | Could not locate statistics for column '%.*ls' in the system catalogs.
2766 | 16 | The definition for user-defined data type '%.*ls' has changed.
2767 | 15 | Could not locate statistics '%.*ls' in the system catalogs.
2768 | 15 | Statistics for %ls '%.*ls'.
2769 | 15 | Column '%.*ls'. Cannot create statistics on a column of data type %ls.
2770 | 16 | The SELECT INTO statement cannot have same source and destination tables.
2771 | 16 | Cannot create statistics on table '%.*ls'. This table is a virtual system table.
2809 | 18 | The request for %S_MSG '%.*ls' failed because '%.*ls' is a %S_MSG object.
2812 | 16 | Could not find stored procedure '%.*ls'.


Errors 3000 - 3999

Error | Severity | Description
3009 | 16 | Could not insert a backup or restore history/detail record in the msdb database. This may indicate a problem with the msdb database. The backup/restore operation was still successful.
3013 | 16 | Backup or restore operation terminating abnormally.
3014 | 10 | Backup or restore operation successfully processed %d pages in %d.%03d seconds (%d.%03d MB/sec).
3015 | 10 | %hs is not yet implemented.
3016 | 16 | File '%ls' of database '%ls' has been removed or shrunk since this backup or restore operation was interrupted. The operation cannot be restarted.
3017 | 16 | Could not resume interrupted backup or restore operation. See the SQL Server error log for more information.
3018 | 16 | There is no interrupted backup or restore operation to restart. Reissue the statement without the RESTART clause.
3019 | 16 | The checkpoint file was for a different backup or restore operation. Reissue the statement without the RESTART clause.
3020 | 16 | The backup operation cannot be restarted as the log has been truncated. Reissue the statement without the RESTART clause.
3021 | 16 | Cannot perform a backup or restore operation within a transaction.
3023 | 16 | Backup, CHECKALLOC, bulk copy, SELECT INTO, and file manipulation (such as CREATE FILE) operations on a database must be serialized. Reissue the statement after the current backup, CHECKALLOC, or file manipulation operation is completed.
3024 | 16 | You can only perform a full backup of the master database. Use BACKUP DATABASE to back up the entire master database.
3025 | 16 | Missing database name. Reissue the statement specifying a valid database name.
3026 | 16 | Could not find filegroup ID %d in sysfilegroups for database '%ls'.
3027 | 16 | Could not find filegroup '%.*ls' in sysfilegroups for database '%.*ls'.
3028 | 16 | Operation checkpoint file is invalid. Could not restart operation. Reissue the statement without the RESTART option.
3029 | 16 | Database file '%ls' is subject to logical recovery and must be among the files to be backed up as part of the file or filegroup backup.
3030 | 16 | Database file '%ls' is subject to logical recovery and must be among the files to be restored.
3031 | 16 | The statement has inconsistent or conflicting options. Remove the conflicting option and reissue the statement.
3032 | 16 | One or more of the options is not supported for this statement. Review the documentation for supported options.
3033 | 16 | BACKUP DATABASE cannot be used on a database opened in emergency mode.
3034 | 16 | No files were selected to be processed. You may have selected one or more filegroups that have no members.
3035 | 16 | Cannot perform a differential backup for database '%ls', because a current database backup does not exist. Re-issue the statement omitting the WITH DIFFERENTIAL option.
3036 | 16 | Database '%ls' is in warm-standby state (set by executing RESTORE WITH STANDBY) and cannot be backed up until the entire load sequence is completed.
3101 | 16 | Database in use. The system administrator must have exclusive use of the database to run the restore operation.
3106 | 16 | The specified file '%ls' is in an obsolete backup database format (version %d) and cannot be upgraded to current server version %d.
3108 | 16 | RESTORE DATABASE must be used in single user mode when trying to restore the master database.
3110 | 14 | Only members of the sysadmin role or the database owner of '%.*ls' can run RESTORE DATABASE.
3112 | 16 | Cannot restore any database other than master when the server is in single user mode.
3113 | 21 | The database owner (DBO) does not have an entry in sysusers in database '%.*ls'.
3114 | 21 | Database '%.*ls' does not have an entry in sysdatabases.
3115 | 10 | User '%.*ls' in database '%.*ls' has SUID %d, which is the same as the SUID of the database owner (as defined in sysdatabases). User '%.*ls' will be given SUID %d.
3116 | 10 | When all restore transactions have been completed for database '%.*ls', user '%.*ls' should be given the next available SUID.
3117 | 10 | Database '%.*ls' already has a user with SUID %d.
3120 | 16 | The database you are attempting to restore was backed up under a different sort order ID (%d) than the one currently running on this server (%d), and at least one of them is a non-binary sort order.
3123 | 16 | Invalid database name '%.*ls' specified for backup or restore operation.
3127 | 16 | Temporary Message: The backup set does not contain pages for file '%ls'.
3128 | 16 | File '%ls' has an unsupported page size (%d).
3129 | 16 | Temporary Message: File '%ls' has changed size from %d to %d bytes.
3132 | 16 | The RAID set for database '%ls' is missing member number %d.
3133 | 16 | The volume on device '%ls' is not a member of the media family.
3135 | 16 | Cannot use the backup set in file '%ls' for this restore operation.
3136 | 16 | Cannot apply the differential backup on device '%ls' to database '%ls'.
3138 | 16 | One or more files in the backup set are no longer part of database '%ls'.
3140 | 16 | Could not adjust the space allocation for file '%ls'.
3141 | 16 | The database to be restored was named '%ls'. Reissue the statement using the WITH REPLACE option to overwrite the '%ls' database.
3142 | 16 | One or more devices or files already exist. Reissue the statement using the WITH REPLACE option to overwrite these files and devices.
3143 | 16 | The data set on device '%ls' is not a SQL Server backup set.
3144 | 16 | File '%.*ls' was not backed up in file %d on device '%ls'. The file cannot be restored from this backup set.
3145 | 16 | The STOPAT option is not supported for RESTORE DATABASE. You can use the STOPAT option with RESTORE LOG.
3146 | 16 | None of the newly-restored files had been modified after the backup was taken, so no further recovery actions are required. The database is now available for use.
3147 | 16 | Backup and restore operations are not allowed on database tempdb.
3148 | 16 | Media recovery for ALTER DATABASE is not yet implemented. The database cannot be rolled forward.
3149 | 16 | The database you are attempting to restore was backed up under a different Unicode locale ID (%d) or Unicode comparison style (%d) than the Unicode locale ID (%d) or Unicode comparison style (%d) currently running on this server.
3150 | 10 | The master database has been successfully restored. Shutting down SQL Server.
3151 | 21 | The master database failed to restore. Use the rebuildm utility to rebuild the master database. Shutting down SQL Server.
3152 | 16 | Cannot overwrite file '%ls' because it is marked as read-only.
3153 | 16 | The database is already fully recovered.
3154 | 16 | The backup set holds a backup of a database other than the existing '%ls' database.
3155 | 16 | The RESTORE operation cannot proceed because one or more files have been added or dropped from the database since the backup set was created.
3156 | 16 | The file '%ls' cannot be used by RESTORE. Consider using the WITH MOVE option to identify a valid location for the file.
3157 | 16 | The logical file (%d) is named '%ls'. RESTORE will not overwrite it from '%ls'.
3158 | 16 | Could not create one or more files. Consider using the WITH MOVE option to identify valid locations.
3159 | 16 | The tail of the log for database '%ls' has not been backed up. Back up the log and rerun the RESTORE statement specifying the FILE clause.
3160 | 16 | Could not update primary file information in sysdatabases.
3161 | 16 | The primary file is unavailable. It must be restored or otherwise made available.
3162 | 16 | The database has on-disk structure version %d. The server supports version %d and can only restore such a database that was inactive when it was backed up. This database was not inactive.
3163 | 16 | The transaction log was damaged. All data files must be restored before RESTORE LOG can be attempted.
3164 | 16 | Cannot roll forward the database with on-disk structure version %d. The server supports version %d. Reissue the RESTORE statement WITH RECOVERY.
3165 | 16 | Could not adjust the replication state of database '%ls'. The database was successfully restored, however its replication state is indeterminant. See the Troubleshooting Replication section in Books Online.
3166 | 16 | RESTORE DATABASE could not drop database '%ls'. Drop the database and then reissue the RESTORE DATABASE statement.
3167 | 16 | RESTORE could not start database '%ls'.
3201 | 16 | Cannot open backup device '%ls'. Device error or device off-line. See the SQL Server error log for more details.
3202 | 16 | Write on '%ls' failed, status = %ld. See the SQL Server error log for more details.
3203 | 16 | Read on '%ls' failed, status = %ld. See the SQL Server error log for more details.
3204 | 16 | Operator aborted backup or restore. See the error messages returned to the console for more details.
3205 | 16 | Too many backup devices specified for backup or restore; only %d are allowed.
3206 | 16 | No entry in sysdevices for backup device '%.*ls'. Update sysdevices and rerun statement.
3207 | 16 | Backup or restore requires at least one backup device. Rerun your statement specifying a backup device.
3208 | 16 | Unexpected end of file while reading beginning of backup set. Confirm that the media contains a valid SQL Server backup set, and see the console error log for more details.
3209 | 16 | '%.*ls' is not a backup device. Check sysdevices.
3211 | 10 | %d percent %hs.
3217 | 16 | Invalid value specified for %ls parameter.
3221 | 16 | The ReadFileEx system function executed on file '%ls' only read %d bytes, expected %d.
3222 | 16 | The WriteFileEx system function executed on file '%ls' only wrote %d bytes, expected %d.
3224 | 16 | Could not create worker thread.
3227 | 16 | The volume on device '%ls' is a duplicate of stripe set member %d.
3229 | 16 | Request for device '%ls' timed out.
3230 | 16 | Operation on device '%ls' exceeded retry count.
3234 | 16 | File '%.*ls' is not a database file for database '%ls'.
3235 | 16 | File '%ls' is not part of database '%ls'. You can only list files that are members of this database.
3237 | 16 | Option not supported for Named Pipe-based backup sets.
3239 | 16 | The backup set on device '%ls' uses a feature of the Microsoft Tape Format not supported by SQL Server.
3241 | 16 | The media family on device '%ls' is incorrectly formed. SQL Server cannot process this media family.
3242 | 16 | The file on device '%ls' is not a valid Microsoft Tape Format backup set.
3243 | 16 | The media family on device '%ls' was created using Microsoft Tape Format version %d.%d. SQL Server supports version %d.%d.
3244 | 16 | Descriptor block size exceeds %d bytes. Use a shorter name and/or description string and retry the operation.
3245 | 16 | Could not convert a string to or from Unicode, %ls.
3246 | 16 | The media family on device '%ls' is marked as nonappendable. Reissue the statement using the INIT option to overwrite the media.
3247 | 16 | The volume on device '%ls' has the wrong media sequence number (%d). Remove it and insert volume %d.
3248 | 25 | >>> VOLUME SWITCH <<< (not for output!)
3249 | 16 | The volume on device '%ls' is a continuation volume for the backup set. Remove it and insert the volume holding the start of the backup set.
3250 | 16 | The value '%d' is not within range for the %ls parameter.
3251 | 10 | The RAID stream on device '%ls' has been finished. The device will now be re-used for one of the remaining RAID streams.
3252 | 16 | Passwords on media and/or data sets are not supported in this release of SQL Server.
3253 | 16 | The block size parameter must supply a value that is a power of 2.
3254 | 16 | The volume on device '%ls' is empty.
3255 | 16 | The data set on device '%ls' is a SQL Server backup set not compatible with this version of SQL Server.
3256 | 16 | The backup set on device '%ls' was aborted while it was being created and is incomplete. RESTORE sequence is terminated abnormally.
3257 | 16 | There is insufficient free space on disk volume '%ls' to create the database. The database requires %I64u additional free bytes, while only %I64u bytes are available.
3258 | 16 | The volume on device '%ls' belongs to a different media set.
3259 | 16 | The volume on device '%ls' is not part of a multifamily (RAID) media set. Use WITH FORMAT to form a new RAID set.
3260 | 16 | An internal buffer has become full.
3261 | 16 | SQL Server cannot use the virtual device configuration.
3262 | 10 | The backup set is valid.
3263 | 16 | Cannot use the volume on device '%ls' as a continuation volume. It is sequence number %d of family %d for the current media set. Insert a new volume, or sequence number %d of family %d for the current set.
3264 | 16 | The operation did not proceed far enough to allow RESTART. Reissue the statement without the RESTART qualifier.
3265 | 16 | The login has insufficient authority. Membership of the sysadmin role is required to use VIRTUAL_DEVICE with BACKUP or RESTORE.
3266 | 10 | The Microsoft Tape Format (MTF) soft filemark database on backup device '%ls' cannot be read, inhibiting random access.
3267 | 16 | Insufficient resources to create UMS scheduler.
3268 | 16 | Cannot use the backup file '%ls' because it was originally formatted with sector size %d and is now on a device with sector size %d.
3269 | 16 | Cannot restore the file '%ls' because it was originally written with sector size %d; '%ls' is now on a device with sector size %d.
3270 | 16 | An internal consistency error occurred. Contact Technical Support for assistance.
3271 | 16 | Nonrecoverable I/O error occurred on file '%ls'.
3272 | 16 | The '%ls' device has a hardware sector size of %d, but the block size parameter specifies an incompatible override value of %d. Reissue the statement using a compatible block size.
3301 | 21 | Invalid log record found in the transaction log (logop %d).
3307 | 21 | Process %d was expected to hold logical lock on page %S_PGID.
3313 | 21 | Error while redoing logged operation in database '%.*ls'. Error at log record ID %S_LSN.
3314 | 21 | Error while undoing logged operation in database '%.*ls'. Error at log record ID %S_LSN.
3405 | 10 | Recovering database '%.*ls'.
3406 | 10 | %d transactions rolled forward in database '%.*ls' (%d).
3407 | 10 | %d transactions rolled back in database '%.*ls' (%d).
3408 | 10 | Recovery complete.
3413 | 21 | Database ID %d. Could not mark database as suspect. Getnext NC scan on sysdatabases.dbid failed.
3414 | 10 | Database '%.*ls' (database ID %d) could not recover. Contact Technical Support for further instructions.
3415 | 16 | Read-only database '%.*ls' must be made writable before it can be upgraded.
3417 | 21 | Cannot recover the master database. Exiting.
3429 | 10 | Warning: The outcome of transaction %S_XID, named '%.*ls' in database '%.*ls' (database ID %d), could not be determined because the coordinating database (database ID %d) could not be opened. The transaction was assumed to be committed.
3430 | 10 | Warning: Could not determine the outcome of transaction %S_XID, named '%.*ls' in database '%.*ls' (with ID %d) because the coordinating database (ID %d) did not contain the outcome. The transaction was assumed to be committed.
3431 | 21 | Could not recover database '%.*ls' (database ID %d) due to unresolved transaction outcomes.
3432 | 16 | Warning: syslanguages is missing.
3433 | 16 | Name is truncated to '%.*ls'. The maximum name length is %d.
3434 | 20 | Cannot change sort order or locale. Server shutting down. Restart SQL Server to continue with sort order unchanged.
3435 | 20 | Sort order or locale cannot be changed because user objects or user databases exist.
3436 | 20 | Cannot rebuild index ID %d for the '%.*ls' table in the '%.*ls' database.
3437 | 21 | Error recovering database '%.*ls'. Could not connect to MS DTC to check the completion status of transaction %S_XID.
3438 | 10 | Database '%.*ls' (database ID %d) failed to recover because transaction first LSN is not equal to LSN in checkpoint. Contact Technical Support for further instructions.
3439 | 10 | Database '%.*ls' (database ID %d). The DBCC RECOVERDB statement failed due to previous errors.
3440 | 21 | Database '%.*ls' (database ID %d). The DBCC RECOVERDB statement can only be run after a RESTORE statement that used the WITH NORECOVERY option.
3441 | 21 | Database '%.*ls' (database ID %d). The RESTORE statement could not access file '%ls'. Error was '%ls'.
3442 | 21 | Database '%.*ls' (database ID %d). The size of the undo file is insufficient.
3443 | 21 | Database '%.*ls' (database ID %d) was marked for standby or read-only use, but has been modified. The RESTORE LOG statement cannot be performed.
3444 | 21 | Database '%.*ls' (database ID %d). Could not find start of previous recovery operation. The RESTORE LOG statement cannot be performed.
3445 | 21 | Database '%.*ls' (database ID %d). The file '%ls' is not a valid undo file.
3446 | 16 | Primary file not available for database '%.*ls'.
3447 | 16 | Could not activate or scan all of the log files for database '%.*ls'.
3448 | 21 | Could not undo log record %S_LSN, for transaction ID %S_XID, on page %S_PGID, database '%.*ls' (database ID %d). Page information: LSN = %S_LSN, type = %ld. Log information: OpCode = %ld, context %ld.
3449 | 21 | An error has occurred indicating potential database corruption. SQL Server is shutting down so that recovery can be performed on database ID %d.
3450 | 10 | Recovery progress on database '%.*ls' (%d): %d percent.
3451 | 16 | Recovery has failed because reexecution of CREATE INDEX found inconsistencies between target filegroup '%ls' (%d) and source filegroup '%ls' (%d). Restore both filegroups before attempting further RESTORE LOG operations.
3452 | 10 | Recovery of database '%.*ls' (%d) detected possible identity value inconsistency in table ID %d. Run DBCC CHECKIDENT ('%.*ls').
3453 | 21 | Recovery has failed because a nonlogged operation could not be redone. Use the RESTORE statement to restore all data in filegroup '%ls' (%d) to a point beyond the nonlogged changes.
3501 | 21 | Could not find row in sysdatabases for database ID %d at checkpoint time.
3505 | 14 | Only the owner of database '%.*ls' can run the CHECKPOINT statement.
3508 | 25 | Could not get an exclusive lock on the database '%.*ls'. Make sure that no other users are currently using this database, and rerun the CHECKPOINT statement.
3509 | 14 | Could not set database '%.*ls' %ls read-only user mode because you could not exclusively lock the database.
3510 | 16 | Database '%.*ls' cannot be changed from read-only because the primary and/or log file(s) are not writable.
3604 | 10 | Duplicate key was ignored.
3605 | 10 | Duplicate row was ignored.
3606 | 10 | Arithmetic overflow occurred.
3607 | 10 | Division by zero occurred.
3608 | 16 | Cannot allocate a GUID for the token.
3612 | 10 | %hsSQL Server Execution Times:%hs CPU time = %lu ms, elapsed time = %lu ms.
3613 | 10 | SQL Server parse and compile time: %hs CPU time = %lu ms, elapsed time = %lu ms.
3615 | 10 | Table '%.*ls'. Scan count %d, logical reads %d, physical reads %d, read-ahead reads %d.
3618 | 10 | The transaction has been aborted.
3619 | 10 | Could not write a CHECKPOINT record in database ID %d because the log is out of space.
3620 | 10 | Automatic checkpointing is disabled in database '%.*ls' because the log is out of space. It will continue when the database owner successfully checkpoints the database. Free up some space or extend the database and then run the CHECKPOINT statement.
3621 | 10 | The statement has been aborted.
3622 | 10 | A domain error occurred.
3623 | 10 | A transaction on a no_log table was undone. See the SQL Server errorlog for details.
3625 | 20 | '%hs' is not yet implemented.
3627 | 16 | Could not create worker thread.
3701 | 11 | Cannot drop the %S_MSG '%.*ls', because it does not exist in the system catalog.
3702 | 16 | Cannot drop the %S_MSG '%.*ls' because it is currently in use.
3704 | 16 | Only the owner or members of the sysadmin role can drop the %S_MSG '%.*ls'.
3705 | 16 | Cannot use DROP %ls with '%.*ls' because '%.*ls' is a %S_MSG. Use DROP %ls.
3708 | 16 | Cannot drop the %S_MSG '%.*ls' because it is a system %S_MSG.
3716 | 16 | The %S_MSG '%.*ls' cannot be dropped because it is bound to one or more %S_MSG.
3718 | 11 | Could not drop index '%.*ls' because the table or clustered index entry cannot be found in the sysindexes system table.
3723 | 16 | An explicit DROP INDEX is not allowed on index '%.*ls'. It is being used for %ls constraint enforcement.
3724 | 16 | Cannot drop the %S_MSG '%.*ls' because it is published for replication.
3725 | 16 | The constraint '%.*ls' is being referenced by table '%.*ls', foreign key constraint '%.*ls'.
3726 | 16 | Could not drop object '%.*ls' because it is referenced by a FOREIGN KEY constraint.
3727 | 10 | Could not drop constraint. See previous errors.
3728 | 16 | '%.*ls' is not a constraint.
3733 | 16 | Constraint '%.*ls' does not belong to table '%.*ls'.
3736 | 16 | Cannot drop the %S_MSG '%.*ls' because it is being used for distribution.
3737 | 16 | Could not delete file '%ls'. See the SQL Server error log for more information.
3738 | 16 | Deleting database file '%ls'.
3739 | 15 | Cannot %ls the index '%.*ls' because it is not a statistics collection.
3740 | 16 | Cannot drop the %S_MSG '%.*ls' because at least part of the table resides on a read-only filegroup.
3902 | 13 | The COMMIT TRANSACTION request has no corresponding BEGIN TRANSACTION.
3903 | 13 | The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTION.
3904 | 21 | Cannot unsplit logical page %S_PGID in object '%.*ls', in database '%.*ls'. Both pages together contain more data than will fit on one page.
3906 | 16 | Could not run BEGIN TRANSACTION in database '%.*ls' because the database is read-only.
3908 | 16 | Could not run BEGIN TRANSACTION in database '%.*ls' because the database is in bypass recovery mode.
3909 | 16 | Session binding token is invalid or corrupt.
3910 | 16 | Transaction context in use by another session.
3912 | 16 | Cannot bind using an XP token while the server is not in an XP call.
3914 | 16 | The data type '%s' is invalid for transaction names or savepoint names. Allowed data types are char, varchar, nchar, or nvarchar.
3915 | 16 | Cannot use the ROLLBACK statement within an INSERT-EXEC statement.
3916 | 16 | Cannot use the COMMIT statement within an INSERT-EXEC statement unless BEGIN TRANSACTION is used first.
3917 | 16 | Session is bound to a transaction context that is in use. Other statements in the batch were ignored.


Errors 4000 - 4999

Error | Severity | Description
4003 | 21 | ODS error. Server is terminating this connection.
4004 | 16 | ntext data cannot be sent to clients using DB-Library (such as ISQL) or ODBC version 3.7 or earlier.
4015 | 16 | Language requested in login '%.*ls' is not an official name on this SQL Server. Using server-wide default %.*ls instead.
4016 | 16 | Language requested in 'login %.*ls' is not an official name on this SQL Server. Using user default %.*ls instead.
4017 | 16 | Neither the language requested in 'login %.*ls' nor user default language %.*ls is an official language name on this SQL Server. Using server-wide default %.*ls instead.
4018 | 16 | User default language %.*ls is not an official language name on this SQL Server. Using server-wide default %.*ls instead.
4019 | 16 | Language requested in login '%.*ls' is not an official language name on this SQL Server. Login fails.
4020 | 16 | Default date order '%.*ls' for language %.*ls is invalid. Using mdy instead.
4027 | 16 | Mount tape for %hs of database '%ls'.
4028 | 16 | End of tape has been reached. Remove tape '%ls' and mount next tape for %hs of database '%ls'.
4030 | 10 | The medium on device '%ls' expires on %hs and cannot be overwritten.
4035 | 10 | Processed %d pages for database '%ls', file '%ls' on file %d.
4037 | 16 | User-specified volume ID '%ls' does not match the volume ID '%ls' of the device '%ls'.
4038 | 16 | Cannot find file ID %d on device '%ls'.
4060 | 11 | Cannot open database requested in login '%.*ls'. Login fails.
4061 | 11 | Cannot open either database requested in login (%.*ls) or user default database (%.*ls). Using master database instead.
4062 | 11 | Cannot open user default database '%.*ls'. Using master database instead.
4063 | 11 | Cannot open database requested in login (%.*ls). Using user default '%.*ls' instead.
4207 | 16 | BACKUP LOG is not allowed while the select into/bulkcopy option is enabled. Use BACKUP DATABASE or disable the option using sp_dboption.
4208 | 16 | BACKUP LOG is not allowed while the trunc. log on chkpt. option is enabled. Use BACKUP DATABASE or disable the option using sp_dboption.
4212 | 16 | Cannot back up the log of the master database. Use BACKUP DATABASE instead.
4213 | 16 | Cannot allow BACKUP LOG because file '%ls' has been subjected to nonlogged updates and cannot be rolled forward. Perform a full database, or differential database, backup.
4214 | 10 | There is no current database backup. This log backup cannot be used to roll forward a preceding database backup.
4215 | 10 | The log was not truncated because records at the beginning of the log are pending replication. Ensure the logreader agent is running or use sp_repldone to mark transactions as distributed.
4301 | 16 | Database in use. The system administrator must have exclusive use of the database to restore the log.
4304 | 16 | A USER ATTENTION signal raised during RESTORE LOG is being ignored until the current restore completes.
4305 | 16 | This backup set cannot be restored because the database has not been rolled forward far enough. You must first restore all earlier logs before restoring this log.
4306 | 16 | The preceding restore operation did not specify WITH NORECOVERY or WITH STANDBY. Restart the restore sequence, specifying WITH NORECOVERY or WITH STANDBY for all but the final step.
4312 | 16 | Only members of the sysadmin role or owner of database '%.*ls' can run RESTORE LOG.
4316 | 16 | Can only RESTORE LOG in the master database if SQL Server is in single user mode.
4318 | 16 | File '%ls' has been rolled forward to LSN %.*ls. This log terminates at LSN %.*ls, which is too early to apply the WITH RECOVERY option. Reissue the RESTORE LOG statement WITH NORECOVERY.
4319 | 16 | Cannot use the STOPAT and NORECOVERY options together. Reissue the statement specifying WITH RECOVERY to roll the database forward to a specific point in time.
4320 | 16 | File '%ls' was only partially restored by a database or file restore. The entire file must be successfully restored before applying the log.
4321 | 16 | The minimum recovery point of the database is beyond the specified point-in-time. Reissue this statement without specifying STOPAT.
4322 | 10 | This log file contains records logged before the designated point-in-time. The database is being left in load state so you can apply another log file.
4323 | 16 | The database is marked suspect. Transaction logs cannot be restored. Use RESTORE DATABASE to recover the database.
4324 | 10 | Backup history older than %ls has been deleted.
4325 | 16 | Could not delete entries for backup set ID '%ls'.
4403 | 16 | View '%.*ls' is not updatable because it contains aggregates.
4404 | 16 | View '%.*ls' is not updatable because the definition contains the DISTINCT clause.
4405 | 16 | View '%.*ls' is not updatable because the FROM clause names multiple tables.
4406 | 16 | View '%.*ls' is not updatable because a column of the view is derived or constant.
4408 | 19 | The query and the views in it exceed the limit of %d tables.
4413 | 16 | Could not use view '%.*ls' because of previous binding errors.
4414 | 16 | Could not allocate ancillary table for view resolution. The maximum number of tables in a query (%d) was exceeded.
4415 | 16 | View '%.*ls' is not updatable because either it was created WITH CHECK OPTION or it spans a view created WITH CHECK OPTION and the target table is referenced multiple times in the resulting query.
4416 | 16 | View '%.*ls' is not updatable because the definition contains a UNION operator.
4417 | 16 | Derived table '%.*ls' is not updatable because the definition contains a UNION operator.
4418 | 16 | Derived table '%.*ls' is not updatable because it contains aggregates.
4419 | 16 | Derived table '%.*ls' is not updatable because the definition contains the DISTINCT clause.
4420 | 16 | Derived table '%.*ls' is not updatable because the FROM clause names multiple tables.
4421 | 16 | Derived table '%.*ls' is not updatable because a column of the derived table is derived or constant.
4424 | 16 | Joined tables cannot be specified in a query containing outer join operators. View '%.*ls' contains joined tables.
4425 | 16 | Cannot specify outer join operators in a query containing joined tables. View '%.*ls' contains outer join operators.
4427 | 16 | The view '%.*ls' is not updatable because the definition contains the TOP clause.
4428 | 16 | The derived table '%.*ls' is not updatable because the definition contains the TOP clause.
4429 | 16 | View '%.*ls' contains a self-reference. Views cannot reference themselves directly or indirectly.
4430 | 10 | Warning: Index hints supplied for view '%.*ls' will be ignored.
4501 | 16 | View '%.*ls' has more columns defined than column names given.
4502 | 16 | View '%.*ls' has more column names specified than columns defined.
4504 | 16 | Could not perform CREATE TABLE because there was not enough space to allocate memory for the table.
4505 | 16 | CREATE VIEW failed because column '%.*ls' in view '%.*ls' exceeds the maximum of %d columns.
4506 | 10 | Column names in each view must be unique. Column name '%.*ls' in view '%.*ls' is specified more than once.
4508 | 16 | Views are not allowed on temporary tables. Table names that begin with '#' denote temporary tables.
4510 | 16 | Could not perform CREATE VIEW because WITH CHECK OPTION was specified and the view is not updatable.
4511 | 16 | Could not perform CREATE VIEW because no column name was specified for column %d.
4602 | 14 | Only members of the sysadmin role can grant or revoke the CREATE DATABASE permission.
4603 | 14 | Only the owner of the current database can grant or revoke this permission.
4604 | 16 | There is no such user or group '%.*ls'.
4606 | 16 | Granted or revoked privilege %ls is not compatible with object.
4610 | 16 | You can only grant or revoke permissions on objects in the current database.
4611 | 16 | To revoke grantable privileges, specify the CASCADE option with REVOKE.
4613 | 16 | Grantor does not have GRANT permission.
4615 | 16 | Invalid column name '%.*ls'.
4617 | 16 | Cannot grant, deny or revoke permissions to or from special roles.
4618 | 16 | You do not have permission to use %.*ls in the AS clause.
4619 | 16 | CREATE DATABASE permission can only be granted in the master database.
4701 | 11 | Could not truncate table '%.*ls' because this table does not exist in database '%.*ls'.
4706 | 17 | Could not truncate table '%.*ls' because there is not enough room in the log to record the deallocation of all the index and data pages.
4707 | 16 | Could not truncate object '%.*ls' because it or one of its indexes resides on a READONLY filegroup.
4708 | 16 | Could not truncate object '%.*ls' because it is not a table.
4709 | 16 | You are not allowed to truncate the system table '%.*ls'.
4710 | 16 | Only the owner or members of the sysadmin role can truncate table '%.*ls'.
4711 | 16 | Cannot truncate table '%.*ls' because it is published for replication.
4712 | 16 | Cannot truncate table '%.*ls' because it is being referenced by a FOREIGN KEY constraint.
4801 | 20 | Bulk_main: The opentable system function on BULK INSERT table failed. Database ID %d, name '%.*ls'.
4803 | 21 | Received invalid row length %d from bcp client. Maximum row size is %d.
4804 | 21 | Premature end-of-message while reading current row from host. Host program may have died.
4805 | 17 | The front-end tool you are using does not support the feature of bulk insert from host. Use the proper tools for this command.
4807 | 21 | Received invalid row length %d from bcp client. Minimum row size is %d.
4810 | 16 | Expected the TEXT token in data stream for bulk copy of text or image data.
4811 | 16 | Expected the column offset in data stream for bulk copy of text or image data.
4812 | 16 | Expected the row offset in data stream for bulk copy of text or image data.
4813 | 16 | Expected the text length in data stream for bulk copy of text, ntext, or image data.
4815 | 21 | Received invalid column length from bcp client.
4817 | 16 | Could not bulk insert. Invalid sorted column '%.*ls'. Assuming data stream is not sorted.
4818 | 16 | Could not bulk insert. Sorted column '%.*ls' was specified more than once. Assuming data stream is not sorted.
4819 | 16 | Could not bulk insert. Bulk data stream was incorrectly specified as sorted.
4820 | 16 | Could not bulk insert. Unknown version of format file '%s'.
4821 | 16 | Could not bulk insert. Error reading the number of columns from format file '%s'.
4822 | 16 | Could not bulk insert. Invalid number of columns in format file '%s'.
4823 | 16 | Could not bulk insert. Invalid column number in format file '%s'.
4824 | 16 | Could not bulk insert. Invalid data type for column number %d in format file '%s'.
4825 | 16 | Could not bulk insert. Invalid prefix for column number %d in format file '%s'.
4826 | 16 | Could not bulk insert. Invalid column length for column number %d in format file '%s'.
4827 | 16 | Could not bulk insert. Invalid column terminator for column number %d in format file '%s'.
4828 | 16 | Could not bulk insert. Invalid destination table column number for source column %d in format file '%s'.
4829 | 16 | Could not bulk insert. Error reading destination table column name for source column %d in format file '%s'.
4830 | 10 | Bulk Insert: DataFileType was incorrectly specified as char. DataFileType will be assumed to be widechar because the data file has a Unicode signature.
4831 | 10 | Bulk Insert: DataFileType was incorrectly specified as widechar. DataFileType will be assumed to be char because the data file does not have a Unicode signature.
4832 | 16 | Bulk Insert: Unexpected end-of-file (EOF) encountered in data file.
4833 | 16 | Bulk Insert: Version mismatch between the provider dynamic link library and the server executable.
4834 | 16 | Permission denied. Only members of the sysadmin role can use the BULK INSERT statement.
4835 | 16 | Bulk copying into a table with computed columns is not supported for downlevel clients.
4836 | 10 | Warning: Table '%s' is published for merge replication. Reinitialize affected subscribers or execute sp_MSaddtabletocontents to ensure that data added is included in the next sychronization.
4837 | 16 | Error: Cannot bulk copy into a table '%s' enabled for immediate-updating subscriptions
4849 | 16 | Could not import table '%ls'. Error %d.
4850 | 10 | Data import: Table '%ls' is already locked by another user.
4851 | 10 | Data import: Table '%ls' already has data. Skipping to next table.
4852 | 10 | Data import: Table '%ls' does not exist or it is not a user table.
4853 | 10 | %hs
4854 | 21 | %hs
4860 | 16 | Could not bulk insert. File '%ls' does not exist.
4861 | 16 | Could not bulk insert because file '%ls' could not be opened. Operating system error code %ls.
4862 | 16 | Could not bulk insert because file '%ls' could not be read. Operating system error code %ls.
4863 | 16 | Bulk insert data conversion error (truncation) for row %d, column %d (%ls).
4864 | 16 | Bulk insert data conversion error (type mismatch) for row %d, column %d (%ls).
4865 | 16 | Could not bulk insert because the maximum number of errors (%d) was exceeded.
4866 | 16 | Could not bulk insert because column too long in data file. Make sure FieldTerminator and RowTerminator were specified correctly.
4867 | 16 | Bulk insert data conversion error (overflow) for row %d, column %d (%ls).
4901 | 16 | ALTER TABLE only allows columns to be added that can contain nulls or have a DEFAULT definition specified. Column '%.*ls' cannot be added to table '%.*ls' because it does not allow nulls and does not specify a DEFAULT definition.
4902 | 11 | Cannot alter table '%.*ls' because this table does not exist in database '%.*ls'.
4909 | 16 | Cannot alter '%.*ls' because it is not a table.
4910 | 16 | Only the owner or members of the sysadmin role can alter table '%.*ls'.
4916 | 16 | Could not enable or disable the constraint. See previous errors.
4917 | 16 | Constraint '%.*ls' does not exist.
4920 | 16 | ALTER TABLE failed because trigger '%.*ls' on table '%.*ls' does not exist.
4921 | 16 | ALTER TABLE failed because trigger '%.*ls' does not belong to table '%.*ls'.
4922 | 16 | %ls %.*ls failed because %ls %.*ls accesses this column.
4923 | 16 | ALTER TABLE DROP COLUMN failed because '%.*ls' is the only data column in table '%.*ls'. A table must have at least one data column.
4924 | 16 | %ls failed because column '%.*ls' does not exist in table '%.*ls'.
4925 | 16 | ALTER TABLE ALTER COLUMN ADD ROWGUIDCOL failed because a column already exists in table '%.*ls' with ROWGUIDCOL property.
4926 | 16 | ALTER TABLE ALTER COLUMN DROP ROWGUIDCOL failed because a column does not exist in table '%.*ls' with ROWGUIDCOL property.
4927 | 16 | Cannot alter column '%.*ls' to be data type %.*ls.
4928 | 16 | Cannot alter column '%.*ls' because it is '%ls'.
4929 | 16 | Cannot alter the %S_MSG '%.*ls' because it is being published for replication.
4930 | 10 | Warning: Columns added to the replicated table %S_MSG '%.*ls' will be ignored by existing articles.
4931 | 16 | Cannot add columns to %S_MSG '%.*ls' because it is being published for merge replication.


Errors 5000 - 5999

Error | Severity | Description
5001 | 16 | User must be in the master database.
5002 | 16 | Database '%.*ls' does not exist. Check sysdatabases.
5004 | 16 | Database must be in state where it can be checkpointed to use ALTER DATABASE.
5005 | 10 | Extending database by %.2f MB on disk '%.*ls'.
5006 | 16 | Could not get exclusive use of %S_MSG '%.*ls' to perform the requested operation.
5008 | 16 | ALTER DATABASE option not implemented yet.
5009 | 16 | ALTER DATABASE failed. Some disk names listed in the statement were not found. Check that the names exist and are spelled correctly before rerunning the statement.
5011 | 14 | Only members of the sysadmin role or owner of database '%.*ls' can alter it.
5013 | 16 | The master and model databases cannot have files added to them. ALTER DATABASE was aborted.
5014 | 16 | The %S_MSG '%.*ls' does not exist in database '%.*ls'.
5015 | 16 | ALTER DATABASE failed. The total size specified must be 1 MB or greater.
5017 | 16 | ALTER DATABASE failed. Database '%.*ls' was not created with 'FOR LOAD' option.
5018 | 0 | File '%.*ls' modified in sysaltfiles. Delete old file after restarting SQL Server.
5019 | 16 | Could not find entry in sysaltfiles for file '%.*ls'.
5020 | 16 | The primary data or log file cannot be removed from a database.
5021 | 16 | MAXSIZE cannot be larger than the maximum database size of %ld MB.
5022 | 16 | Log file '%ls' for this database is already active.
5023 | 16 | Database must be put in bypass recovery mode to rebuild the log.
5024 | 16 | No entry found for the primary log file in sysfiles1. Could not rebuild the log.
5025 | 16 | The file '%ls' already exists. It should be renamed or deleted so that a new log file can be created.
5026 | 16 | Could not create a new log file with file '%.*ls'. See previous errors.
5027 | 16 | System databases master, model, and tempdb cannot have their logs rebuilt.
5028 | 16 | The system could not activate enough of the database to rebuild the log.
5029 | 10 | Warning: The log for database '%.*ls' has been rebuilt. Transactional consistency has been lost. DBCC CHECKDB should be run to validate physical consistency. Database options will have to be reset, and extra log files may need to be deleted.
5030 | 16 | The database could not be exclusively locked to perform the operation.
5031 | 16 | Cannot remove the file '%.*ls' because it is the only file in the DEFAULT filegroup.
5035 | 16 | Filegroup '%.*ls' already exists in this database.
5036 | 16 | MODIFY FILE failed. Specify logical name.
5037 | 16 | MODIFY FILE failed. Do not specify physical name.
5038 | 16 | MODIFY FILE failed. Only modify one file and one property at a time.
5039 | 16 | MODIFY FILE failed. Specified size is less than current size.
5040 | 16 | MODIFY FILE failed. Size is greater than MAXSIZE.
5041 | 16 | MODIFY FILE failed. File '%.*ls' does not exist.
5042 | 16 | The %S_MSG '%.*ls' cannot be removed because it is not empty.
5043 | 16 | The %S_MSG '%.*ls' cannot be found in %ls.
5044 | 10 | The %S_MSG '%.*ls' has been removed.
5045 | 16 | The %S_MSG already has the '%ls' property set.
5046 | 10 | The %S_MSG property '%ls' has been set.
5047 | 16 | Cannot change the READONLY property of the PRIMARY filegroup.
5048 | 16 | Cannot %ls file in read-only filegroup '%.*ls'.
5049 | 16 | Cannot extend file '%ls' using this syntax as it was not created with DISK INIT. Use ALTER DATABASE MODIFY FILE.
5050 | 16 | Cannot change the properties of empty filegroup '%.*ls'. The filegroup must contain at least one file.
5051 | 16 | Cannot have a filegroup with the name 'DEFAULT'.
5053 | 16 | The maximum of %ld filegroups per database has been exceeded.
5055 | 16 | Cannot %ls read-only file '%.*ls'.
5101 | 15 | You must supply parameters for the DISK %hs statement. Usage: %hs.
5102 | 15 | No such statement DISK %.*ls.
5103 | 16 | MAXSIZE cannot be less than SIZE for file '%ls'.
5104 | 16 | File '%.*ls' already used.
5105 | 16 | Device activation error. The physical file name '%.*ls' may be incorrect.
5106 | 15 | Parameter '%hs' requires value of data type '%hs'.
5107 | 15 | Value is wrong data type for parameter '%hs' (requires data type '%hs').
5109 | 16 | No such parameter '%.*ls'.
5116 | 14 | Permission denied. Only members of the sysadmin role can run DISK statements.
5117 | 16 | Could not run DISK statement. You must be in the master database to run this statement.
5122 | 10 | Each disk file size must be greater than or equal to 1 MB.
5123 | 16 | CREATE FILE encountered operating system error %ls while attempting to open or create the physical file '%.*ls'.
5126 | 16 | The logical device '%.*ls' does not exist in sysdevices.
5146 | 16 | The %hs of %d is out of range. It must be between %d and %d.
5148 | 16 | Could not set the file size to the desired amount. The operating system file size limit may have been reached.
5149 | 16 | MODIFY FILE encountered operating system error %ls while attempting to expand the physical file.
5150 | 16 | The size of a single log file must not be greater than 2 TB.
5151 | 16 | The %hs statement is obsolete and no longer supported.
5154 | 16 | Device '%.*ls' is not open.
5156 | 16 | Usage: DBCC DEVCONTROL(devname,ONLINE|OFFLINE)
5157 | 16 | I/O error encountered in the writelog system function during backout.
5158 | 10 | Warning: Media in device '%.*ls' may have been changed.
5159 | 16 | Operating system error %.*ls on device '%.*ls' during %ls.
5160 | 16 | Cannot take '%.*ls' offline because the database is in use.
5162 | 16 | Cannot find '%.*ls' in sysdatabases.
5163 | 16 | Cannot open '%.*ls' to take offline.
5164 | 16 | Usage: DBCC DBCONTROL(dbname,ONLINE|OFFLINE)
5165 | 16 | Cannot explicitly open or close master database.
5167 | 16 | Database '%.*ls' is already offline.
5168 | 16 | File '%.*ls' is on a network drive, which is not allowed.
5169 | 16 | FILEGROWTH cannot be greater than MAXSIZE for file '%.*ls'.
5170 | 16 | Cannot create file '%ls' because it already exists.
5171 | 16 | %.*ls is not a primary database file.
5172 | 16 | The header for file '%ls' is not a valid database file header. The %ls property is incorrect.
5173 | 16 | Cannot associate files with different databases.
5174 | 10 | Each file size must be greater than or equal to 512 KB.
5175 | 10 | The file '%.*ls' has been expanded to prevent recovery from failing. Contact the system administrator for further assistance.
5176 | 10 | The file '%.*ls' has been expanded beyond its maximum size to prevent recovery from failing. Contact the system administrator for further assistance.
5177 | 16 | Encountered an unexpected error while checking the sector size for file '%.*ls'. Check the SQL Server error log for more information.
5178 | 16 | Cannot use file '%.*ls' because it was originally formatted with sector size %d and is now on a device with sector size %d.
5179 | 16 | Cannot use file '%.*ls', which is on a device with sector size %d. SQL Server supports a maximum sector size of 4096 bytes.
5180 | 22 | Could not open FCB for invalid file ID %d in database '%.*ls'. Table or database may be corrupted.
5181 | 16 | Could not restart database '%.*ls'. Reverting back to old status.
5701 | 10 | Changed database context to '%.*ls'.
5702 | 10 | SQL Server is terminating this process.
5703 | 10 | Changed language setting to %.*ls.
5803 | 10 | Unknown config number (%d) in sysconfigures.
5805 | 16 | Too few locks specified. Minimum %d.
5807 | 16 | Recovery intervals above %d minutes not recommended. Use the RECONFIGURE WITH OVERRIDE statement to force this configuration.
5808 | 16 | Ad hoc updates to system catalogs not recommended. Use the RECONFIGURE WITH OVERRIDE statement to force this configuration.
5809 | 16 | Average time slices above %d milliseconds not recommended. Use the RECONFIGURE WITH OVERRIDE statement to force this configuration.
5810 | 16 | Valid values for the fill factor are 0 to 100.
5812 | 14 | Permission denied. Only members of the sysadmin role can run RECONFIGURE.
5823 | 16 | Cannot reconfigure SQL Server to use sort order ID %d, because the row for that sort order does not exist in syscharsets.
5824 | 16 | Cannot reconfigure SQL Server to use sort order ID %d, because the row for its underlying character set (ID %d) does not exist in syscharsets.
5825 | 16 | Cannot reconfigure the server's sort order because the syscharsets table does not exist. You must upgrade your server prior to attempting this.
5826 | 10 | You have just reconfigured SQL Server's sort order. Table indexes on columns of type char or varchar will be rebuilt when SQL Server is restarted.
5827 | 10 | By changing the default sort order, you have also reconfigured SQL Server's default character set.
5828 | 16 | User connections are limited to %d.
5829 | 16 | The specified user options value is invalid.
5830 | 10 | You have just reconfigured SQL Server's Unicode collation. Table indexes on columns of type nchar or nvarchar will be rebuilt when SQL Server is restarted.
5831 | 16 | Minimum server memory value (%d) must be less than or equal to the maximum value (%d).
5904 | 17 | Background checkpoint process suspended until locks are available.


Errors 6000 - 6999

Error | Severity | Description
6001 | 10 | SHUTDOWN is waiting for %d process(es) to complete.
6002 | 10 | SHUTDOWN is in progress. Log off.
6004 | 10 | SHUTDOWN can only be used by members of the sysadmin role.
6005 | 10 | SHUTDOWN is in progress.
6006 | 10 | Server shut down by request.
6007 | 10 | The SHUTDOWN statement cannot be executed within a transaction or by a stored procedure.
6101 | 16 | Process ID %d is not a valid process ID. Choose a number between 1 and %d.
6102 | 14 | Only members of the sysadmin role can use the KILL statement.
6103 | 17 | Could not do cleanup for the killed process. Received message %d.
6104 | 16 | Cannot use KILL to kill your own process.
6106 | 16 | Process ID %d is not an active process ID.
6107 | 14 | Only user processes can be killed.
6108 | 16 | KILL WITH COMMIT/ABORT can only be used with waiting distributed transactions.
6401 | 16 | Cannot roll back %.*ls. No transaction or savepoint of that name was found.


Errors 7000 - 7999

Error | Severity | Description
7102 | 20 | SQL Server Internal Error. Text manager cannot continue with current statement.
7105 | 22 | Page %S_PGID, slot %d for text, ntext, or image node does not exist.
7116 | 25 | Offset %d is not in the range of available text, ntext, or image data.
7122 | 16 | Invalid text, ntext, or image pointer type. Must be binary(16).
7123 | 16 | Invalid text, ntext, or image pointer value %hs.
7124 | 16 | The offset and length specified in the READTEXT statement is greater than the actual data length of %ld.
7125 | 16 | The text, ntext, or image pointer value conflicts with the column name specified.
7126 | 16 | The text, ntext, or image pointer value references a data page with an invalid text, ntext, or image status.
7127 | 16 | The text, ntext, or image pointer value references a data page with an invalid timestamp.
7128 | 16 | The text, ntext, or image pointer value references a data page that is no longer allocated.
7130 | 16 | %ls WITH NO LOG is not valid at this time. Use sp_dboption to set the 'select into/bulkcopy' option on for database '%.*ls'.
7133 | 16 | NULL textptr (text, ntext, or image pointer) passed to %ls function.
7135 | 16 | Deletion length %ld is not in the range of available text, ntext, or image data.
7136 | 16 | %ls WITH NO LOG is not valid when the column is being replicated.
7139 | 16 | Length of text, ntext, or image data (%ld) to be replicated exceeds configured maximum %ld.
7140 | 16 | Text has been padded with 0 due to dirty read.
7141 | 16 | Must create orphaned text inside a user transaction.
7142 | 16 | Must drop orphaned text before committing the transaction.
7143 | 16 | Invalid locator de-referenced.
7201 | 17 | Could not execute procedure on remote server '%.*ls' because SQL Server is not configured for remote access. Ask your system administrator to reconfigure SQL Server to allow remote access.
7202 | 11 | Could not find server '%.*ls' in sysservers. Execute sp_addlinkedserver to add the server to sysservers.
7204 | 20 | Could not obtain or use interface %hs from Microsoft OLE DB provider for ODBC. Microsoft OLE DB provider for ODBC not registered. Remote procedures cannot be executed.
7212 | 16 | Could not execute procedure '%.*ls' on remote server '%.*ls'.
7213 | 20 | Could not set up parameter for remote server '%.*ls'.
7214 | 16 | Remote procedure time out of %d seconds exceeded. Remote procedure '%.*ls' is canceled.
7221 | 16 | Could not relay results of procedure '%.*ls' from remote server '%.*ls'.
7300 | 16 | OLE DB error trace [%ls].
7301 | 16 | Could not obtain a required interface from OLE DB provider '%ls'.
7302 | 16 | Could not create an instance of OLE DB provider '%ls'.
7303 | 16 | Could not initialize data source object of OLE DB provider '%ls'. %ls
7304 | 16 | Could not create a new session on OLE DB provider '%ls'.
7305 | 16 | Could not create a statement object using OLE DB provider '%ls'.
7306 | 16 | Could not open table '%ls' from OLE DB provider '%ls'. %ls
7307 | 16 | Could not obtain the data source of a session from OLE DB provider '%ls'. This action must be supported by the provider.
7310 | 16 | Could not obtain the schema options for OLE DB provider '%ls'. The provider supports the interface, but returns a failure code when it is used.
7311 | 16 | Could not obtain the schema rowset for OLE DB provider '%ls'. The provider supports the interface, but returns a failure code when it is used.
7312 | 16 | Invalid use of schema and/or catalog for OLE DB provider '%ls'. A four-part name was supplied, but the provider does not expose the necessary interfaces to use a catalog and/or schema.
7313 | 16 | Invalid schema or catalog specified for provider '%ls'.
7314 | 16 | OLE DB provider '%ls' does not contain table '%ls'.
7315 | 16 | OLE DB provider '%ls' contains multiple tables that match the name '%ls'.
7316 | 16 | Could not use qualified table names (schema or catalog) with OLE DB provider '%ls' because it does not implement required functionality.
7317 | 16 | OLE DB provider '%ls' returned an invalid schema definition.
7318 | 16 | OLE DB provider '%ls' returned an invalid column definition.
7319 | 16 | OLE DB provider '%ls' returned a '%ls' index '%ls' with incorrect bookmark ordinal %d.
7320 | 16 | Could not execute query against OLE DB provider '%ls'. %ls
7321 | 16 | An error occurred while preparing a query for execution against OLE DB provider '%ls'. %ls
7322 | 16 | A failure occurred while giving parameter information to OLE DB provider '%ls'. %ls
7323 | 16 | An error occurred while submitting the query text to OLE DB provider '%ls'. %ls
7330 | 16 | Could not fetch a row from OLE DB provider '%ls'. %ls
7331 | 16 | Could not release a row from OLE DB provider '%ls'. %ls
7332 | 16 | Could not rescan the result set from OLE DB provider '%ls'. %ls
7333 | 16 | Could not fetch a row using a bookmark from OLE DB provider '%ls'. %ls
7340 | 16 | Could not create a column accessor for OLE DB provider '%ls'. %ls
7341 | 16 | Could not get the current row value of column '%ls.%ls' from the OLE DB provider '%ls'. %ls
7342 | 16 | Unexpected NULL value returned for column '%ls.%ls' from the OLE DB provider '%ls'. This column cannot be NULL.
7343 | 16 | OLE DB provider '%ls' could not %ls table '%ls'. %ls
7344 | 16 | OLE DB provider '%ls' could not %ls table '%ls' because of column '%ls'. %ls
7345 | 16 | OLE DB provider '%ls' could not delete from table '%ls'. %ls
7346 | 16 | Could not get the data of the row from the OLEDB provider '%ls'. %ls
7347 | 16 | OLE DB provider '%ls' returned an unexpected data length for the fixed-length column '%ls.%ls'. The expected data length is %ls, while the returned data length is %ls.
7348 | 16 | OLE DB provider '%ls' could not set range for table '%ls'.%ls
7349 | 16 | OLE DB provider '%ls' could not set range for table '%ls' because of column '%ls'.%ls
7350 | 16 | Could not get the column information from the OLE DB provider '%ls'.
7351 | 16 | OLE DB provider '%ls' could not map ordinals for one or more columns of object '%ls'.
7352 | 16 | OLE DB provider '%ls' supplied inconsistent metadata. The object '%ls' was missing expected column '%ls'.
7353 | 16 | OLE DB provider '%ls' supplied inconsistent metadata. An extra column was supplied during execution that was not found at compile time.
7354 | 16 | OLE DB provider '%ls' supplied invalid metadata for column '%ls'. %ls
7355 | 16 | OLE DB provider '%ls' supplied inconsistent metadata for a column. The name was changed at execution time.
7356 | 16 | OLE DB provider '%ls' supplied inconsistent metadata for a column. Metadata information was changed at execution time.
7357 | 16 | Could not process object '%ls'. The OLE DB provider '%ls' indicates that the object has no columns.
7358 | 16 | Could not execute query. The OLE DB provider '%ls' did not provide an appropriate interface to access the text, ntext, or image column '%ls.%ls'.
7360 | 16 | Could not get the length of a storage object from the OLE DB provider '%ls' for table '%ls', column '%ls'.
7361 | 16 | Could not read a storage object from the OLE DB provider '%ls', for table '%ls', column '%ls'.
7370 | 16 | One or more properties could not be set on the query for OLE DB provider '%ls'. %ls
7371 | 16 | One or more properties could not be set on the table for OLE DB provider '%ls'.
7373 | 16 | Could not set the initialization properties for the OLE DB provider '%ls'.
7375 | 16 | Could not open index '%ls' on table '%ls' from OLE DB provider '%ls'. %ls
7376 | 16 | Could not enforce the remote join hint for this query.
7390 | 16 | The requested operation could not be performed because the OLE DB provider '%ls' does not support the required transaction interface.
7391 | 16 | The operation could not be performed because the OLE DB provider '%ls' does not support distributed transactions.
7392 | 16 | Could not start a transaction for OLE DB provider '%ls'.
7393 | 16 | OLE DB provider '%ls' reported an error aborting the current transaction.
7394 | 16 | OLE DB provider '%ls' reported an error committing the current transaction.
7399 | 16 | OLE DB provider '%ls' reported an error. %ls
7401 | 16 | Cannot create OLE DB provider enumeration object installed with SQL Server. Verify installation.
7403 | 16 | Could not locate registry entry for OLE DB provider '%ls'.
7404 | 16 | The server could not load DCOM on startup (-O command-line used to force startup). Heterogeneous queries and remote RPC are disabled.
7405 | 16 | Heterogeneous queries require the ANSI_NULLS and ANSI_WARNINGS options to be set for the connection. This ensures consistent query semantics. Enable these options and then reissue your query.
7410 | 16 | Remote access not allowed for Windows NT user activated by SETUSER.
7411 | 16 | Server '%.*ls' is not configured for %ls.
7413 | 16 | Could not perform a Windows NT authenticated login because delegation is not available.
7414 | 16 | Invalid number of parameters. Rowset '%ls' expects %d parameter(s).
7415 | 16 | Ad hoc access to OLE DB provider '%ls' has been denied. You must access this provider through a linked server.
7416 | 16 | Access to the remote server is denied because no login-mapping exists.
7417 | 16 | Remote tables are not allowed in GROUP BY ALL operations.
7601 | 16 | Cannot use a CONTAINS or FREETEXT predicate on %S_MSG '%.*ls' because it is not full-text indexed.
7602 | 16 | The Full-Text Service (Microsoft Search) is not available. The system administrator must start this service.
7603 | 15 | Syntax error in search condition '%ls'.
7604 | 17 | Full-text operation failed due to a time out.
7605 | 17 | Full-text catalog '%ls' has been lost. Use sp_fulltext_catalog to re-build and to re-populate this full-text catalog.
7606 | 17 | Could not find full-text index for database ID %d, table ID %d. Use sp_fulltext_table to deactivate then activate this index.
7607 | 17 | Search on full-text catalog '%ls' for database ID %d, table ID %d with search condition '%ls' failed with unknown result (%x).
7608 | 17 | An unknown full-text failure (%x) occurred in function %hs on full-text catalog '%ls'.
7609 | 17 | Could not load the Full-Text Search component (SQLFTQRY.DLL).
7610 | 16 | Could not create full-text catalog because '%ls' is an invalid file path.
7611 | 10 | Warning: Request to start a population in full-text catalog '%ls' ignored because a crawl is currently active for this full-text catalog.
7612 | 16 | %d is not a valid value for full-text system resource usage.
7613 | 16 | Cannot drop index '%.*ls' because it enforces the full-text key for table '%.*ls'.
7614 | 16 | Cannot alter or drop column '%.*ls' because it is enabled for Full-Text Search.
7615 | 16 | A CONTAINS or FREETEXT predicate can only operate on one table. Qualify the use of * with a table name.
7616 | 16 | Full-Text Search is not enabled for the current database. Use sp_fulltext_database to enable full-text search for the database.
7617 | 16 | Query does not reference the fulltext indexed table.
7618 | 16 | %d is not a valid value for a full-text connection time out.
7620 | 16 | Conversion to data type %ls failed for full-text search key value 0x%ls.
7621 | 16 | Invalid use of full-text predicate in the HAVING clause.
7622 | 17 | Full-text catalog '%ls' lacks sufficient disk space to complete this operation.
7623 | 17 | Full-text query failed because full-text catalog '%ls' is not yet ready for queries.
7624 | 17 | Full-text catalog '%ls' is in a unusable state. Drop and re-create this full-text catalog.
7908 | 10 | The table '%.*ls' was created with the NO_LOG option.
7909 | 10 | A transaction involving the NO_LOG table '%.*ls' was undone. This may have left the table in an inconsistent state. Rebuild the table.
7910 | 10 | Repair: Page %S_PGID has been allocated to object ID %d, index ID %d.
7911 | 10 | Repair: Page %S_PGID has been deallocated from object ID %d, index ID %d.
7912 | 10 | Repair: Extent %S_PGID has been allocated to object ID %d, index ID %d.
7913 | 10 | Repair: Extent %S_PGID has been deallocated from object ID %d, index ID %d.
7914 | 10 | Repair: %ls page at %S_PGID has been rebuilt.
7915 | 10 | Repair: IAM chain for object ID %d, index ID %d, has been truncated before page %S_PGID and will be rebuilt.
7916 | 10 | Repair: Deleted record for object ID %d, index ID %d, on page %S_PGID, slot %d. Indexes will be rebuilt.
7917 | 10 | Repair: Converted forwarded record for object ID %d, index ID %d, at page %S_PGID, slot %d to a data row.
7918 | 10 | Repair: Page %S_PGID next and %S_PGID previous pointers have been set to match each other in object ID %d, index ID %d.
7919 | 16 | Repair statement not processed. Database needs to be in single user mode.
7920 | 10 | Processed %ld entries in sysindexes for database ID %d.
7922 | 16 | ***************************************************************
7923 | 10 | Table %.*ls Object ID %ld.
7924 | 10 | Index ID %ld FirstIAM %S_PGID Root %S_PGID Dpages %ld Sort %d.
7925 | 16 | Index ID %d. %ld index pages in %ld extents.
7926 | 16 | Data level %d. %ld data pages in %ld extents.
7927 | 16 | Total number of extents is %ld.
7932 | 16 | The indexes for '%.*ls' are already correct. They will not be rebuilt.
7933 | 16 | One or more indexes are corrupt. They will be rebuilt.
7934 | 16 | The table '%.*ls' has no indexes.
7935 | 16 | REINDEX received an exception. Statement aborted.
7937 | 16 | The data in table '%.*ls' is possibly corrupt. REINDEX aborted. Run DBCC CHECKTABLE and report errors to your system administrator.
7939 | 16 | Cannot detach database '%.*ls' because it does not exist.
7940 | 16 | System databases master, model, and tempdb cannot be detached.
7941 | 10 | Trace option(s) not enabled for this connection. Use 'DBCC TRACEON()'.
7942 | 10 | DBCC %ls scanning '%.*ls' table...
7943 | 10 | Table: '%.*ls' (%d); index ID: %d, database ID: %d
7944 | 10 | %ls level scan performed.
7945 | 10 | - Pages Scanned................................: %lu
7946 | 10 | - Extents Scanned..............................: %lu
7947 | 10 | - Extent Switches..............................: %lu
7948 | 10 | - Avg. Pages per Extent........................: %3.1f
7949 | 10 | - Scan Density [Best Count:Actual Count].......: %4.2f%ls [%lu:%lu]
7950 | 10 | - Logical Scan Fragmentation ..................: %4.2f%ls
7951 | 10 | - Physical Scan Fragmentation .................: %4.2f%ls
7952 | 10 | - Extent Scan Fragmentation ...................: %4.2f%ls
7953 | 10 | - Avg. Bytes Free per Page.....................: %3.1f
7954 | 10 | - Avg. Page Density (full).....................: %4.2f%ls
7955 | 10 | Invalid SPID %d specified.
7956 | 10 | Permission to execute DBCC %ls denied.
7957 | 10 | Cannot display the specified SPID's buffer; in transition.
7958 | 10 | The specified SPID does not process input/output data streams.
7959 | 10 | The DBCC statement is not supported in this release.
7962 | 16 | Upgrade requires SQL Server to be started in single user mode. Restart SQL Server with the -m flag.
7963 | 16 | Upgrade encountered a fatal error. See the SQL Server errorlog for more information.
7965 | 16 | Table corrupt: Could not check object ID %d, index ID %d due to invalid allocation (IAM) page(s).
7966 | 10 | Warning: NO_INDEX option of %ls being used. Checks on non-system indexes will be skipped.
7968 | 10 | Transaction information for database '%.*ls'.
7969 | 10 | No active open transactions.
7970 | 10 | %hsOldest active transaction:
7971 | 10 | SPID (server process ID) : %d
7972 | 10 | UID (user ID) : %d
7974 | 10 | Name : %.*ls
7975 | 10 | LSN : (%d:%d:%d)
7977 | 10 | Start time : %.*ls
7979 | 10 | %hsReplicated Transaction Information:
7980 | 10 | Oldest distributed LSN : (%d:%d:%d)
7982 | 10 | Oldest non-distributed LSN : (%d:%d:%d)
7983 | 14 | Only the owner of database '%.*ls' can run the DBCC %ls statement.
7984 | 16 | Invalid object name '%.*ls'.
7985 | 16 | The object name '%.*ls' contains more than the maximum number of prefixes. The maximum is %d.
7986 | 16 | Warning: Pinning tables should be carefully considered. If a pinned table is larger, or grows larger, than the available data cache, the server may need to be restarted and the table unpinned.
7991 | 16 | System table mismatch: Table '%.*ls', object ID %d has index ID 1 in sysindexes but the status in sysobjects does not have the clustered bit set. The table will be checked as a heap.
7992 | 16 | Cannot shrink 'read only' database '%.*ls'
7993 | 10 | Cannot shrink file '%d' in database '%.*ls' to %d pages as it only contains %d pages.
7994 | 16 | Object ID %d, index ID %d: FirstIAM field in sysindexes is %S_PGID. FirstIAM for statistics only and dummy index entries should be (0:0).
7995 | 16 | Database '%ls' consistency errors in sysobjects, sysindexes, syscolumns, or systypes prevent further %ls processing.
7996 | 16 | Extended stored procedures can only be created in the master database.
7997 | 16 | '%.*ls' does not contain an identity column.
7998 | 16 | Checking identity information: current identity value '%.*hs', current column value '%.*hs'.
7999 | 16 | Could not find any index named '%.*ls' for table '%.*ls'.


Errors 8000 - 8999

Error | Severity | Description
8101 | 16 | An explicit value for the identity column in table '%.*ls' can only be specified when a column list is used and IDENTITY_INSERT is ON.
8102 | 16 | Cannot update identity column '%.*ls'.
8103 | 16 | Table '%.*ls' does not exist or cannot be opened for SET operation.
8104 | 16 | The current user is not the database or object owner of table '%.*ls'. Cannot perform SET operation.
8105 | 16 | '%.*ls' is not a user table. Cannot perform SET operation.
8106 | 16 | Table '%.*ls' does not have the identity property. Cannot perform SET operation.
8107 | 16 | IDENTITY_INSERT is already ON for table '%.*ls.%.*ls.%.*ls'. Cannot perform SET operation for table '%.*ls'.
8108 | 16 | Cannot add identity column, using the SELECT INTO statement, to table '%.*ls', which already has column '%.*ls' that inherits the identity property.
8109 | 16 | Attempting to add multiple identity columns to table '%.*ls' using the SELECT INTO statement.
8110 | 16 | Cannot add multiple PRIMARY KEY constraints to table '%.*ls'.
8111 | 16 | Cannot define PRIMARY KEY constraint on nullable column in table '%.*ls'.
8112 | 16 | Cannot add more than one clustered index for constraints on table '%.*ls'.
8114 | 16 | Error converting data type %ls to %ls.
8115 | 16 | Arithmetic overflow error converting %ls to data type %ls.
8116 | 16 | Argument data type %ls is invalid for argument %d of %ls function.
8117 | 16 | Operand data type %ls is invalid for %ls operator.
8118 | 16 | Column '%.*ls.%.*ls' is invalid in the select list because it is not contained in an aggregate function and there is no GROUP BY clause.
8119 | 16 | Column '%.*ls.%.*ls' is invalid in the HAVING clause because it is not contained in an aggregate function and there is no GROUP BY clause.
8120 | 16 | Column '%.*ls.%.*ls' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
8121 | 16 | Column '%.*ls.%.*ls' is invalid in the HAVING clause because it is not contained in either an aggregate function or the GROUP BY clause.
8122 | 16 | Only the first query in a UNION statement can have a SELECT with an assignment.
8123 | 16 | A correlated expression is invalid because it is not in a GROUP BY clause.
8124 | 16 | Multiple columns are specified in an aggregated expression containing an outer reference. If an expression being aggregated contains an outer reference, then that outer reference must be the only column referenced in the expression.
8125 | 16 | An aggregated expression containing an outer reference must be contained in either the select list, or a HAVING clause subquery in the query whose FROM clause contains the table with the column being aggregated.
8126 | 16 | Column name '%.*ls.%.*ls' is invalid in the ORDER BY clause because it is not contained in an aggregate function and there is no GROUP BY clause.
8127 | 16 | Column name '%.*ls.%.*ls' is invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause.
8128 | 10 | Using '%s' version '%s' to execute extended stored procedure '%s'.
8129 | 16 | The new disk size must be greater than %d. Consider using DBCC SHRINKDB.
8130 | 16 | The device is not a database device. Only database devices can be expanded.
8131 | 10 | Extended stored procedure DLL '%s' does not export __GetXpVersion(). Refer to the topic "Backward Compatibility Details (Level 1) - Open Data Services" in the documentation for more information.
8132 | 10 | Extended stored procedure DLL '%s' reports its version is %d.%d. Server expects version %d.%d.
8133 | 16 | None of the result expressions in a CASE specification can be NULL.
8134 | 16 | Divide by zero error encountered.
8135 | 16 | Table level constraint does not specify column list, table '%.*ls'.
8136 | 16 | Duplicate columns specified in %ls constraint key list, table '%.*ls'.
8138 | 16 | More than 16 columns specified in foreign key column list, table '%.*ls'.
8139 | 16 | Number of referencing columns in foreign key differs from number of referenced columns, table '%.*ls'.
8140 | 16 | More than one key specified in column level %ls constraint, table '%.*ls'.
8141 | 16 | Column %ls constraint for column '%.*ls' references another column, table '%.*ls'.
8142 | 16 | Subqueries are not supported in %ls constraints, table '%.*ls'.
8143 | 16 | Parameter '%.*ls' was supplied multiple times.
8144 | 16 | Too many arguments were supplied for procedure %.*ls.
8145 | 16 | %.*ls is not a parameter for procedure %.*ls.
8146 | 16 | Procedure %.*ls has no parameters and arguments were supplied.
8147 | 16 | Could not create IDENTITY attribute on nullable column '%.*ls', table '%.*ls'.
8148 | 16 | More than one column %ls constraint specified for column '%.*ls', table '%.*ls'.
8150 | 16 | Multiple NULL constraints were specified for column '%.*ls', table '%.*ls'.
8151 | 16 | Both a PRIMARY KEY and UNIQUE constraint have been defined for column '%.*ls', table '%.*ls'. Only one is allowed.
8152 | 16 | String or binary data would be truncated.
8153 | 0 | Warning: Null value eliminated from aggregate.
8154 | 15 | The table '%.*ls' is ambiguous.
8155 | 15 | No column was specified for column %d of '%.*ls'.
8156 | 15 | The column '%.*ls' was specified multiple times for '%.*ls'.
8157 | 15 | All the queries in a query expression containing a UNION operator must have the same number of expressions in their select lists.
8158 | 15 | '%.*ls' has more columns than were specified in the column list.
8159 | 15 | '%.*ls' has fewer columns than were specified in the column list.
8160 | 15 | A grouping function can only be specified when either CUBE or ROLLUP is specified in the GROUP BY clause.
8161 | 15 | A grouping function argument does not match any of the expressions in the GROUP BY clause.
8162 | 16 | Formal parameter '%.*ls' was defined as OUTPUT but the actual parameter not declared OUTPUT.
8163 | 16 | The text, ntext, or image data type cannot be selected as DISTINCT.
8164 | 16 | An INSERT EXEC statement cannot be nested.
8166 | 16 | Constraint name '%.*ls' not permitted. Constraint names cannot begin with a number sign (#).
8168 | 16 | Cannot create two constraints named '%.*ls'. Duplicate constraint names are not allowed.
8169 | 16 | Syntax error converting from a character string to uniqueidentifier.
8170 | 16 | Insufficient result space to convert uniqueidentifier value to char.
8175 | 10 | Could not find table %.*ls. Will try to resolve this table name later.
8177 | 16 | Cannot use a column in the %hs clause unless it is contained in either an aggregate function or the GROUP BY clause.
8178 | 16 | Prepared statement '%.*ls' expects parameter %.*ls, which was not supplied.
8179 | 16 | Could not find prepared statement with handle %d.
8180 | 16 | Statement(s) could not be prepared.
8181 | 16 | Text for '%.*ls' is missing from syscomments. The object must be dropped and re-created before it can be used.
8190 | 16 | Cannot compile replication filter procedure without defining table being filtered.
8191 | 16 | Replication filter procedures can only contain SELECT, GOTO, IF, WHILE, RETURN, and DECLARE statements.
8192 | 16 | Replication filter procedures cannot have parameters.
8193 | 16 | Cannot execute a procedure marked FOR REPLICATION.
8194 | 16 | Cannot execute a USE statement while an application role is active.
8196 | 16 | Duplicate column specified as ROWGUIDCOL.
8197 | 16 | Windows NT user '%.*ls' does not have server access.
8198 | 16 | Could not obtain information about Windows NT group/user '%ls'.
8199 | 16 | In EXECUTE <procname>, procname can only be a literal or variable of type char, varchar, nchar, or nvarchar.
8501 | 16 | MS DTC on server '%.*ls' is unavailable.
8502 | 20 | Unknown MS DTC token '0x%x' received.
8504 | 20 | Invalid transaction import buffer.
8506 | 20 | Invalid transaction state change requested from %hs to %hs.
8508 | 20 | QueryInterface failed for '%hs': %hs.
8509 | 20 | Import of MS DTC transaction failed: %hs.
8510 | 20 | Enlist of MS DTC transaction failed: %hs.
8511 | 20 | Unknown isolation level %d requested from MS DTC.
8512 | 20 | MS DTC Commit acknowledgement failed: %hs.
8513 | 20 | MS DTC Abort acknowledgement failed: %hs.
8514 | 20 | MS DTC PREPARE acknowledgement failed: %hs.
8515 | 20 | MS DTC Global state is invalid.
8517 | 20 | Failed to get MS DTC PREPARE information: %hs.
8518 | 20 | MS DTC BEGIN TRANSACTION failed: %hs.
8519 | 16 | Current MS DTC transaction must be committed by remote client.
8520 | 20 | Commit of internal MS DTC transaction failed: %hs.
8521 | 20 | Invalid awakening state. Slept in %hs; awoke in %hs.
8522 | 20 | Distributed transaction aborted by MS DTC.
8523 | 15 | PREPARE TRAN statement not allowed on MS DTC transaction.
8524 | 16 | The current transaction could not be exported to the remote provider. It has been rolled back.
8601 | 17 | Internal Query Processor Error: The query processor could not obtain access to a required interface.
8602 | 16 | The Index Tuning Wizard cannot process queries which contain index hints. Remove the index hints which reference table '%.*ls'.
8616 | 10 | The index hints for table '%.*ls' were ignored because the table was considered a fact table in the star join.
8617 | 17 | Invalid Query: CUBE and ROLLUP cannot compute distinct aggregates.
8618 | 17 | Warning: The query processor could not produce a query plan from the optimizer because the total length of all the columns in the GROUP BY clause exceeds 8000 bytes.
8619 | 17 | Warning: The query processor could not produce a query plan from the optimizer because the maximum row size of an intermediate result was too large to fit into a work table. Resubmit your query without the ROBUST PLAN hint.
8620 | 17 | Internal Query Processor Error: The query processor encountered an internal limit overflow.
8621 | 16 | Internal Query Processor Error: The query processor ran out of stack space during query optimization.
8622 | 16 | Query processor could not produce a query plan because of the hints defined in this query. Resubmit the query without specifying any hints and without using SET FORCEPLAN.
8623 | 16 | Internal Query Processor Error: The query processor could not produce a query plan.
8624 | 16 | Internal SQL Server error.
8625 | 16 | Warning: The join order has been enforced because a local join hint is used.
8626 | 16 | Only text pointers are allowed in work tables, never text, ntext, or image columns. The query processor produced a query plan that required a text, ntext, or image column in a work table.
8627 | 16 | The query processor could not produce a query plan because of the combination of hints and text, ntext, or image data passing through operators using work tables.
8628 | 17 | A time out occurred while waiting to optimize the query. Re-run the query.
8629 | 16 | The query processor could not produce a query plan from the optimizer because a query cannot update a text, ntext, or image column and a clustering key at the same time.
8630 | 17 | Internal Query Processor Error: The query processor encountered an unexpected error during execution.
8640 | 17 | Internal Query Processor Error: The query processor encountered an unexpected work table error during execution.
8642 | 17 | The query processor could not start the necessary thread resources for parallel query execution.
8644 | 16 | Internal Query Processor Error: The plan selected for execution does not support the invoked given execution routine.
8645 | 17 | A time out occurred while waiting for memory resources to execute the query. Re-run the query.
8646 | 21 | The index entry for row ID %.*hs was not found in index ID %d, of table %d, in database '%.*ls'.
8647 | 20 | Scan on sysindexes for database ID %d, object ID %ld, returned a duplicate index ID %d. Run DBCC CHECKTABLE on sysindexes.
8648 | 20 | Could not insert a row larger than the page size into a hash table. Resubmit the query with the ROBUSTPLAN hint.
8649 | 17 | The query has been canceled because the estimated cost of this query (%d) exceeds the configured threshold of %d. Contact the system administrator.
8650 | 13 | Intra-query parallelism caused your server command (process ID #%d) to deadlock. Rerun the query without intra-query parallelism by using the query hint option (maxdop 1).
8651 | 17 | Could not perform the requested operation because the minimum query memory is not available. Decrease the configured value for the 'min memory per query' server configuration option.
8680 | 17 | Internal Query Processor Error: The query processor encountered an unexpected error during the processing of a remote query phase.
8901 | 13 | Deadlock detected during DBCC. Complete the transaction in progress and retry this statement.
8902 | 17 | Memory allocation error during DBCC processing.
8903 | 16 | Extent %S_PGID in database ID %d is allocated in both GAM %S_PGID and SGAM %S_PGID.
8904 | 16 | Extent %S_PGID in database ID %d is allocated by more than one allocation object.
8905 | 16 | Extent %S_PGID in database ID %d is marked allocated in the GAM, but no SGAM or IAM has allocated it.
8906 | 16 | Page %S_PGID in database ID %d is allocated in the SGAM %S_PGID and PFS %S_PGID, but was not allocated in any IAM. PFS flags '%hs'.
8907 | 16 | Mixed extent %S_PGID in database ID %d has %d free pages. It should be included in the SGAM %S_PGID.
8908 | 16 | Table Corrupt: Database ID %d, object ID %d, index ID %d. Chain linkage mismatch. %S_PGID->next = %S_PGID, but %S_PGID->prev = %S_PGID.
8909 | 16 | Table Corrupt: Object ID %d, index ID %d, page ID %S_PGID. The PageId in the page header = %S_PGID.
8910 | 16 | Page %S_PGID in database ID %d is allocated to both object ID %d, index ID %d, and object ID %d, index ID %d.
8911 | 10 | The error has been repaired.
8912 | 10 | %.*ls fixed %d allocation errors and %d consistency errors in database '%ls'.
8913 | 16 | Extent %S_PGID is allocated to '%ls' and at least one other object.
8914 | 10 | Incorrect PFS free space information for page %S_PGID, object ID %d, index ID %d, in database ID %d. Expected value %hs, actual value %hs.
8915 | 10 | %S_PGID (number of mixed extents = %ld, mixed pages = %ld).
8916 | 10 | Object ID %ld, Index ID %ld, data extents %ld, pages %ld, mixed extent pages %ld.
8917 | 10 | Object ID %ld, Index ID %ld, index extents %ld, pages %ld, mixed extent pages %ld.
8918 | 10 | (number of mixed extents = %ld, mixed pages = %ld) in this database.
8919 | 16 | Single page allocation %S_PGID in table %ls, object ID %d, index ID %d is not allocated in PFS page ID %S_PGID.
8920 | 16 | Cannot perform a %ls operation inside a user transaction. Terminate the transaction and reissue the statement.
8921 | 16 | CHECKTABLE aborted. A failure was detected while collecting facts. Possibly tempdb out of space or a system table is corrupt. Check previous errors.
8922 | 10 | Could not repair this error.
8923 | 10 | The repair level on the DBCC statement caused this repair to be bypassed.
8924 | 10 | Repairing this error requires other errors to be corrected first.
8925 | 16 | Table Corrupt: Cross object linkage: Page %S_PGID, slot %d, in object ID %d, index ID %d, refers to page %S_PGID, slot %d, in object ID %d, index ID %d.
8926 | 16 | Table Corrupt: Cross object linkage: Parent page %S_PGID, slot %d, in object ID %d, index ID %d, and page %S_PGID, slot %d, in object ID %d, index ID %d, next refer to page %S_PGID but are not in the same object.
8927 | 16 | Object ID %d, index ID %d: The ghosted record count (%d) in the header does not match the number of ghosted records (%d) found on page %S_PGID.
8928 | 16 | Object ID %d, index ID %d: Page %S_PGID could not be processed. See other errors for details.
8929 | 16 | Object ID %d: Errors found in text ID %I64d owned by data record identified by %.*ls.
8930 | 16 | Table Corrupt: Object ID %d, index ID %d cross-object chain linkage. Page %S_PGID points to %S_PGID in object ID %d, index ID %d.
8931 | 16 | Table Corrupt: Object ID %d, index ID %d B-tree level mismatch, page %S_PGID. Level %d does not match level %d from parent %S_PGID or previous %S_PGID.
8932 | 16 | Table Corrupt: Object ID %d, index ID %d, column '%.*ls'. The column ID %d is not valid for this table. The valid range is from 1 to %d. System table corruption.
8933 | 16 | Table Corrupt: Object ID %d, index ID %d. The low key value on page %S_PGID (level %d) is not %ls the key value in the parent %S_PGID slot %d.
8934 | 16 | Table Corrupt: Object ID %d, index ID %d. The high key value on page %S_PGID (level %d) is not less than the low key value in the parent %S_PGID, slot %d of the next page %S_PGID.
8935 | 16 | Table Corrupt: Object ID %d, index ID %d. The previous link %S_PGID on page %S_PGID does not match the previous page %S_PGID that the parent %S_PGID, slot %d expects for this page.
8936 | 16 | Table Corrupt: Object ID %d, index ID %d. B-tree chain linkage mismatch. %S_PGID->next = %S_PGID, but %S_PGID->Prev = %S_PGID.
8937 | 16 | Table Corrupt: Object ID %d, index ID %d. B-tree page %S_PGID has two parent nodes %S_PGID, slot %d and %S_PGID, slot %d.
8938 | 16 | Table Corrupt: Page %S_PGID corrupt. Object ID %d, index ID %d. Unexpected page type %d.
8939 | 16 | Table Corrupt: Object ID %d, index ID %d, page %S_PGID. Test (%hs) failed. Values are %ld and %ld.
8940 | 16 | Table Corrupt: Object ID %d, index ID %d, page %S_PGID. Test (%hs) failed. Address 0x%x is not aligned.
8941 | 16 | Table Corrupt: Object ID %d, index ID %d, page %S_PGID. Test (%hs) failed. Slot %d, offset 0x%x is invalid.
8942 | 16 | Table Corrupt: Object ID %d, index ID %d, page %S_PGID. Test (%hs) failed. Slot %d, offset 0x%x overlaps with the prior row.
8943 | 16 | Table Corrupt: Object ID %d, index ID %d, page %S_PGID. Test (%hs) failed. Slot %d, row extends into freespace at 0x%x.
8944 | 16 | Table Corrupt: Object ID %d, index ID %d, page %S_PGID, row %d. Test (%hs) failed. Values are %ld and %ld.
8945 | 16 | Table Corrupt: Object ID %d, index ID %d will be rebuilt.
8946 | 16 | Table Corrupt: Allocation page %S_PGID has invalid %ls page header values. Type is %d. Check type, object ID and page ID on the page.
8947 | 16 | Table Corrupt: Multiple IAM pages for object ID %d, index ID %d contain allocations for the same interval. IAM pages %S_PGID and %S_PGID.
8948 | 16 | Database Corrupt: Page %S_PGID is marked with the wrong type in PFS page %S_PGID. PFS status 0x%x expected 0x%x.
8949 | 10 | %.*ls fixed %d allocation errors and %d consistency errors in table '%ls' (object ID %d).
8950 | 16 | %.*ls fixed %d allocation errors and %d consistency errors not associated with any single object.
8951 | 16 | Table Corrupt: Table '%ls' (ID %d). Missing or invalid key in index '%ls' (ID %d) for the row:
8952 | 16 | Table Corrupt: Database '%ls', index '%ls.%ls' (ID %d) (index ID %d). Extra or invalid key for the keys:
8953 | 10 | Repair: Deleted text column, text ID %I64d, for object ID %d on page %S_PGID, slot %d.
8954 | 10 | %.*ls found %d allocation errors and %d consistency errors not associated with any single object.
8955 | 16 | Data row (%d:%d:%d) identified by (%ls) has index values (%ls).
8956 | 16 | Index row (%d:%d:%d) with values (%ls) points to the data row identified by (%ls).
8957 | 10 | DBCC %ls (%ls%ls%ls) executed by %ls found %d errors and repaired %d errors.
8958 | 10 | %ls is the minimum repair level for the errors found by DBCC %ls (%ls %ls).
8959 | 16 | Table Corrupt: IAM page %S_PGID for object ID %d, index ID %d is linked in the IAM chain for object ID %d, index ID %d by page %S_PGID.
8960 | 23 | Table Corrupt: Page %S_PGID, slot %d, column %d is not a valid complex column.
8961 | 23 | Table Corrupt: Object ID %d. The text, ntext, or image node at page %S_PGID, slot %d, text ID %I64d does not match its reference from page %S_PGID, slot %d.
8962 | 23 | Table Corrupt: The text, ntext, or image node at page %S_PGID, slot %d, text ID %I64d has incorrect node type %d.
8963 | 23 | Table Corrupt: The text, ntext, or image node at page %S_PGID, slot %d, text ID %I64d has type %d. It cannot be placed on a page of type %d.
8964 | 23 | Table Corrupt: Object ID %d. The text, ntext, or image node at page %S_PGID, slot %d, text ID %I64d is not referenced.
8965 | 23 | Table Corrupt: Object ID %d. The text, ntext, or image node at page %S_PGID, slot %d, text ID %I64d is referenced by page %S_PGID, slot %d, but was not seen in the scan.
8966 | 22 | Could not read and latch page %S_PGID with latch type %ls. %ls failed.
8967 | 16 | Table Corrupt: Invalid value detected in %ls for Object ID %d, index ID %d. Row skipped.
8968 | 16 | Table Corrupt: %ls page %S_PGID (object ID %d, index ID %d) is out of the range of this database.
8969 | 16 | Table Corrupt: IAM chain linkage error: Object ID %d, index ID %d. The next page for IAM page %S_PGID is %S_PGID, but the previous link for page %S_PGID is %S_PGID.
8970 | 16 | Row corrupt: Object ID %d, index ID %d, page ID %S_PGID, row ID %d. Column '%.*ls' was created NOT NULL, but is NULL in the row.
8971 | 16 | Forwarded row mismatch: Object ID %d, page %S_PGID, slot %d points to forwarded row page %S_PGID, slot %d; the forwarded row points back to page %S_PGID, slot %d.
8972 | 16 | Forwarded row referenced by more than one row. Object ID %d, page %d, slot %d incorrectly points to forwarded row page %S_PGID, slot %d; the forwarded row correctly refers back to page %S_PGID, slot %d.
8973 | 16 | CHECKTABLE processing of object ID %d, index ID %d encountered page %S_PGID, slot %d twice. Possible internal error or allocation fault.
8974 | 16 | Text node referenced by more than one node. Object ID %d, text, ntext, or image node page %S_PGID, slot %d, text ID %I64d is pointed to by page %S_PGID, slot %d and by page %S_PGID, slot %d.
8975 | 16 | Page referenced by more than one page: Object ID %d, index ID %d. Page %S_PGID->next is an unmatched linkage to page %S_PGID. %S_PGID->next matches the previous linkage of the page.
8976 | 16 | Table Corrupt: Object ID %d, index ID %d. Page %S_PGID not allocated or corrupt. Parent %S_PGID and previous %S_PGID refer to it.
8977 | 16 | Table Corrupt: Object ID %d, index ID %d. Parent node for page %S_PGID was not encountered.
8978 | 16 | Table Corrupt: Object ID %d, index ID %d. Page %S_PGID is missing a reference from previous page %S_PGID. Possible chain linkage problem.
8979 | 16 | Table Corrupt: Object ID %d, index ID %d. Page %S_PGID is missing references from parent (unknown) and previous (page %S_PGID) nodes. Possible bad root entry in sysindexes.
8980 | 16 | Table Corrupt: Object ID %d, index ID %d. Index node page %S_PGID, slot %d refers to child page %S_PGID and previous child %S_PGID, but they were not encountered.
8981 | 16 | Table Corrupt: Object ID %d, index ID %d. The next pointer of %S_PGID refers to page %S_PGID. Neither %S_PGID nor its parent were encountered. Possible bad chain linkage.
8982 | 16 | Table Corrupt: Cross object linkage. Page %S_PGID->next in object ID %d, index ID %d refers to page %S_PGID in object ID %d, index ID %d but is not in the same index.
8983 | 10 | Allocation page %S_PGID. Extents %d, used pages %d, referenced pages %d, mixed extents %d, mixed pages %d.
8984 | 10 | Object ID %d, index ID %d. Allocations for %S_PGID. IAM %S_PGID, extents %d, used pages %d, mixed pages %d.
8985 | 16 | Could not locate file '%.*ls' in sysfiles.
8986 | 16 | Too many errors found (%d) for object ID %d. To see all error messages rerun the statement using "WITH ALL_ERRORMSGS".
8987 | 16 | No help available for DBCC statement '%.*ls'.
8988 | 10 | The schema for database '%ls' is changing. May find spurious allocation problems due to schema changes in progress.
8989 | 10 | %.*ls found %d allocation errors and %d consistency errors in database '%ls'.
8990 | 10 | %.*ls found %d allocation errors and %d consistency errors in table '%ls' (object ID %d).
8991 | 16 | 0x%.8x + 0x%.8x bytes is not a valid address range.
8992 | 16 | Database ID %d, object '%ls' (ID %d). Loop in data chain detected at %S_PGID.
8993 | 16 | Object ID %d, forwarding row page %S_PGID, slot %d points to page %S_PGID, slot %d. Did not encounter forwarded row. Possible allocation error.
8994 | 16 | Object ID %d, forwarded row page %S_PGID, slot %d should be pointed to by forwarding row page %S_PGID, slot %d. Did not encounter forwarding row. Possible allocation error.
8995 | 16 | System table '%.*ls' (object ID %d, index ID %d) is in filegroup %d. All system tables must be in filegroup %d.
8996 | 16 | IAM page %S_PGID for object ID %d, index ID %d controls pages in filegroup %d, that should be in filegroup %d.
8997 | 16 | Single page allocation %S_PGID for object ID %d, index ID %d is in filegroup %d; it should be in filegroup %d.
8998 | 16 | Page corruptions on the GAM, SGAM, or PFS pages do not allow CHECKALLOC to verify database ID %d pages from %S_PGID to %S_PGID. See other errors for cause.
8999 | 10 | Database tempdb allocation errors prevent further %ls processing.


Errors 9000 - 9999

Error | Severity | Description
9001 | 10 | The log for database '%.*ls' is not available.
9002 | 19 | The log file for database '%.*ls' is full. Back up the transaction log for the database to free up some log space.
9003 | 20 | The LSN %S_LSN passed to log scan in database '%.*ls' is invalid.
9004 | 21 | The log for database '%.*ls' is corrupt.


Errors 10000 - 10999

Error | Severity | Description
10000 | 16 | Unknown provider error.
10001 | 16 | The provider reported an unexpected catastrophic failure.
10002 | 16 | The provider did not implement the functionality.
10003 | 16 | The provider ran out of memory.
10004 | 16 | One or more arguments were reported invalid by the provider.
10005 | 16 | The provider did not support an interface.
10006 | 16 | The provider indicated an invalid pointer was used.
10007 | 16 | The provider indicated an invalid handle was used.
Error 10008 (DB-Library) | 16 | The provider aborted the operation.
10009 | 16 | The provider did not give any information about the error.
10010 | 16 | The data necessary to complete this operation was not yet available to the provider.
10021 | 16 | Execution aborted by the provider because a resource limit was reached.
10022 | 16 | The provider called a method from IRowsetNotify in the consumer, and the method has not yet returned.
10023 | 16 | The provider does not support the necessary method.
Error 10024 (DB-Library) | 16 | The provider indicates that the user did not have the permission to perform the operation.
10031 | 16 | An error occurred because one or more properties could not be set.
10032 | 16 | Cannot return multiple result sets (not supported by the provider).
10033 | 16 | The specified index does not exist or the provider does not support an index scan on this data source.
10034 | 16 | The specified table does not exist.
10035 | 16 | No value was given for one or more of the required parameters.
10041 | 16 | Could not set any property values.
10042 | 16 | Cannot set any properties while there is an open rowset.
10051 | 16 | An error occurred while setting the data.
10052 | 16 | The insertion was canceled by the provider during notification.
Error 10053 (DB-Library) | 16 | Could not convert the data value due to reasons other than sign mismatch or overflow.
Error 10054 (DB-Library) | 16 | The data value for one or more columns overflowed the type used by the provider.
10055 | 16 | The data violated the integrity constraints for one or more columns.
10056 | 16 | The number of rows that have pending changes has exceeded the limit specified by the DBPROP_MAXPENDINGROWS property.
10057 | 16 | Cannot create the row. Would exceed the total number of active rows supported by the rowset.
10058 | 16 | The consumer cannot insert a new row before releasing previously-retrieved row handles.
10061 | 16 | An error occurred while setting data for one or more columns.
10062 | 16 | The change was canceled by the provider during notification.
10063 | 16 | Could not convert the data value due to reasons other than sign mismatch or overflow.
10064 | 16 | The data value for one or more columns overflowed the type used by the provider.
10065 | 16 | The data violated the integrity constraints for one or more columns.
10066 | 16 | The number of rows that have pending changes has exceeded the limit specified by the DBPROP_MAXPENDINGROWS property.
10067 | 16 | The rowset was using optimistic concurrency and the value of a column has been changed after the containing row was last fetched or resynchronized.
10068 | 16 | The consumer could not delete the row. A deletion is pending or has already been transmitted to the data source.
10069 | 16 | The consumer could not delete the row. The insertion has been transmitted to the data source.
10075 | 16 | An error occurred while deleting the row.
10081 | 16 | The rowset uses integrated indexes and there is no current index.
10085 | 16 | RestartPosition on the table was canceled during notification.
10086 | 16 | The table was built over a live data stream and the position cannot be restarted.
10087 | 16 | The provider did not release some of the existing rows.
10088 | 16 | The order of the columns was not specified in the object that created the rowset. The provider had to reexecute the command to reposition the next fetch position to its initial position, and the order of the columns changed.


Errors 11000 - 11999

Error | Severity | Description
11000 | 16 | Unknown status code for this column.
11001 | 16 | Non-NULL value successfully returned.
11002 | 16 | Deferred accessor validation occurred. Invalid binding for this column.
11003 | 16 | Could not convert the data value due to reasons other than sign mismatch or overflow.
11004 | 16 | Successfully returned a NULL value.
11005 | 16 | Successfully returned a truncated value.
11006 | 16 | Could not convert the data type because of a sign mismatch.
11007 | 16 | Conversion failed because the data value overflowed the data type used by the provider.
11008 | 16 | The provider cannot allocate memory or open another storage object on this column.
11009 | 16 | The provider cannot determine the value for this column.
11010 | 16 | The user did not have permission to write to the column.
11011 | 16 | The data value violated the integrity constraints for the column.
11012 | 16 | The data value violated the schema for the column.
11013 | 16 | The column had a bad status.
11014 | 16 | The column used the default value.
11015 | 16 | The column was skipped when setting data.
11031 | 16 | The row was successfully deleted.
11032 | 16 | The table was in immediate-update mode, and deleting a single row caused more than one row to be deleted in the data source.
11033 | 16 | The row was released even though it had a pending change.
11034 | 16 | Deletion of the row was canceled during notification.
11036 | 16 | The rowset was using optimistic concurrency and the value of a column has been changed after the containing row was last fetched or resynchronized.
11037 | 16 | The row has a pending delete or the deletion had been transmitted to the data source.
11038 | 16 | The row is a pending insert row.
11039 | 16 | DBPROP_CHANGEINSERTEDROWS was VARIANT_FALSE and the insertion for the row has been transmitted to the data source.
11040 | 16 | Deleting the row violated the integrity constraints for the column or table.
11041 | 16 | The row handle was invalid or was a row handle to which the current thread does not have access rights.
11042 | 16 | Deleting the row would exceed the limit for pending changes specified by the rowset property DBPROP_MAXPENDINGROWS.
11043 | 16 | The row has a storage object open.
11044 | 16 | The provider ran out of memory and could not fetch the row.
11045 | 16 | User did not have sufficient permission to delete the row.
11046 | 16 | The table was in immediate-update mode and the row was not deleted due to reaching a limit on the server, such as query execution timing out.
11047 | 16 | Updating did not meet the schema requirements.
11048 | 16 | There was a recoverable, provider-specific error, such as an RPC failure.
11100 | 16 | The provider indicates that conflicts occurred with other properties or requirements.
11101 | 16 | Could not obtain an interface required for text, ntext, or image access.
11102 | 16 | The provider could not support a required row lookup interface.
11103 | 16 | The provider could not support an interface required for the UPDATE/DELETE/INSERT statements.
11104 | 16 | The provider could not support insertion on this table.
11105 | 16 | The provider could not support updates on this table.
11106 | 16 | The provider could not support deletion on this table.
11107 | 16 | The provider could not support a row lookup position.
11108 | 16 | The provider could not support a required property.
11109 | 16 | The provider does not support an index scan on this data source.


Errors 13000 - 13999

Error | Severity | Description
13001 | 10 | data page
13002 | 10 | index page
13003 | 10 | leaf page
13004 | 10 | last
13005 | 10 | root
13006 | 10 | read from
13007 | 10 | send to
13008 | 10 | receive
13009 | 10 | send
13010 | 10 | read
13011 | 10 | wait
13012 | 10 | A USE database statement
13013 | 10 | a procedure or trigger
13014 | 10 | A DISTINCT clause
13015 | 10 | a view
13016 | 10 | An INTO clause
13017 | 10 | An ORDER BY clause
13018 | 10 | A COMPUTE clause
13019 | 10 | a SELECT INTO statement
13020 | 10 | option
13021 | 10 | offset option
13022 | 10 | statistics option
13023 | 10 | parameter option
13024 | 10 | function name
13026 | 10 | parameter
13027 | 10 | convert specification
13028 | 10 | index
13029 | 10 | table
13030 | 10 | database
13031 | 10 | procedure
13032 | 10 | trigger
13033 | 10 | view
13034 | 10 | default
13035 | 10 | rule
13036 | 10 | system
13037 | 10 | unknown type
13038 | 10 | SET statement
13039 | 10 | column
13040 | 10 | type
13041 | 10 | character string
13042 | 10 | integer
13043 | 10 | identifier
13044 | 10 | number
13045 | 10 | integer value
13046 | 10 | floating point value
13047 | 10 | object
13048 | 10 | column heading
13076 | 10 | an assignment
13077 | 10 | a cursor declaration
13078 | 10 | replication filter
13079 | 10 | variable assignment
13080 | 10 | statistics
13081 | 10 | file
13082 | 10 | filegroup
13083 | 10 | server
13084 | 0 | write


Errors 14000 - 14999

Error | Severity | Description
14001 | 16 | The destination table must not be qualified.
14002 | 16 | Could not find the 'Sync' subsystem with the task ID %ld.
14003 | 16 | You must supply a publication name.
14004 | 16 | %s must be in the current database.
14005 | 16 | Could not drop publication. A subscription exists on it.
14006 | 16 | Could not drop the publication.
14008 | 11 | There are no publications.
14009 | 11 | There are no articles for publication '%s'.
14010 | 16 | The remote server is not defined as a subscription server.
14012 | 16 | The @status parameter value must be either 'active' or 'inactive'.
14013 | 16 | This database is not enabled for publication.
14014 | 16 | The synchronization method (@sync_method) must be either '[bcp] native' or '[bcp] character'.
14015 | 16 | The replication frequency (@repl_freq) must be either 'continuous' or 'snapshot'.
14016 | 16 | The publication '%s' already exists.
14017 | 16 | Invalid @restricted parameter value. Valid options are 'true' or 'false'.
14018 | 16 | Could not create the publication.
14019 | 16 | The @operation parameter value must be either 'add' or 'drop'.
14020 | 16 | Could not obtain the column ID for the specified column. The column was not correctly added to the article.
14021 | 16 | The column was not correctly added to the article.
14022 | 16 | The parameter must be 'description', 'sync_object', 'type', 'status', 'ins_cmd', 'del_cmd', 'upd_cmd', 'filter', 'dest_table', 'creation_script', 'pre_creation_cmd', or 'script_options'.
14023 | 16 | The type must be 'logbased', 'logbased manualfilter', 'logbased manualview', or 'logbased manualboth'.
14025 | 10 | The article was successfully updated.
14027 | 11 | %s does not exist in the current database.
14028 | 16 | Only user tables and procedures can be published.
14029 | 16 | The vertical partition switch must be either 'true' or 'false'.
14030 | 16 | The article '%s' already exists in publication '%s'.
14031 | 16 | User tables and views are the only valid synchronization objects.
14032 | 16 | The value of parameter %s cannot be 'all'. It is reserved by replication stored procedures.
14033 | 16 | Could not change replication frequency because there are active subscriptions on the publication.
14034 | 16 | The publication name (@publication) cannot be the keyword 'all'.
14035 | 16 | The replication option '%s' of database '%s' has already been set to true.
14036 | 16 | Could not enable database for publishing.
14037 | 16 | The replication option '%s' of database '%s' has already been set to false.
14038 | 16 | Could not disable database for publishing.
14039 | 16 | Could not construct column clause for article view. Reduce the number of columns or create the view manually.
14040 | 16 | The server '%s' is already a subscriber.
14042 | 16 | Could not create Subscriber.
14043 | 16 | The parameter %s cannot be NULL.
14044 | 16 | Owner-qualified %s names are not allowed.
14046 | 16 | Could not drop article. A subscription exists on it.
14047 | 16 | Could not drop %s.
14048 | 16 | The server '%s' is not a Subscriber.
14049 | 16 | Stored procedures for replication are the only objects that can be used as a filter.
14050 | 11 | You do not have a subscription on this publication or article.
14051 | 16 | The parameter value must be 'sync_type' or 'dest_db'.
14052 | 16 | The @sync_type parameter value must be 'automatic' or 'none'.
14053 | 16 | The subscription could not be updated at this time.
14054 | 10 | The subscription was successfully updated.
14055 | 10 | The subscription does not exist.
14056 | 16 | The subscription could not be dropped at this time.
14057 | 16 | The subscription could not be created.
14058 | 16 | The subscription already exists.
14061 | 16 | The @pre_creation_cmd parameter value must be 'none', 'drop', 'delete', or 'truncate'.
14062 | 10 | The Subscriber was dropped.
14063 | 11 | The remote server does not exist or has not been designated as a valid Subscriber.
14065 | 16 | The @status parameter value must be 'active', 'inactive', or 'subscribed'.
14066 | 16 | The previous status must be 'active', 'inactive', or 'subscribed'.
14067 | 16 | The status value is the same as the previous status value.
14068 | 16 | Could not update sysobjects. The subscription status could not be changed.
14069 | 16 | Could not update sysarticles. The subscription status could not be changed.
14070 | 16 | Could not update the distribution database subscription table. The subscription status could not be changed.
14071 | 16 | Could not find the Distributor, or the distribution database, for the local server. The Distributor may not be installed, or the local server may not be configured as a Distribution Publisher at the Distributor.
14074 | 16 | The server '%s' is already listed as a Publisher.
14075 | 16 | The Publisher could not be created at this time.
14076 | 16 | Could not grant replication login privilege to '%s'.
14077 | 10 | The publication was successfully updated.
14078 | 16 | The parameter must be 'description', 'taskid', 'sync_method', 'status', 'repl_freq', 'restricted', 'retention', 'immediate_sync', 'enabled_for_internet', 'allow_push', 'allow_pull', 'allow_anonymous', 'retention', or 'default_access'.
14079 | 16 | Do not qualify the destination object name with a database. Use the 'dest_db' property of sp_changesubscription to specify a destination database.
14080 | 11 | The remote server does not exist or has not been designated as a valid Publisher.
14085 | 16 | The Subscriber information could not be obtained from the Distributor.
14088 | 16 | The table '%s' must have a primary key in order to be published using the transaction-based method.
14091 | 16 | The @type parameter passed to sp_helpreplicationdb must be either 'pub' or 'sub'.
14092 | 16 | Could not change article because there is an existing subscription to the article.
14093 | 16 | Cannot grant or revoke access directly on publication '%s' because it uses the default publication access list.
14094 | 16 | Could not subscribe to article '%s' because the ODBC Subscriber '%s' does not support the @pre_creation_cmd parameter value 'truncate'.
14095 | 16 | Could not subscribe to publication '%s' because ODBC Subscriber '%s' only supports the @sync_method parameter value 'bcp character' .
14096 | 16 | The path and name of the table creation script must be specified if the @pre_creation_cmd parameter value is 'drop'.
14097 | 16 | The @type parameter value must be 'no column names', 'include column names', 'string literals', or 'parameters'.
14098 | 16 | Cannot drop Distribution Publisher '%s'. The remote Publisher is using '%s' as Distributor.
14099 | 16 | The server '%s' is already defined as a Distributor.
14101 | 16 | The publication '%s' already has a Snapshot Agent defined.
14105 | 10 | You have successfully updated the distribution database property '%s'.
14106 | 10 | Distribution retention periods must be greater than 0.
14107 | 10 | The @max_distretention value must be larger than the @min_distretention value.
14108 | 10 | Removed %ld history records from %s.
14109 | 10 | The @security_mode parameter value must be 0 (SQL Server Authentication) or 1 (Windows NT Authentication).
14110 | 16 | For sp_changearticle, the @property parameter value must be 'name', 'description', 'dest_object', 'creation_script', 'pre_creation_cmd', or 'schema_option'.
14111 | 16 | The @pre_creation_cmd parameter value must be 'none' or 'drop'.
14112 | 16 | This procedure can only be executed against table-based articles.
14113 | 16 | Could not execute '%s'. Check '%s' in the install directory.
14114 | 16 | '%s' is not configured as a Distributor.
14115 | 16 | The property parameter value must be %s.
14117 | 16 | '%s' is not configured as a distribution database.
14118 | 16 | The @type parameter value must be 'proc exec', or 'serializable proc exec'.
14119 | 16 | Could not add the distribution database '%s'. This distribution database already exists.
14120 | 16 | Could not drop the distribution database '%s'. This distributor database is associated with a Publisher.
14121 | 16 | Could not to drop the Distributor '%s'. This Distributor has associated distribution databases.
14122 | 16 | The @article parameter value must be 'all' for immediate_sync publications.
14123 | 16 | The subscription @sync_type parameter value 'manual' is no longer supported.
14124 | 16 | An immediate_sync publication must have at least one article before it can be subscribed to.
14126 | 16 | You do not have the required permissions to complete the operation.
14128 | 16 | Invalid @subscription_type parameter value. Valid options are 'push' or 'pull'.
14129 | 16 | The @status parameter value must be NULL for 'automatic' sync_type when you add subscriptions to an immediate_sync publication.
14135 | 16 | There is no subscription on Publisher '%s', publisher database '%s', publication '%s'.
14136 | 16 | The keyword 'all' is reserved by replication stored procedures.
14137 | 16 | The @value parameter value must be either 'true' or 'false'.
14138 | 16 | The @optname parameter value must be either 'publish' or 'merge publish'.
14139 | 16 | The replication system table '%s' already exists.
14143 | 16 | Cannot drop Distributor Publisher '%s'. There are Subscribers associated with it in the distribution database '%s'.
14144 | 16 | Cannot drop Subscriber '%s'. There are subscriptions from it in the published database '%s'.
14145 | 16 | You must give the path of a user-supplied article creation script if you enable the schema option of using user-supplied schema script (schema_option & 0x1 = 0).
14146 | 16 | The article parameter '@schema_option' cannot be NULL.
14147 | 16 | Restricted publications are no longer supported.
14148 | 16 | Invalid '%s' value. Valid values are 'true' or 'false'.
14149 | 10 | Removed %ld replication history records in %s seconds (%ld row/secs).
14150 | 10 | Replication-%s: agent %s succeeded. %s
14151 | 18 | Replication-%s: agent %s failed. %s
14152 | 10 | Replication-%s: agent %s scheduled for retry. %s
14153 | 10 | Replication-%s: agent %s warning. %s
14154 | 16 | The Distributor parameter must be '@heartbeat_interval'.
14155 | 16 | Invalid article ID specified for procedure script generation.
14156 | 16 | The custom stored procedure was not specified in the article definition.
14157 | 10 | The subscription created by Subscriber '%s' to publication '%s' has expired and has been dropped.
14158 | 10 | Replication-%s: agent %s: %s.
14159 | 16 | Could not change property '%s' for article '%s' because there is an existing subscription to the article.
14200 | 16 | The specified '%s' is invalid.
14201 | 10 | 0 (all steps)..
14202 | 10 | before or after @active_start_time
14203 | 10 | sp_helplogins [excluding Windows NT groups]
14204 | 10 | 0 (non-idle), 1 (executing), 2 (waiting for thread), 3 (between retries), 4 (idle), 5 (suspended), 7 (performing completion actions)
14205 | 10 | (unknown)
14206 | 10 | 0..n seconds
14207 | 10 | -1 [no maximum], 0..n
14208 | 10 | 1..7 [1 = E-mail, 2 = Pager, 4 = NetSend]
14209 | 10 | 0..127 [1 = Sunday .. 64 = Saturday]
14210 | 10 | notification
14211 | 10 | server
14212 | 10 | (all jobs)
14213 | 16 | Core Job Details:
14214 | 16 | Job Steps:
14215 | 16 | Job Schedules:
14216 | 16 | Job Target Servers:
14217 | 16 | SQL Server Warning: '%s' has performed a forced defection of TSX server '%s'. Run sp_delete_targetserver at the MSX in order to complete the defection.
14218 | 10 | hour
14219 | 10 | minute
14220 | 10 | second
14221 | 16 | This job has one or more notifications to operators other than '%s'. The job cannot be targeted at remote servers as currently defined.
14222 | 16 | Cannot rename the '%s' operator.
14223 | 16 | Cannot modify or delete operator '%s' while this server is a %s.
14224 | 0 | Warning: The server name given is not the current MSX server ('%s').
14225 | 16 | Warning: Could not determine local machine name. This prevents MSX operations from being posted.
14226 | 0 | %ld history entries purged.
14227 | 0 | Server defected from MSX '%s'. %ld job(s) deleted.
14228 | 0 | Server MSX enlistment changed from '%s' to '%s'.
14229 | 0 | Server enlisted into MSX '%s'.
14230 | 0 | SP_POST_MSX_OPERATION: %ld %s download instruction(s) posted.
14231 | 0 | SP_POST_MSX_OPERATION Warning: The specified %s ('%s') is not involved in a multiserver job.
14232 | 16 | Specify either a job_name, job_id, or an originating_server.
14233 | 16 | Specify a valid job_id (or 0x00 for all jobs).
14234 | 16 | The specified '%s' is invalid (valid values are returned by %s).
14235 | 16 | The specified '%s' is invalid (valid values are greater than 0 but excluding %ld).
14236 | 0 | Warning: Non-existent step referenced by %s.
14237 | 16 | When an action of 'REASSIGN' is specified, the New Login parameter must also be supplied.
14238 | 0 | %ld jobs deleted.
14239 | 0 | %ld jobs re-assigned to %s.
14240 | 0 | Job applied to %ld new servers.
14241 | 0 | Job removed from %ld servers.
14242 | 16 | Only a system administrator can re-assign ownership of a job.
14243 | 0 | Job '%s' started successfully.
14244 | 16 | Only a system administrator can reassign tasks.
14245 | 16 | Specify either the @name, @id, or @loginname of the task(s) to be deleted.
14246 | 16 | Specify either the @currentname or @id of the task to be updated.
14247 | 16 | Only a system administrator can view tasks owned by others.
14248 | 16 | This login is the owner of %ld job(s). You must delete or re-assign these jobs before the login can be dropped.
14249 | 16 | Specify either @taskname or @oldloginname when re-assigning a task.
14250 | 16 | The specified %s is too long. It must contain no more than %ld characters.
14251 | 16 | Cannot specify '%s' as the operator to be notified.
14252 | 16 | Cannot perform this action on a job you do not own.
14253 | 0 | %ld (of %ld) job(s) stopped successfully.
14254 | 0 | Job '%s' stopped successfully.
14255 | 16 | The owner ('%s') of this job is either an invalid login, or is not a valid user of database '%s'.
14256 | 16 | Cannot start job '%s' (ID %s) because it does not have any job server(s) defined.
14257 | 16 | Cannot stop job '%s' (ID %s) because it does not have any job server(s) defined.
14258 | 16 | Cannot perform this operation while SQLServerAgent is starting. Try again later.
14259 | 16 | A schedule (ID %ld, '%s') for this job with this definition already exists.
14260 | 16 | You do not have sufficient permission to run this command.
14261 | 16 | The specified %s ('%s') already exists.
14262 | 16 | The specified %s ('%s') does not exist.
14263 | 16 | Target server '%s' is already a member of group '%s'.
14264 | 16 | Target server '%s' is not a member of group '%s'.
14265 | 25 | The MSSQLServer service aborted unexpectedly.
14266 | 16 | The specified '%s' is invalid (valid values are: %s).
14267 | 16 | Cannot add a job to the '%s' job category.
14268 | 16 | There are no jobs at this server that originated from server '%s'.
14269 | 16 | Job '%s' is already targeted at server '%s'.
14270 | 16 | Job '%s' is not currently targeted at server '%s'.
14271 | 16 | A target server cannot be named '%s'.
14272 | 16 | Object-type and object-name must be supplied as a pair.
14273 | 16 | You must provide either @job_id or @job_name (and, optionally, @schedule_name), or @schedule_id.
14274 | 16 | Cannot add, update, or delete a job (or its steps or schedules) that originated from an MSX server.
14275 | 16 | The originating server must be either '(local)' or '%s'.
14276 | 16 | '%s' is a permanent %s category and cannot be deleted.
14277 | 16 | The command script does not destroy all the objects that it creates. Revise the command script.
14278 | 16 | The schedule for this job is invalid (reason: %s).
14279 | 16 | Supply either @job_name or @originating_server.
14280 | 16 | Supply either a job name (and job aspect), or one or more job filter parameters.
14281 | 0 | Warning: The @new_owner_login_name parameter is not necessary when specifying a 'DELETE' action.
14282 | 16 | Supply either a date (created or last modified) and a data comparator, or no date parameters at all.
14283 | 16 | Supply @target_server_groups or @target_servers, or both.
14284 | 16 | Cannot specify a job ID for a new job. An ID will be assigned by the procedure.
14285 | 16 | Cannot add a local job to a multi-server job category.
14286 | 16 | Cannot add a multi-server job to a local job category.
14287 | 16 | The '%s' supplied has an invalid %s.
14288 | 16 | %s cannot be less than %s.
14289 | 16 | %s cannot contain '%s' characters.
14290 | 16 | This job is currently targeted at the local server so cannot also be targeted at a remote server.
14291 | 16 | This job is currently targeted at a remote server so cannot also be targeted at the local server.
14292 | 16 | There are two or more tasks named '%s'. Specify %s instead of %s to uniquely identify the task.
14293 | 16 | There are two or more jobs named '%s'. Specify %s instead of %s to uniquely identify the job.
14294 | 16 | Supply either %s or %s to identify the job.
14295 | 16 | Frequency Type 0x2 (OnDemand) is no longer supported.
14296 | 16 | This server is already enlisted into MSX '%s'.
14297 | 16 | Cannot enlist into the local machine.
14298 | 16 | This server is not currently enlisted into an MSX.
14299 | 16 | Server '%s' is an MSX. Cannot enlist one MSX into another MSX.
14300 | 16 | Circular dependencies exist. Dependency evaluation cannot continue.
14301 | 16 | Logins other than the current user can only be seen by members of the sysadmin role.
14302 | 16 | You must upgrade your client to version 6.5 of SQL-DMO and SQL Server Enterprise Manager to connect to this server. The upgraded versions will administer both SQL Server version 6.5 and 6.0 (if sqlole65.sql is run).
14500 | 16 | Supply either a non-zero message ID, non-zero severity, or non-null performance condition.
14501 | 16 | An alert ('%s') has already been defined on this condition.
14502 | 16 | The @target_name parameter must be supplied when specifying an @enum_type of 'TARGET'.
14503 | 16 | The @target_name parameter should not be supplied when specifying an @enum_type of 'ALL' or 'ACTUAL'.
14504 | 16 | '%s' is the fail-safe operator. You must make another operator the fail-safe operator before '%s' can be dropped.
14505 | 16 | Specify a null %s when supplying a performance condition.
14506 | 16 | Cannot set alerts on message ID %ld.
14507 | 16 | A performance condition must be formatted as: 'object_name|counter_name|instance_name|comparator(> or < or =)|numeric value'.
14545 | 16 | The %s parameter is not valid for a job step of type '%s'.
14546 | 16 | The %s parameter is not supported on Windows 95/98 platforms.
14547 | 10 | Warning: This change will not be downloaded by the target server(s) until an %s for the job is posted using %s.
14548 | 10 | Target server '%s' does not have any jobs assigned to it.
14549 | 10 | (Description not requested.)
14550 | 10 | Command-Line Subsystem
14551 | 10 | Replication Snapshot Subsystem
14552 | 10 | Replication Transaction-Log Reader Subsystem
14553 | 10 | Replication Distribution Subsystem
14554 | 10 | Replication Merge Subsystem
14555 | 10 | Active Scripting Subsystem
14556 | 10 | Transact-SQL Subsystem
14557 | 10 | [Internal]
14558 | 10 | (encrypted command)
14559 | 10 | (append output file)
14560 | 10 | (include results in history)
14561 | 10 | (normal)
14562 | 10 | (quit with success)
14563 | 10 | (quit with failure)
14564 | 10 | (goto next step)
14565 | 10 | (goto step)
14566 | 10 | (idle)
14567 | 10 | (below normal)
14568 | 10 | (above normal)
14569 | 10 | (time critical)
14570 | 10 | (Job outcome)
14571 | 10 | No description available.
14572 | 10 | @freq_interval must be at least 1 for a daily job.
14573 | 10 | @freq_interval must be a valid day of the week bitmask [Sunday = 1 .. Saturday = 64] for a weekly job.
14574 | 10 | @freq_interval must be between 1 and 31 for a monthly job.
14575 | 10 | @freq_relative_interval must be one of 1st (0x1), 2nd (0x2), 3rd [0x4], 4th (0x8) or Last (0x10).
14576 | 10 | @freq_interval must be between 1 and 10 (1 = Sunday .. 7 = Saturday, 8 = Day, 9 = Weekday, 10 = Weekend-day) for a monthly-relative job.
14577 | 10 | @freq_recurrence_factor must be at least 1.
14578 | 10 | Starts whenever the CPU usage has remained below %ld percent for %ld seconds.
14579 | 10 | Automatically starts when SQLServerAgent starts.
14580 | 10 | job
14588 | 10 | ID.VersionID =
14589 | 10 | [not specified]
14590 | 16 | DTS Package '%s' already exists with a different ID in this category.
14591 | 16 | DTS Category '%s' already exists in the specified parent category.
14592 | 16 | DTS Category '%s' was found in multiple parent categories. You must uniquely specify the category to be dropped.
14593 | 16 | DTS Category '%s' contains packages and/or other categories. You must drop these first, or specify a recursive drop.
14594 | 10 | DTS Package
14595 | 16 | DTS Package '%s' exists in different categories. You must uniquely specify the package.
14596 | 16 | DTS Package '%s' exists in another category.
14597 | 16 | DTS Package ID '%s' already exists with a different name.
14598 | 16 | Cannot drop the Local, Repository, or LocalDefault DTS categories.
14599 | 10 | Name


Errors 15000 - 15999

Error | Severity | Description
15000 | 16 | Only members of the sysadmin role or the database owner can execute this stored procedure.
15001 | 16 | %s does not exist.
15002 | 16 | The procedure '%s' cannot be executed within a transaction.
15003 | 16 | Only members of the %s role can execute this stored procedure.
15004 | 16 | Name cannot be NULL.
15005 | 0 | Statistics for all tables have been updated.
15006 | 16 | '%s' is not a valid name because it contains invalid characters.
15007 | 16 | The login '%s' does not exist.
15008 | 16 | User '%s' does not exist in the current database.
15009 | 16 | The object '%s' does not exist in database '%s'.
15010 | 16 | The database '%s' does not exist. Use sp_helpdb to show available databases.
15011 | 16 | Database option '%s' does not exist.
15012 | 16 | The device '%s' does not exist. Use sp_helpdevice to show available devices.
15013 | 0 | Table '%s': No columns without statistics found.
15014 | 16 | The role '%s' does not exist in the current database.
15015 | 16 | The server '%s' does not exist. Use sp_helpserver to show available servers.
15016 | 16 | The default '%s' does not exist.
15017 | 16 | The rule '%s' does not exist.
15018 | 0 | Table '%s': Creating statistics for the following columns:
15019 | 16 | The extended stored procedure '%s' does not exist.
15020 | 0 | Statistics have been created for the %d listed columns of the above tables.
15021 | 16 | There are no remote users mapped to any local user from remote server '%s'.
15022 | 16 | The specified user name is already aliased.
15023 | 16 | User or role '%s' already exists in the current database.
15024 | 16 | The group '%s' already exists in the current database.
15025 | 16 | The login '%s' already exists.
15026 | 16 | Logical device '%s' already exists.
15027 | 16 | There are no remote users mapped to local user '%s' from remote server '%s'.
15028 | 16 | The server '%s' already exists.
15029 | 16 | The data type '%s' already exists in the current database.
15030 | 16 | The read-only bit cannot be turned off because the database is in standby mode.
15031 | 0 | 'Virtual_device' device added.
15032 | 16 | The database '%s' already exists.
15033 | 16 | '%s' is not a valid official language name.
15034 | 16 | The application role password must not be NULL.
15035 | 16 | '%s' is not a database device.
15036 | 16 | The data type '%s' does not exist.
15037 | 16 | The physical data type '%s' does not allow nulls.
15038 | 16 | User-defined data types based on timestamp are not allowed.
15039 | 16 | The language %s already exists in syslanguages.
15040 | 16 | User-defined error messages must have an ID greater than 50000.
15041 | 16 | User-defined error messages must have a severity level between 1 and 25.
15042 | 16 | Only members of the sysadmin role can add messages with severity levels greater than 18 or those which use the TRUE (for WITH_LOG) option.
15043 | 16 | You must specify 'REPLACE' to overwrite an existing message.
15044 | 16 | ''%s' is an unknown device type. Use 'disk', 'tape', or 'pipe'.
15045 | 16 | The logical name cannot be NULL.
15046 | 16 | The physical name cannot be NULL.
15047 | 16 | The only permitted options for a tape device are 'skip' and 'noskip'.
15048 | 0 | Valid values of database compatibility level are %d, %d, or %d.
15049 | 11 | Cannot unbind from '%s'. Use ALTER TABLE DROP CONSTRAINT.
15050 | 11 | Cannot bind default '%s'. The default must be created using the CREATE DEFAULT statement.
15051 | 11 | Cannot rename the table because it is published for replication.
15052 | 0 | Prior to updating sysdatabases entry for database '%s', mode = %d and status = %d (status suspect_bit = %d).
15053 | 16 | Objects exist which are not owned by the database owner.
15054 | 0 | The current compatibility level is %d.
15055 | 11 | Error. Updating sysdatabases returned @@error <> 0.
15056 | 0 | No row in sysdatabases was updated because mode and status are already correctly reset. No error and no changes made.
15057 | 16 | List of %s name contains spaces, which are not allowed.
15058 | 16 | List of %s has too few names.
15059 | 16 | List of %s has too many names.
15060 | 16 | List of %s names contains name(s) which have '%s' non-alphabetic characters.
15061 | 16 | Add device request denied. A physical device named '%s' already exists.
15062 | 16 | The guest user cannot be mapped to a login name.
15063 | 16 | The login already has an account under a different user name.
15064 | 11 | PRIMARY KEY and UNIQUE KEY constraints do not have space allocated.
15065 | 16 | All user IDs have been assigned.
15066 | 16 | A default-name mapping of a remote login from remote server '%s' already exists.
15067 | 16 | '%s' is not a local user. Remote login denied.
15068 | 16 | A remote user '%s' already exists for remote server '%s'.
15069 | 16 | One or more users are using the database. The requested operation cannot be completed.
15070 | 0 | Object '%s' was successfully marked for recompilation.
15071 | 16 | Usage: sp_addmessage <msgnum>,<severity>,<msgtext> [,<language> [,FALSE | TRUE [,REPLACE]]]
15072 | 16 | Usage: sp_addremotelogin remoteserver [, loginame [,remotename]]
15073 | 0 | For row in sysdatabases for database '%s', the status bit %d was forced off and mode was forced to 0.
15074 | 0 | Warning: You must recover this database prior to access.
15075 | 16 | The data type '%s' is reserved for future use.
15076 | 16 | Default, table, and user data types must be in the current database.
15077 | 16 | Rule, table, and user data type must be in the current database.
15078 | 16 | The table or view must be in the current database.
15079 | 10 | Queries processed: %d.
15082 | 11 | NULL is not an acceptable parameter value for this procedure. Use a percent sign instead.
15084 | 16 | The column or user data type must be in the current database.
15085 | 16 | Usage: sp_addtype name, 'data type' [,'NULL' | 'NOT NULL']
15086 | 16 | Invalid precision specified. Precision must be between 1 and 38.
15087 | 16 | Invalid scale specified. Scale must be less than precision and positive.
15088 | 16 | The physical data type is fixed length. You cannot specify the length.
15089 | 11 | Cannot change the '%s' option of a database while another user is in the database.
15090 | 16 | There is already a local server.
15091 | 16 | You must specify a length with this physical data type.
15092 | 16 | Invalid length specified. Length must be between 1 and 8000 bytes.
15093 | 16 | '%s' is not a valid date order.
15094 | 16 | '%s' is not a valid first day.
15095 | 16 | Insert into syslanguages failed. Language not added.
15096 | 16 | Only members of the sysadmin role or '%s' can change the default language for '%s'.
15100 | 16 | Usage: sp_bindefault defaultname, objectname [, 'futureonly']
15101 | 16 | Cannot bind a default to a column of data type timestamp.
15102 | 16 | Cannot bind a default to an identity column.
15103 | 16 | Cannot bind a default to a column created with or altered to have a default value.
15104 | 16 | You do not own a table named '%s' that has a column named '%s'.
15105 | 16 | You do not own a data type with that name.
15106 | 16 | Usage: sp_bindrule rulename, objectname [, 'futureonly']
15107 | 16 | Cannot bind a rule to a column of data type text, ntext, image, or timestamp.
15108 | 16 | Only members of the sysadmin role can change the owner of a database.
15109 | 16 | Cannot change the owner of the master database.
15110 | 16 | The proposed new database owner is already a user in the database.
15111 | 16 | The proposed new database owner is already aliased in the database.
15123 | 16 | The configuration option '%s' does not exist, or it may be an advanced option.
15124 | 16 | The configuration option '%s' is not unique.
15125 | 16 | Only members of the sysadmin role can change configuration parameters.
15127 | 16 | Cannot set the default language to a language ID not defined in syslanguages.
15129 | 16 | '%d' is not a valid value for configuration option '%s'.
15131 | 16 | Usage: sp_dbremove <dbname> [,dropdev]
15132 | 16 | Cannot change default database belonging to someone else.
15134 | 16 | No alias exists for the specified user.
15139 | 16 | The device is a RAM disk and cannot be used as a default device.
15140 | 16 | Usage: sp_diskdefault logicalname {defaulton | defaultoff}
15142 | 16 | Cannot drop the role '%s'.
15143 | 16 | '%s' is not a valid option for the @updateusage parameter. Enter either 'true' or 'false'.
15144 | 16 | The role has members. It must be empty before it can be dropped.
15174 | 16 | Login '%s' owns one or more database(s). Change the owner of the following database(s) before dropping login:
15175 | 16 | Login '%s' is aliased or mapped to a user in one or more database(s). Drop the user or alias before dropping the login.
15176 | 16 | The only valid @parameter value is 'WITH_LOG'.
15177 | 16 | Usage: sp_dropmessage <msg number> [,<language> | 'ALL']
15178 | 16 | Cannot drop a message with an ID less than 50000.
15179 | 16 | Message number %u does not exist.
15180 | 16 | Cannot drop. The data type is being used.
15181 | 16 | Cannot drop the database owner.
15182 | 16 | Cannot drop the guest user from master or tempdb.
15183 | 16 | The user owns objects in the database and cannot be dropped.
15184 | 16 | The user owns data types in the database and cannot be dropped.
15185 | 16 | There is no remote user '%s' mapped to local user '%s' from the remote server '%s'.
15190 | 16 | There are still remote logins for the server '%s'.
15191 | 16 | Usage: sp_dropserver server [, droplogins]
15193 | 16 | This procedure can only be used on system tables.
15194 | 16 | Cannot re-create index on this table.
15197 | 16 | There is no text for object '%s'.
15198 | 16 | The name supplied (%s) is not a user, role, or aliased login.
15200 | 16 | There are no remote servers defined.
15201 | 16 | There are no remote logins for the remote server '%s'.
15202 | 16 | There are no remote logins defined.
15203 | 16 | There are no remote logins for '%s'.
15204 | 16 | There are no remote logins for '%s' on remote server '%s'.
15205 | 16 | There are no servers defined.
15206 | 16 | Invalid Remote Server Option: '%s'.
15210 | 16 | Only members of the sysadmin role can use the loginame option. The password was not changed.
15211 | 16 | Old (current) password incorrect for user. The password was not changed.
15216 | 16 | '%s' is not a valid option for the @delfile parameter.
15218 | 16 | Object '%s' is not a table.
15219 | 16 | You do not own table '%s'. Only members of the sysadmin role or the table owner may perform this action.
15220 | 16 | Usage: sp_remoteoption [remoteserver, loginame, remotename, optname, {true | false}]
15221 | 16 | Remote login option does not exist or cannot be set by user. Run sp_remoteoption with no parameters to see options.
15222 | 16 | Remote login option '%s' is not unique.
15223 | 11 | Error: The input parameter '%s' is not allowed to be null.
15224 | 11 | Error: The value for the @newname parameter contains invalid characters or violates a basic restriction (%s).
15225 | 11 | No item by the name of '%s' could be found in the current database '%s', given that @itemtype was input as '%s'.
15226 | 16 | Only members of the sysadmin role can change the name of a database.
15227 | 16 | The database '%s' cannot be renamed.
15228 | 16 | A member of the sysadmin role must set database '%s' to single user mode with sp_dboption before it can be renamed.
15229 | 16 | Usage: sp_serveroption [server [,optname [,'true' | 'false']]]
15230 | 16 | Server option '%s' does not exist or cannot be set by user. Run sp_serveroption with no parameters to see options.
15231 | 16 | Server option '%s' is not unique.
15232 | 16 | Only members of the sysadmin role may set server options.
15234 | 16 | Object is stored in sysprocedures and has no space allocated directly.
15235 | 16 | Views do not have space allocated.
15236 | 16 | Column '%s' has no default.
15237 | 16 | User data type '%s' has no default.
15238 | 16 | Column '%s' has no rule.
15239 | 16 | User data type '%s' has no rule.
15241 | 16 | Usage: sp_dboption [dbname [,optname [,'true' | 'false']]]
15242 | 16 | Database option '%s' is not unique.
15243 | 16 | The option '%s' cannot be changed for the master database.
15244 | 16 | Only members of the sysadmin role or the database owner may set database options.
15245 | 16 | DBCC DBCONTROL error. Database was not placed offline.
15248 | 11 | Error: The parameter @oldname is either ambiguous or the claimed @itemtype (%s) was wrong.
15249 | 11 | Error: Explicit @itemtype '%s' is unrecognized (%d).
15250 | 16 | The database name component of the object qualifier must be the name of the current database.
15251 | 16 | Invalid '%s' specified. It must be %s.
15252 | 16 | The primary or foreign key table name must be given.
15253 | 11 | Syntax error parsing SQL identifier '%s'.
15254 | 16 | Users other than the database owner or guest exist in the database. Drop them before removing the database.
15255 | 11 | '%s' is not a valid value for @autofix. The only valid value is 'auto'.
15256 | 16 | Usage: sp_certify_removable <dbname> [,'auto']
15257 | 16 | The database that you are attempting to certify cannot be in use at the same time.
15258 | 16 | The database must be owned by a member of the sysadmin role before it can be removed.
15261 | 16 | Usage: sp_create_removable <dbname>,<syslogical>,<sysphysical>,<syssize>,<loglogical>,<logphysical>,<logsize>,<datalogical1>,<dataphysical1>,<datasize1> [,<datalogical2>,<dataphysical2>,<datasize2>...<datalogical16>,<dataphysical16>,<datasize16>]
15262 | 0 | Invalid file size entered. All files must be at least 1 MB.
15264 | 16 | Could not create the '%s' portion of the database.
15266 | 16 | Cannot make '%s' database removable.
15269 | 16 | Logical data device '%s' not created.
15270 | 16 | You cannot specify a length for user data types based on sysname.
15271 | 16 | Invalid @with_log parameter value. Valid values are 'true' or 'false'.
15275 | 16 | FOREIGN KEY constraints do not have space allocated.
15277 | 16 | The only valid @parameter_value values are 'true' or 'false'.
15278 | 16 | Login '%s' is already mapped to user '%s' in database '%s'.
15279 | 16 | You must add the us_english version of this message before you can add the '%s' version.
15280 | 16 | All localized versions of this message must be dropped before the us_english version can be dropped.
15283 | 16 | The name '%s' contains too many characters.
15284 | 16 | The user has granted or revoked privileges to the following in the database and cannot be dropped.
15285 | 16 | The special word '%s' cannot be used for a logical device name.
15286 | 16 | Aborting this procedure. The @action '%s' is unrecognized. Try 'REPORT', 'UPDATE_ONE', or 'AUTO_FIX'.
15287 | 16 | Aborting this procedure. '%s' is a forbidden value for the login name parameter in this procedure.
15288 | 16 | Aborting this procedure. Only %s has the permissions to run the action '%s'.
15289 | 16 | Aborting this procedure. Cannot have an open transaction when this is run.
15290 | 16 | Aborting this procedure. The Action '%s' is incompatible with the other parameter values ('%s', '%s').
15291 | 16 | Aborting this procedure. The %s name '%s' is absent or invalid.
15292 | 0 | The row for user '%s' will be fixed by updating its login link to a login already in existence.
15293 | 0 | Barring a conflict, the row for user '%s' will be fixed by updating its link to a new login. Consider changing the new password from null.
15294 | 0 | The number of orphaned users fixed by adding new logins and then updating users was %d.
15295 | 0 | The number of orphaned users fixed by updating users was %d.
15298 | 0 | New login created.
15300 | 11 | No recognized letter is contained in the parameter value for General Permission Type (%s). Valid letters are in this set: %s .
15302 | 11 | Database_Name should not be used to qualify owner.object for the parameter into this procedure.
15303 | 11 | The "user options" config value (%d) was rejected because it would set incompatible options.
15304 | 16 | The severity level of the '%s' version of this message must be the same as the severity level (%ld) of the us_english version.
15305 | 16 | The @TriggerType parameter value must be 'insert', 'update', or 'delete'.
15306 | 16 | Cannot change the compatibility level of replicated or distributed databases.
15307 | 16 | Could not change the merge publish option because the server is not set up for replication.
15308 | 16 | You must set database '%s' to single user mode with sp_dboption before fixing indexes on system tables.
15311 | 16 | The file named '%s' does not exist.
15312 | 16 | The file named '%s' is a primary file and cannot be removed.
15318 | 0 | All fragments for database '%s' on device '%s' are now dedicated for log usage only.
15319 | 17 | Error: DBCC DBREPAIR REMAP failed for database '%s' (device '%s').
15321 | 16 | There was some problem removing '%s' from sysaltfiles.
15322 | 0 | File '%s' was removed from tempdb, and will take effect upon server restart.
15323 | 16 | The selected index does not exist on table '%s'.
15324 | 16 | The option %s cannot be changed for the '%s' database.
15325 | 16 | The current database does not contain a %s named '%ls'.
15326 | 0 | No extended stored procedures exist.
15327 | 0 | The database is now offline.
15328 | 0 | The database is already offline.
15330 | 11 | There are no matching rows on which to report.
15331 | 11 | The user '%s' cannot take the action auto_fix because another user has SUID = %d.
15333 | 11 | Error: the qualified @oldname references a database (%s) other than the current database.
15334 | 11 | Error: Only members of the sysadmin role or the database owner can rename items they do not own.
15335 | 11 | Error: The @newname value '%s' is already in use as a %s name and would cause a duplicate that is not permitted.
15337 | 0 | Caution: sysdepends shows that other objects (views, procedures and so on) are referencing this object by its old name. These objects will become invalid, and should be dropped and re-created promptly.
15338 | 0 | The %s was renamed to '%s'.
15339 | 0 | Creating '%s'.
15340 | 0 | Alias user added.
15341 | 0 | Granted database access to '%s'.
15342 | 0 | Replacing message.
15343 | 0 | New message added.
15354 | 0 | Usage: sp_detachdb <dbname>, [TRUE|FALSE]
15358 | 0 | User-defined filegroups should be made read-only.
15363 | 16 | The role '%s' already exists in the current database.
15379 | 11 | The server option value '%s' supplied is unrecognized.
15386 | 11 | For input parameter @OptionName you entered the value '%s'. The number of valid option names matching this value is %d (not equal to 1). Aborting this procedure.
15387 | 11 | If the qualified object name specifies a database, that database must be the current database.
15388 | 11 | There are no objects matching the input name '%s' in the current database.
15389 | 11 | The value '%s' for the @OptionValue parameter is unrecognized.
15390 | 11 | Only members of the sysadmin role or the database owner can modify '%s' settings for objects owned by other users.
15391 | 0 | All %d matched objects now have their '%s' setting as '%s'. Updates were required for %d objects.
15392 | 11 | Only members of the sysadmin role can modify the settings for option %s.
15393 | 16 | Commit service transaction (XACT) ID does not exist.
15395 | 11 | The qualified old name could not be found for item type '%s'.
15396 | 11 | Cannot change option %s for an object without first performing a DROP statement then a CREATE statement.
15397 | 11 | Could not change option %s. Not more than one object can be changed per execution for this option. %d objects match the parameter values in the current attempt.
15398 | 11 | Only objects in the master database and owned by a member of the sysadmin role can have the setting changed for option %s.
15399 | 11 | Could not change option %s. This type of change is restricted to objects that have no parameters or columns.
15400 | 11 | Could not change an object of type %s. The setting of option %s cannot be changed for objects of this type. Bypassing object '%s'. Other valid, matching objects will be processed now.
15401 | 11 | Windows NT user or group '%s' not found. Check the name again.
15402 | 11 | '%s' is not a fixed server role.
15403 | 11 | Insufficient permission to add a member to the fixed role '%s'.
15405 | 11 | Cannot use the reserved user or role name '%s'.
15407 | 11 | '%s' is not a valid Windows NT name. Give the complete name: <domain\username>.
15409 | 11 | '%s' is not a role.
15410 | 11 | User or role '%s' does not exist in this database.
15412 | 11 | '%s' is not a known fixed role.
15413 | 11 | Cannot make a role a member of itself.
15415 | 11 | User is a member of more than one group. sp_changegroup is set up for backward compatibility and expects membership in one group at most.
15416 | 16 | Usage: sp_dbcmptlevel [dbname [, compatibilitylevel]]
15417 | 16 | Insufficient permission to change the compatibility level of the '%s' database.
15418 | 16 | Only members of the sysadmin role or the database owner may set the database compatibility level.
15419 | 16 | Supplied parameter @sid should be binary(16).
15420 | 16 | The group '%s' does not exist in this database.
15421 | 16 | The user owns role(s) in the database and cannot be dropped.
15422 | 16 | Application roles can only be activated at the ad hoc level.
15423 | 0 | The password for application role '%s' has been changed.
15424 | 0 | New role added.
15425 | 0 | New application role added.
15426 | 16 | You must specify a provider name with this set of properties.
15427 | 16 | You must specify a provider name for unknown product '%ls'.
15428 | 16 | You cannot specify a provider or any properties for product '%ls'.
15429 | 16 | '%ls' is an invalid product name.
15430 | 19 | Limit exceeded for number of servers.
15431 | 16 | You must specify the @rolename parameter.
15432 | 16 | Stored procedure '%s' can only be executed at the ad hoc level.
15433 | 16 | Supplied parameter @sid is in use.
15434 | 16 | Could not drop login '%s' as the user is currently logged in.
15435 | 0 | Database successfully published.
15436 | 0 | Database successfully enabled for subscriptions.
15437 | 0 | Database successfully published using merge replication.
15438 | 0 | Database is already online.
15439 | 0 | Database is now online.
15440 | 0 | Database is no longer published.
15441 | 0 | Database is no longer enabled for subscriptions.
15442 | 0 | Database is no longer enabled for merge publications.
15443 | 0 | Checkpointing database that was changed.
15444 | 0 | 'Disk' device added.
15445 | 0 | 'Diskette' device added.
15446 | 0 | 'Tape' device added.
15447 | 0 | 'Pipe' device added.
15448 | 0 | New remote login created.
15449 | 0 | Type added.
15450 | 0 | New language inserted.
15451 | 0 | %s messages altered.
15452 | 0 | No alternate languages are available.
15453 | 0 | us_english is always available, even though it is not in syslanguages.
15454 | 0 | Language deleted.
15456 | 0 | Valid configuration options are:
15457 | 0 | Configuration option changed. Run the RECONFIGURE statement to install.
15458 | 0 | Database removed.
15459 | 0 | In the current database, the specified object references the following:
15460 | 0 | In the current database, the specified object is referenced by the following:
15461 | 0 | Object does not reference any object, and no objects reference it.
15462 | 0 | File '%s' closed.
15463 | 0 | Device dropped.
15466 | 0 | Message dropped.
15467 | 0 | Type has been dropped.
15468 | 0 | Remote login dropped.
15469 | 0 | No constraints have been defined for this object.
15470 | 0 | No foreign keys reference this table.
15471 | 0 | The object comments have been encrypted.
15472 | 0 | The object does not have any indexes.
15473 | 0 | Settable remote login options.
15474 | 11 | Only members of the sysadmin role can set remote login options.
15475 | 0 | The database is renamed and in single user mode.
15476 | 0 | A member of the sysadmin role must reset the database to multiuser mode with sp_dboption.
15477 | 0 | Caution: Changing any part of an object name could break scripts and stored procedures.
15478 | 0 | Password changed.
15479 | 0 | Login dropped.
15480 | 0 | Could not grant login access to '%s'.
15481 | 0 | Granted login access to '%s'.
15482 | 0 | Could not deny login access to '%s'.
15483 | 0 | Denied login access to '%s'.
15484 | 0 | Could not revoke login access from '%s'.
15485 | 0 | Revoked login access from '%s'.
15486 | 0 | Default database changed.
15487 | 0 | %s's default language is changed to %s.
15488 | 0 | '%s' added to role '%s'.
15489 | 0 | '%s' dropped from role '%s'.
15490 | 0 | The dependent aliases were also dropped.
15491 | 0 | User has been dropped from current database.
15492 | 0 | Alias user dropped.
15493 | 0 | Role dropped.
15494 | 0 | The application role '%s' is now active.
15495 | 0 | Application role dropped.
15496 | 0 | Group changed.
15497 | 0 | Could not add login using sp_addlogin (user = %s). Aborting this procedure.
15498 | 17 | Inside txn_1a_, update failed. Will roll back (1a1).
15499 | 0 | The dependent aliases were mapped to the new database owner.
15500 | 0 | The dependent aliases were dropped.
15501 | 0 | Database owner changed.
15502 | 0 | Setting database owner to SA.
15503 | 0 | Giving ownership of all objects to the database owner.
15504 | 0 | Deleting users except guest and the database owner from sysusers.
15505 | 0 | The object owner has been changed.
15506 | 0 | Server added.
15507 | 0 | Remote logins for remote server '%s' have been dropped.
15508 | 0 | Server dropped.
15509 | 0 | Settable server options.
15510 | 0 | Server network name set.
15511 | 0 | Default bound to column.
15512 | 0 | Default bound to data type.
15513 | 0 | The new default has been bound to columns(s) of the specified user data type.
15514 | 0 | Rule bound to table column.
15515 | 0 | Rule bound to data type.
15516 | 0 | The new rule has been bound to column(s) of the specified user data type.
15517 | 0 | Option %s turned on.
15518 | 0 | Option %s turned off.
15519 | 0 | Default unbound from table column.
15520 | 0 | Default unbound from data type.
15521 | 0 | Columns of the specified user data type had their defaults unbound.
15522 | 0 | Rule unbound from table column.
15523 | 0 | Rule unbound from data type.
15524 | 0 | Columns of the specified user data type had their rules unbound.
15525 | 0 | sp_checknames is used to search for non 7-bit ASCII characters.
15526 | 0 | in several important columns of system tables. The following
15527 | 0 | columns are searched:
15528 | 0 | In master:
15536 | 0 | In all databases:
15543 | 0 | Looking for non 7-bit ASCII characters in the system tables of database '%s'.
15544 | 0 | Table.column '%s'
15545 | 0 | The following database names contain non 7-bit ASCII characters.
15546 | 0 | If you wish to change these names, use '%s'.
15547 | 0 | The following logins have default database names that contain
15548 | 0 | non 7-bit ASCII characters. If you wish to change these names use
15549 | 0 | sp_defaultdb.
15550 | 0 | The following servers have 'initialization file' names that contain
15551 | 0 | non 7-bit ASCII characters. If you wish to change these names,
15552 | 0 | use UPDATE.
15553 | 0 | Database '%s' has no object, user, and so on
15554 | 0 | names that contain non 7-bit ASCII characters.
15555 | 0 | The database name provided '%s' must be the current database when executing this stored procedure.
15564 | 0 | The following device names contain non 7-bit ASCII characters.
15565 | 0 | The following login names contain non 7-bit ASCII characters.
15566 | 0 | The following remote login names contain non 7-bit ASCII characters.
15567 | 0 | The following server names contain non 7-bit ASCII characters.
15568 | 0 | The following column and parameter names contain non 7-bit ASCII characters.
15569 | 0 | The following index names contain non 7-bit ASCII characters.
15570 | 0 | The following object names contain non 7-bit ASCII characters.
15571 | 0 | The following segment names contain non 7-bit ASCII characters.
15572 | 0 | The following data type names contain non 7-bit ASCII characters.
15573 | 0 | The following user or role names contain non 7-bit ASCII characters.
15600 | 15 | An invalid parameter or option was specified for procedure '%s'.
15601 | 16 | Fulltext Search is not enabled for the current database. Use sp_fulltext_database to enable full-text search.
15602 | 16 | Full-Text catalog '%ls' does not exist.
15603 | 16 | A full-text catalog named '%ls' already exists in this database.
15604 | 16 | Cannot drop full-text catalog '%ls' because it contains a full-text index.
15605 | 16 | A full-text index for table '%ls' has already been created.
15606 | 16 | You must first create a full-text index on table '%ls'.
15607 | 16 | '%ls' is not a valid index to enforce a full-text search key. You must specify a unique, non-nullable, single-column index.
15608 | 16 | Full-text search has already been activated for table '%ls'.
15609 | 16 | Cannot activate full-text search for table '%ls' because no columns have been enabled for full-text search.
15610 | 16 | You must deactivate full-text search on table '%ls' before adding columns to or removing columns from the full-text index.
15611 | 16 | Column '%ls' of table '%ls' cannot be used for full-text search because it is not a character-based column.
15612 | 16 | DBCC DBCONTROL error. Database was not made read-only.
15613 | 0 | The database is now read-only.
15614 | 0 | The database already is read-only.
15615 | 16 | DBCC DBCONTROL error. Database was not made single user.
15616 | 0 | The database is now single user.
15617 | 0 | The database already is single user.
15618 | 0 | The database is now read/write.
15619 | 0 | The database already is read/write.
15620 | 0 | The database is now multiuser.
15621 | 0 | The database already is multiuser.


Errors 16000 - 16999

Error | Severity | Description
16801 | 11 | sp_dropwebtask requires at least one defined parameter @outputfile or @procname.
16802 | 11 | sp_dropwebtask cannot find the specified task.
16803 | 11 | sp_runwebtask requires at least one defined parameter @outputfile or @procname.
16804 | 11 | SQL Web Assistant: Could not establish a local connection to SQL Server.
16805 | 11 | SQL Web Assistant: Could not execute the SQL statement.
16806 | 11 | SQL Web Assistant: Could not bind the parameter to the SQL statement.
16807 | 11 | SQL Web Assistant: Could not obtain a bind token.
16808 | 11 | SQL Web Assistant: Could not find the existing trigger. This could be due to encryption.
16809 | 11 | SQL Web Assistant failed on the call to SQLGetData.
16810 | 11 | SQL Web Assistant failed on the call to SQLFetch.
16811 | 11 | SQL Web Assistant failed to bind a results column.
16812 | 11 | SQL Web Assistant: The @query parameter must be specified.
16813 | 11 | SQL Web Assistant: Parameters can be passed either by name or position.
16814 | 11 | SQL Web Assistant: Invalid parameter.
16815 | 11 | SQL Web Assistant: @procname is not valid.
16816 | 11 | SQL Web Assistant: @outputfile is not valid.
16817 | 11 | SQL Web Assistant: Could not read the given file.
16820 | 11 | SQL Web Assistant failed because the state of the Web task in msdb..MSwebtasks is invalid.
16821 | 11 | SQL Web Assistant: Could not open the output file.
16822 | 11 | SQL Web Assistant: Could not open the template file.
16823 | 11 | SQL Web Assistant: Could not allocate enough memory to satisfy this request.
16824 | 11 | SQL Web Assistant: The template file specified in the Web task has a bad size.
16825 | 11 | SQL Web Assistant: Could not read the template file.
16826 | 11 | SQL Web Assistant: Could not find the specified marker for data insertion in the template file.
16827 | 11 | SQL Web Assistant: Could not write to the output file.
16828 | 11 | SQL Web Assistant: @tabborder must be tinyint.
16829 | 11 | SQL Web Assistant: @singlerow must be 0 or 1. Cannot specify this parameter with @nrowsperpage.
16830 | 11 | SQL Web Assistant: The @blobfmt parameter specification is invalid.
16831 | 11 | SQL Web Assistant: The output file name is mandatory for every column specified in the @blobfmt parameter.
16832 | 11 | SQL Web Assistant: Procedure called with too many parameters.
16833 | 11 | SQL Web Assistant: @nrowsperpage must be a positive number and it cannot be used with @singlerow.
16834 | 11 | SQL Web Assistant: Read/write operation on text, ntext, or image column failed.
16838 | 11 | SQL Web Assistant: Could not find the table in the HTML file.
16839 | 11 | SQL Web Assistant: Could not find the matching end table tag in the HTML file.
16841 | 11 | SQL Web Assistant: The @datachg parameter cannot be specified with the given @whentype value.
16842 | 11 | SQL Web Assistant: Could not find and drop the necessary trigger for updating the Web page.
16843 | 11 | SQL Web Assistant: Could not add the necessary trigger for the @datachg parameter. There could be an existing trigger on the table with missing or encrypted text.
16844 | 11 | SQL Web Assistant: Incorrect syntax for the @datachg parameter.
16845 | 11 | SQL Web Assistant: @datachg must be specified for the given @whentype option.
16846 | 11 | SQL Web Assistant: @unittype and/or @numunits must be specified for the given @whentype option.
16847 | 11 | SQL Web Assistant: @fixedfont must be 0 or 1.
16848 | 11 | SQL Web Assistant: @bold must be 0 or 1.
16849 | 11 | SQL Web Assistant: @italic must be 0 or 1.
16850 | 11 | SQL Web Assistant: @colheaders must be 0 or 1.
16851 | 11 | SQL Web Assistant: @lastupdated must be 0 or 1.
16852 | 11 | SQL Web Assistant: @HTMLheader must be in the range 1 to 6.
16853 | 11 | SQL Web Assistant: @username is not valid.
16854 | 11 | SQL Web Assistant: @dbname is not valid.
16855 | 11 | SQL Web Assistant: @whentype must be in the range 1 to 9.
16856 | 11 | SQL Web Assistant: @unittype must be in the range 1 to 4.
16857 | 11 | SQL Web Assistant: @targetdate is invalid. It must be a valid date after 1900-01-01.
16858 | 11 | SQL Web Assistant: The @targettime parameter must be between 0 and 240000.
16859 | 11 | SQL Web Assistant: @dayflags must be 1, 2, 4, 8, 16, 32, or 64.
16860 | 11 | SQL Web Assistant: @numunits must be greater than 0.
16861 | 11 | SQL Web Assistant: @targetdate must be specified for the given @whentype option.
16862 | 11 | SQL Web Assistant: @dayflags must be specified for the given @whentype option.
16863 | 11 | SQL Web Assistant: URL specification is invalid.
16864 | 11 | SQL Web Assistant: @blobfmt is invalid. The file must include the full path to the output_file location.
16865 | 11 | SQL Web Assistant: URL hyperlink text column must not be of the image data type.
16866 | 11 | SQL Web Assistant: Could not obtain the number of columns in @query.
16867 | 11 | SQL Web Assistant: URL hyperlink text column is missing in @query.
16868 | 11 | SQL Web Assistant failed on the call to SQLColAttribute.
16869 | 11 | SQL Web Assistant: Columns of data type image cannot have a template.
16870 | 11 | SQL Web Assistant: Internal error. Could not read @ parameters.
16871 | 11 | SQL Web Assistant: Invalid @charset. Execute sp_enumcodepages for a list of character sets.
16873 | 11 | SQL Web Assistant: Invalid @codepage. Execute sp_enumcodepages for a list of code pages.
16874 | 11 | SQL Web Assistant: Internal error. Cannot translate to the specified code page.
16875 | 11 | SQL Web Assistant: Translation to the desired code page is unavailable on this system.
16876 | 11 | SQL Web Assistant: Internal error. Could not obtain COM interface ID.
16877 | 11 | SQL Web Assistant: Internal error. Could not obtain COM language ID.
16878 | 11 | SQL Web Assistant: Internal error. Could not initialize COM library.
16879 | 11 | SQL Web Assistant: Internal error. Could not translate from Unicode to the specified code page.
16880 | 11 | SQL Web Assistant: Internal error. Could not create translation object. Make sure that the file MLang.dll is in your system directory.
16881 | 16 | SQL Web Assistant: This version is not supported on Win32s of Windows 3.1.
16882 | 16 | SQL Web Assistant: Web task not found. Verify the name of the task for possible errors.
16883 | 16 | SQL Web Assistant: Could not list Web task parameters. xp_readwebtask requires @procname.
16884 | 16 | SQL Web Assistant: Procedure name is required to convert Web tasks.
16885 | 16 | SQL Web Assistant: Could not upgrade the Web task to 7.0. The Web task will remain in 6.5 format and will need to be re-created.
16886 | 16 | SQL Web Assistant: Could not update Web tasks system table. The Web task remains in 6.5 format.
16887 | 16 | SQL Web Assistant: @procname parameter is missing. The parameter is required to upgrade a Web task to 7.0.
16888 | 16 | SQL Web Assistant: Source code page is not supported on the system. Ensure @charset and @codepage language files are installed on your system.
16889 | 16 | SQL Web Assistant: Could not send Web task row to the client.
16890 | 16 | SQL Web Assistant: ODS error occurred. Could not send Web task parameters.
16901 | 16 | %hs: This feature has not been implemented yet.
16902 | 16 | %hs: The value of parameter %hs is invalid.
16903 | 16 | %hs procedure called with incorrect number of parameters.
16904 | 16 | sp_cursor: optype: You can only specify ABSOLUTE in conjunction with DELETE or UPDATE.
16905 | 16 | The cursor is already open.
16907 | 16 | %hs is not allowed in cursor statements.
16909 | 16 | %hs: The cursor identifier value provided (%x) is not valid.
16911 | 16 | %hs: The fetch type %hs cannot be used with forward only cursors.
16914 | 16 | %hs procedure called with too many parameters.
16915 | 16 | A cursor with the name '%.*ls' already exists.
16916 | 16 | A cursor with the name '%.*ls' does not exist.
16917 | 16 | Cursor is not open.
16922 | 16 | Cursor Fetch: Implicit conversion from data type %s to %s is not allowed.
16924 | 16 | Cursorfetch: The number of variables declared in the INTO list must match that of selected columns.
16925 | 16 | The fetch type %hs cannot be used with dynamic cursors.
16926 | 16 | sp_cursoroption: The column ID (%d) does not correspond to a text, ntext, or image column.
16927 | 16 | sp_cursoroption: The cursor already has a name.
16929 | 16 | The cursor is READ ONLY.
16930 | 16 | The requested row is not in the fetch buffer.
16931 | 16 | There are no rows in the current fetch buffer.
16932 | 16 | The cursor has a FOR UPDATE list and the requested column to be updated is not in this list.
16933 | 16 | The cursor does not include the table being modified.
16934 | 16 | Optimistic concurrency check failed. The row was modified outside of this cursor.
16935 | 16 | No parameter values were specified for the sp_cursor-%hs statement.
16936 | 16 | sp_cursor: One or more values parameters were invalid.
16937 | 16 | A server cursor is not allowed on a stored procedure with more than one SELECT statement. Use a default result set or client cursor.
16938 | 16 | sp_cursoropen/sp_cursorprepare: The statement parameter can only be a single select or a single stored procedure.
16940 | 16 | Cannot specify UPDLOCK or TABLOCKX with READ ONLY or INSENSITIVE cursors.
16941 | 16 | Cursor updates are not allowed on tables opened with the NOLOCK option.
16942 | 16 | Could not generate asynchronous keyset. The cursor has been deallocated.
16943 | 16 | Could not complete cursor operation because the table schema changed after the cursor was declared.
16944 | 16 | Cannot specify UPDLOCK or TABLOCKX on a read-only table in a cursor.
16945 | 16 | The cursor was not declared.
16946 | 16 | Could not open the cursor because one or more of its tables have gone out of scope.
16947 | 10 | No rows were updated or deleted.
16948 | 16 | The variable '%.*ls' is not a cursor variable, but it is used in a place where a cursor variable is expected.
16949 | 16 | The variable '%.*ls' is a cursor variable, but it is used in a place where a cursor variable is not valid.
16950 | 10 | The variable '%.*ls' does not currently have a cursor allocated to it.
16951 | 16 | The variable '%.*ls' cannot be used as a parameter because a CURSOR OUTPUT parameter must not have a cursor allocated to it before execution of the procedure.
16952 | 16 | A cursor variable cannot be used as a parameter to a remote procedure call.
16953 | 10 | Updatable keyset cursors on remote tables require a transaction with the REPEATABLE_READ or SERIALIZABLE isolation level.
16954 | 16 | Executing SQL directly; no cursor.
16955 | 16 | Could not create an acceptable cursor.
16956 | 10 | Cursor created was not of the requested type.
16997 | 16 | Could not create cursor because worktable rows exceed maximum rowsize (8060). Use fewer columns in the declaration.
16998 | 20 | Internal Cursor Error: A cursor work table operation failed.
16999 | 20 | Internal Cursor Error: The cursor is in an invalid state.


Errors 17000 - 17999

Error | Severity | Description
17000 | 10 | Usage: sp_autostats <table_name> [, {ON|OFF} [, <index_name>] ]
17026 | 10 | Using '%1' version '%2'.
17050 | 16 | initerrlog: Could not open error log file '%1'. Operating system error = %2.
17052 | 10 | %1
17053 | 16 | %1: Operating system error %2 encountered.
17054 | 16 | LogEvent: Failed to report the current event. Operating system error = %1.
17055 | 16 | %1 :%n%2
17059 | 16 | Operating system error %1!d!.
17065 | 16 | SQL Server Assertion: File: <%1>, line = %2!d! %nFailed Assertion = '%3' %4.
17066 | 16 | SQL Server Assertion: File: <%1>, line=%2!d! %nFailed Assertion = '%3'.
17067 | 16 | SQL Server Assertion: File: <%1>, line = %2!d! %n%3.
17068 | 10 | PrintStack Request
17112 | 16 | Invalid command option %1!c!.
17113 | 16 | initconfig: Error %2 opening '%1' for configuration information.
17114 | 16 | initconfig: Error %2 reading configuration information from '%1'.
17117 | 10 | initconfig: Number of user connections reduced to %1!ld!.
17118 | 10 | upinit: Warning: Could not raise priority of %1 thread.
17119 | 10 | initconfig: Number of server processes reduced to %1!ld!.
17120 | 16 | SQL Server could not spawn %1 process.
17121 | 16 | SQL Server could not spawn first connection handler.
17122 | 16 | initdata: Warning: Could not set working set size to %1!d! KB.
17123 | 16 | initdata: Could not create thread local storage.
17127 | 16 | initdata: No memory for kernel buffer hash table.
17128 | 16 | initdata: No memory for kernel buffers.
17130 | 16 | initdata: No memory for kernel locks.
17131 | 16 | initdata: Not enough memory for descriptor hash tables.
17132 | 16 | initdata: Not enough memory for descriptors.
17134 | 16 | initmaster: Could not allocate process status structure (PSS).
17138 | 16 | Could not allocate enough memory for data initialization.
17140 | 16 | Could not dispatch SQL Server by Service Control Manager. Operating system error = %1.
17141 | 16 | Could not register Service Control Handler. Operating system error = %1.
17142 | 16 | SQL Server has been paused. No new connections will be allowed.
17143 | 16 | %1: Could not set Service Control Status. Operating system error = %2.
17144 | 10 | SQL Server is disallowing new connections due to 'pause' request from Service Control Manager.
17145 | 10 | Service Control Handler received an invalid control code = %1!d!.
17146 | 10 | SQL Server is allowing new connections due to 'continue' request from Service Control Manager.
17147 | 10 | SQL Server terminating because of system shutdown.
17148 | 10 | SQL Server is terminating due to 'stop' request from Service Control Manager.
17150 | 16 | %1: Error in spawning console process.
17151 | 10 | Maximum number of pages in batch I/O is limited to %1!ld!.
17154 | 16 | initdata: Not enough memory for procedure cache/hash table.
17156 | 16 | initeventlog: Could not initiate the EventLog Service for the key '%1'.
17157 | 16 | %1: Could not initialize Communication Layer.
17158 | 16 | Could not use OPENDSNT.DLL version '%1'. OPENDSNT.DLL version '%2' was expected.
17160 | 16 | Could not use SQLEVN70.DLL version '%1'. SQLEVN70.DLL version '%2' was expected.
17161 | 10 | Master device sector size is %1!d!. SQL Server cannot use the NO_BUFFERING option during I/O.
17162 | 10 | SQL Server is starting at priority class '%1'(%2!d! %3 detected).
17204 | 16 | %1: Could not open device %2 for virtual device number (VDN) %3!d!.
17207 | 16 | %1: Operating system error %3 during the creation/opening of physical device %2.
17208 | 16 | %1: File '%2' has an incorrect size (%3!d! MB, should be %4!d! MB).
17218 | 16 | %1: Operating system error %2 on device '%3' (virtual page %4).
17249 | 16 | %1: Negative outstanding I/O count in process ID = %2!d!.
17252 | 16 | %1: Actual bytes transferred (%2!d!) does not match requested amount (%3!d!) on device '%4' (virtual page %5).
17253 | 10 | The sector size for device %1 is %2!d!. SQL Server cannot use the NO_BUFFERING option during I/O on this device.
17254 | 10 | Warning: Cannot use NO_BUFFERING option on '%1'. Operating system error %2.
17300 | 16 | Not enough memory for process status structure (PSS) allocation.
17302 | 16 | The maximum limit for connections has been reached.
17303 | 16 | freepss: Bad process status structure (PSS) value.
17304 | 10 | Warning: Clean_process system function called from another thread. Outstanding I/O may not complete.
17308 | 16 | %1: Process %2!d! generated an access violation. SQL Server is terminating this process.
17309 | 16 | The current contents of process' input buffer are '%1'.
17310 | 16 | %1: Process %2!d! generated fatal exception %3!lx! %4. SQL Server is terminating this process.
17311 | 16 | SQL Server is aborting. Fatal exception %1!lx! caught.
17402 | 10 | Database '%1' set to single user mode.
17422 | 16 | closetable: Called with null session descriptor (SDES), server process ID (SPID) %1!d!.
17423 | 16 | closetable: Table already closed for session descriptor (SDES) %1!08lx!.
17424 | 10 | Warning: OPEN OBJECTS parameter may be too low.
17426 | 16 | Run sp_configure to increase the parameter value.
17429 | 16 | The srchindex system function failed for index ID = %1!d!, sridoff = %2!d!.
17430 | 10 | Database '%1' set to read only mode.
17550 | 10 | DBCC TRACEON %d, server process ID (SPID) %d.
17551 | 10 | DBCC TRACEOFF %d, server process ID (SPID) %d.
17557 | 16 | DBCC DBRECOVER failed for database ID %d.
17558 | 10 | %\*** Bypassing recovery for database ID %d.
17560 | 10 | DBCC DBREPAIR: '%ls' index restored for '%ls.%ls'.
17561 | 10 | '%ls' index restored for '%ls.%ls'.
17569 | 16 | DBCC cannot find the library initialization function %ls.
17570 | 16 | DBCC cannot find the function %ls in the library %ls.
17571 | 20 | DBCC function %ls in the library %ls generated an access violation. SQL Server is terminating process %d.
17572 | 16 | DBCC cannot free DLL %ls. SQL Server depends on this DLL to function properly.
17654 | 10 | Warning: Process status structure (PSS) found with open session descriptor (SDES). PSPID %1!d!, PSUID %2!d!, PCURDB %3!d!, range entry %4!d!, SDESP 0x%5!lx!, object ID %6!ld!.
17657 | 10 | Attempting to change default sort order ID from %1!d! to %2!d!.
17658 | 10 | SQL Server started in single user mode. Updates allowed to system catalogs.
17660 | 10 | Starting without recovery.
17661 | 10 | Recovering all databases but not clearing tempdb.
17669 | 10 | Table still open. Database ID %1!d!, table ID %2!ld!.
17674 | 10 | Login: %1 %2, server process ID (SPID): %3!d!, kernel process ID (KPID): %4!d!.
17676 | 10 | SQL Server shutdown due to Ctrl-C or Ctrl-Break signal.
17750 | 16 | Cannot load the DLL %ls, or one of the DLLs it references. Reason: %ls.
17751 | 16 | Cannot find the function %ls in the library %ls. Reason: %ls.
17752 | 16 | Extended procedure memory allocation failed for '%ls'.
17753 | 16 | %.*ls can only be executed in the master database.
17801 | 16 | Unknown internal error value.
17802 | 16 | Could not create server event thread.
17803 | 16 | Insufficient memory available.
17804 | 16 | Invalid 'nbytes' value.
17805 | 16 | Invalid buffer received from client.
17806 | 16 | Invalid event specification.
17807 | 16 | Invalid event '%1!ld!'.
17808 | 16 | Invalid starting position specified.
Error 17809 (ODS) | 10 | Could not connect. The maximum number of '%1!ld!' configured user connections are already connected. The system administrator can change the maximum to a higher value using sp_configure.
17810 | 16 | Could not set up Named Pipe.
17811 | 16 | Requested data-conversion does not exist.
17812 | 16 | Data conversion resulted in overflow.
17813 | 16 | Could not convert data due to syntax error in source field.
17814 | 16 | Invalid function parameter.
17815 | 10 | No longer waiting for client connections using '%1!hs!'.
17816 | 16 | No active RPC or parameter value out of range.
17817 | 16 | No active RPC or no parameters.
17818 | 16 | No active RPC or parameter name not found.
17819 | 16 | No active RPC.
17820 | 16 | Invalid data type parameter.
17821 | 16 | Could not set up subchannel.
17822 | 16 | Could not load ListenOn Net-Library '%1!hs!'.
17823 | 16 | Could not read from ListenOn connection.
Error 17824 (ODS) | 16 | Could not write to ListenOn connection '%1!hs!', loginname '%2!ls!', hostname '%3!ls!'. Connection closed.
17825 | 16 | Could not close ListenOn connection.
17826 | 16 | Could not set up ListenOn connection '%1!hs!'.
17827 | 10 | The maximum number of '%1!ld!' remote connections are currently in use.
17828 | 16 | Could not read from local subchannel Named Pipe.
17829 | 16 | Could not copy buffer to subchannel thread, subchannel closed.
17830 | 16 | A subchannel protocol error has occurred.
17831 | 16 | Could not load ListenOn Net-Library '%1!hs!' version '%2!hs!'. Need Net-Library version '%3!hs!' or greater.
17832 | 16 | Connection opened but invalid login packet(s) sent. Connection closed.
17833 | 16 | ListenOn connection '%1!hs!' is already in use.
17834 | 10 | Using '%1!hs!' version '%2!hs!' to listen on '%3!hs!'.
17835 | 16 | Configured for local access only.
17836 | 16 | Could not create I/O completion port.
17837 | 16 | char data type%0
17838 | 16 | variable-length char data type%0
17839 | 16 | binary data type%0
17840 | 16 | variable-length binary data type%0
17841 | 16 | 1-byte integer data type%0
17842 | 16 | 2-byte integer data type%0
17843 | 16 | 4-byte integer data type%0
17844 | 16 | bit data type%0
17845 | 16 | datetime data type%0
17846 | 16 | datetime data type, nulls allowed%0
17847 | 16 | money data type%0
17848 | 16 | money data type, nulls allowed%0
17849 | 16 | 4-byte float data type, nulls allowed%0
17850 | 16 | 8-byte float data type%0
17851 | 16 | 8-byte float data type, nulls allowed%0
17852 | 16 | 4-byte datetime data type, nulls allowed%0
17853 | 16 | 4-byte money data type%0
17854 | 16 | event type%0
17855 | 16 | done packet status field%0
17856 | 16 | error severity type%0
17857 | 16 | 4-byte integer data type, nulls allowed%0
17858 | 16 | image data type%0
17859 | 16 | text data type%0
17868 | 16 | numeric data type%0
17869 | 16 | numeric data type, nulls allowed%0
17870 | 16 | decimal data type%0
17871 | 16 | decimal data type, nulls allowed%0
17872 | 16 | bit data type, nulls allowed%0
17873 | 16 | 8000-byte variable-length binary data type%0
17874 | 16 | 8000-byte variable-length character data type%0
17875 | 16 | 8000-byte binary data type%0
17876 | 16 | 8000-byte character data type%0
17877 | 16 | 8000-byte Unicode character data type%0
17878 | 16 | 8000-byte Unicode variable-length character data type%0
17879 | 16 | Unicode text data type%0
17880 | 16 | uniqueidentifier data type%0


Errors 18000 - 18999

Error | Severity | Description
18002 | 20 | Stored function '%.*ls' in the library '%.*ls' generated an access violation. SQL Server is terminating process %d.
18052 | 16 | Error: %1!d!, Severity: %2!d!, State: %3!d!.
18053 | 16 | Error: %1!d!, Severity: %2!d!, State: %3!d!%n%4%5.
18100 | 10 | Process ID %d killed by hostname %.*ls, host process ID %d.
18101 | 10 | Non-Unicode sort order being reconfigured:
18102 | 10 | old value = %d new value = %d
18103 | 10 | Non-Unicode character set also being reconfigured:
18112 | 10 | Non-Unicode sort order successfully changed.
18113 | 10 | SQL Server shutdown after verifying system indexes.
18114 | 16 | Cannot install '%1' because there can be at most %2!d! languages in cache.
18122 | 10 | Unicode locale ID being reconfigured:
18123 | 10 | Unicode comparison style being reconfigured:
18124 | 10 | Unicode collation successfully changed.
18200 | 16 | %1: Backup device ID %2!d! out of range.
18201 | 16 | ksconsole: Cannot create ConsBufMutex: %1.
18203 | 16 | ksconsole: Cannot create %1 : %2.
18204 | 16 | %1: Backup device ‘%2’ failed to %3. Operating system error = %4.
18205 | 16 | %1: Could not initialize console operation.
18207 | 16 | %1: Null request packet.
18208 | 16 | %1: Backup device ID %2!d! is not active.
18209 | 16 | ksconsole: Could not send request to console client.
18210 | 16 | %1: %2 failure on backup device ‘%3’. Operating system error %4.
18211 | 16 | ksconsole: Could not receive request from console client.
18213 | 16 | ksconsole: Console input request for type 0x%1!x!, ID 0x%2!x! failed.
18214 | 16 | %1: Server console thread not running.
18215 | 16 | %1: Response type 0x%2!x!, ID 0x%3!x! not found in request.
18216 | 16 | %1: Could not access console mutex. Operating system error %2.
18217 | 16 | %1: Type 0x%2!x! not implemented.
18218 | 16 | %1: Incorrect number of parameters: %2!d!.
18219 | 16 | ksconsole: Could not close console connection.
18221 | 10 | ksconsole: Reinitializing the console.
18223 | 16 | %1: No console client connected. Start CONSOLE.EXE.
18225 | 10 | Tape ‘%1’ (Family ID: %2, sequence %3) mounted on tape drive ‘%4’.
18227 | 10 | Unnamed tape (Family ID: %1, sequence %2) mounted on tape drive ‘%3’.
18257 | 10 | %1: Device or media does not support %2.
18264 | 10 | Database backed up with following information: Database: %1, creation date and time: %2(%3), pages dumped: %4!d!, first LSN: %5, last LSN: %6, sort order: %7!d!, striped: %8, number of dump devices: %9!d!, device information: (%10).
18265 | 10 | Log backed up with following information: Database: %1, creation date and time: %2(%3), first LSN: %4, last LSN: %5, striped: %6, number of dump devices: %7!d!, device information: (%8).
18266 | 10 | Database file backed up with following information: Database: %1, creation date and time: %2(%3), file list: (%4), pages dumped: %5!d!, sort order: %6!d!, striped: %7, number of dump devices: %8!d!, device information: (%9).
18267 | 10 | Database restored: Database: %1, creation date and time: %2(%3), first LSN: %4, last LSN: %5, striped: %6, number of dump devices: %7!d!, device information: (%8).
18268 | 10 | Log restored: Database: %1, creation date and time: %2(%3), first LSN: %4, last LSN: %5, striped: %6, number of dump devices: %7!d!, device information: (%8).
18269 | 10 | Database file restored: Database: %1, creation date and time: %2(%3), file list: (%4), striped: %5, number of dump devices: %6!d!, device information: (%7).
18270 | 10 | Database incremental changes backed up with following information: Database: %1, creation date and time: %2(%3), pages dumped: %4!d!, first LSN: %5, last LSN: %6, full backup LSN: %7, sort order: %8!d!, striped: %9, number of dump devices: %10!d!, device
18271 | 10 | Database incremental changes restored: Database: %1, creation date and time: %2(%3), first LSN: %4, last LSN: %5, striped: %6, number of dump devices: %7!d!, device information: (%8).
18272 | 16 | I/O error on backup or restore restart-checkpoint file ‘%1’. Operating system error %2. The statement is proceeding but is non-restartable.
18400 | 16 | Checkpoint process is terminating due to a fatal exception.
18450 | 14 | Login failed for user ‘%ls’. Reason: Not defined as a valid user of a trusted SQL Server connection.
18452 | 14 | Login failed for user ‘%ls’. Reason: Not associated with a trusted SQL Server connection.
18453 | 14 | Login succeeded for user ‘%ls’. Connection: Trusted.
18454 | 14 | Login succeeded for user ‘%ls’. Connection: Non-Trusted.
18455 | 14 | Login succeeded for user ‘%ls’.
18456 | 14 | Login failed for user ‘%ls’.
18457 | 14 | Login failed for user ‘%ls’. Reason: User name contains a mapping character or is longer than 30 characters.
18458 | 14 | Login failed. The maximum simultaneous user count of %d licenses for this server has been exceeded. Additional licenses should be obtained and registered through the Licensing application in the Windows NT Control Panel.
18459 | 14 | Login failed. The maximum workstation licensing limit for SQL Server access has been exceeded.
18460 | 14 | Login failed. The maximum simultaneous user count of %d licenses for this '%ls' server has been exceeded. Additional licenses should be obtained and installed or you should upgrade to a full version.
18482 | 16 | Could not connect to server '%ls' because '%ls' is not defined as a remote server.
18483 | 16 | Could not connect to server '%ls' because '%ls' is not defined as a remote login at the server.
18485 | 16 | Could not connect to server '%ls' because it is not configured for remote access.
18490 | 16 | Maximum number of processors supported is '%1!ld!'.
18491 | 16 | Could not start due to invalid serial number.
18492 | 16 | The license agreement has been violated for this '%1' version of SQL Server. Cannot start.
18500 | 16 | Could not load startup handler DLL '%1'.
18501 | 16 | Could not load startup handler function '%1'.
18502 | 16 | Could not add startup handler '%1'.
18666 | 17 | Could not free up descriptor in rel_desclosed() system function.
18750 | 16 | %ls: The parameter '%ls' is invalid.
18751 | 16 | %ls procedure called with incorrect number of parameters.
18752 | 16 | Another log reader is replicating the database.
18754 | 16 | Could not open table %d.
18755 | 16 | Could not allocate memory for replication.
18756 | 16 | Could not get replication information for table %d.
18757 | 16 | The database is not published.
18759 | 16 | Replication failure. File '%ls', line %d.
18760 | 16 | Invalid %ls statement for article %d.
18761 | 16 | Commit record at (%ls) has already been distributed. Check DBTABLE.
18762 | 16 | Invalid begin LSN (%ls) for commit record (%ls). Check DBTABLE.
18763 | 16 | Commit record (%ls) reports oldest active LSN as (0:0:0).
18764 | 16 | Execution of filter stored procedure %d failed. See the SQL Server errorlog for more information.
18765 | 16 | Begin LSN specified for replication log scan is invalid.
18766 | 16 | The replbeginlsn field in the DBTABLE is invalid.
18767 | 16 | The specified begin LSN (%ls) for replication log scan occurs before replbeginlsn (%ls).
18768 | 16 | The specified LSN (%ls) for repldone log scan occurs before the current start of log (%ls).
18769 | 16 | The specified LSN (%ls) for repldone log scan is not a replicated commit record.
18831 | 16 | ;// Database ID %d. Could not find object descriptor for object ID %ld.
18833 | 16 | Database ID %d. Could not find clustered index on system table ID %ld. This index should exist in all databases. Run DBCC CHECKTABLE on sysindexes in the database.
18836 | 16 | Database ID %d. Could not find object ID %ld in sysobjects. This system catalog should exist in all databases. Run DBCC CHECKTABLE on sysobjects in this database.
18841 | 16 | Could not locate entry in sysdatabases for database ‘%.*ls’. No entry found with that name.
18843 | 16 | Could not find database ID %d in sysdatabases.
18872 | 16 | Rec_finish: getnext SCAN_NOINDEX on sysdatabases.dbid=%d failed.
18874 | 16 | Rec_complete: Could not open controlling database (ID %d) of controlling database in multi-database transaction
18875 | 16 | Recovering database ‘%.*s’.
18876 | 16 | %d transactions rolled forward in database ‘%.*ls’ (%d).
18877 | 16 | %d transactions rolled back in database ‘%.*ls’ (%d).
18878 | 16 | Recovery complete.
18883 | 16 | ;//Database ID %d: Attempt to mark database SUSPECT. Getnext NC scan on sysobjects.dbid failed.
18884 | 16 | ;//Database ‘%.*s’ (ID %d). Recovery failed. Run DBCC.
18885 | 16 | Page #%lx from table ID #%ld, database ID #%d, not found in cache.
18886 | 16 | Page #%lx from sysindexes in database ID #%X not in cache after reading it into cache.
18887 | 16 | Cannot recover the master database. Exiting.
18892 | 16 | Extent ID %ld which should belong to syslogs belongs to object ID %ld.
18894 | 16 | No more room in the transaction table.
18895 | 16 | Transaction (%d, %d) not found in the transaction table.
18901 | 16 | Could not build an allocation map for the database ‘%.*s’. Database does not have a DBINFO structure.


Errors 19000 -19999

Error | Severity | Description
19000 | 16 | ODBC error encountered, State = %1, native error = %2, error message = %3.
19001 | 16 | Windows NT Error encountered, %1.
19002 | 16 | MS SQL SNMP Extension Agent starting, %1, version %2.
19003 | 16 | MS SQL SNMP Extension Agent reconnecting.
19004 | 16 | MS SQL SNMP Extension Agent stopping.
19020 | 16 | RPC Net-Library listening on: %1.


Errors 20000 - 20999

Error | Severity | Description
20001 | 0 | There is no nickname for article '%s' in publication '%s'.
20002 | 0 | The filter '%s' already exists for article '%s' in publication '%s'.
20003 | 0 | Could not generate nickname for '%s'.
20007 | 16 | The system tables for merge replication could not be dropped successfully.
20008 | 16 | The system tables for merge replication could not be created successfully.
20009 | 16 | The article '%s' could not be added to the publication '%s'.
20010 | 16 | The Snapshot Agent corresponding to the publication '%s' could not be dropped.
20011 | 16 | Cannot set incompatible publication properties. The 'allow_anonymous' property of a publication depends on the 'immediate_sync' property.
20012 | 16 | The subscription type '%s' is not allowed on publication '%s'.
20013 | 16 | The publication property '%s' cannot be changed when there are subscriptions on it.
20014 | 16 | Invalid @schema_option value.
20015 | 16 | Could not remove directory '%ls'. Check the security context of xp_cmdshell and close other processes that may be accessing the directory.
20016 | 16 | Invalid @subscription_type value. Valid values are 'pull' or 'anonymous'.
20017 | 16 | The Subscriber side subscription does not exist.
20018 | 16 | The @optional_command_line is too long. Use an agent definition file.
20019 | 16 | The value must be 'name', 'description', 'subset_filterclause', 'column_tracking', 'article_resolver', 'resolver_procedure', 'status', 'pre_creation_command', 'creation_script', or 'schema_option'.
20020 | 16 | The article resolver supplied is either invalid or nonexistent.
20021 | 16 | The subscription could not be found.
20023 | 16 | Invalid @subscriber_type value. Valid options are 'local', 'global', 'anonymous', or 'repub'.
20025 | 16 | The publication name must be unique. The specified publication name '%s' has already been used.
20026 | 16 | The publication '%s' does not exist.
20027 | 16 | The article '%s' does not exist.
20028 | 16 | The Distributor has not been installed correctly. Could not enable database for publishing.
20029 | 16 | The distributor has not been installed correctly. Could not disable database for publishing.
20030 | 16 | The article '%s' already exists in another publication with a different column tracking option.
20031 | 16 | Could not delete the row could because it was not present.
20032 | 16 | '%s' is not defined as a Subscriber for '%s'.
20033 | 16 | Invalid publication type.
20034 | 16 | Publication '%s' does not support '%s' subscriptions.
20036 | 16 | The Distributor has not been installed correctly.
20037 | 16 | The article '%s' already exists in another publication with a different article resolver.
20038 | 16 | The article filter could not be added to the article '%s' in the publication '%s'.
20039 | 16 | The article filter could not be dropped from the article '%s' in the publication '%s'.
20040 | 16 | Could not drop the article(s) from the publication '%s'.
20041 | 16 | Transaction rolled back. Could not execute trigger. Retry your transaction.
20043 | 16 | Could not change the article '%s' because the publication has already been activated.
20044 | 16 | The priority property is invalid for local subscribers.
20045 | 16 | You must supply an article name.
20046 | 16 | The article does not exist.
20047 | 16 | You are not authorized to perform this operation.
20049 | 16 | The priority value should not be larger than 100.0.
20050 | 16 | The retention period must be greater than or equal to %d.
20051 | 16 | The Subscriber is not a registered Subscriber.
20054 | 16 | Current database is not enabled for publishing.
20055 | 16 | Table '%s' cannot be published for merge replication because it has a timestamp column.
20056 | 16 | Table '%s' cannot be re-published.
20057 | 16 | The profile name '%s' already exists for the specified agent type.
20058 | 16 | The @agent_type must be 1 (Snapshot), 2 (Logreader), 3 (Distribution), or 4 (Merge)
20059 | 16 | The @profile_type must be 0 (system) or 1 (Custom)
20060 | 16 | Compatibility level can not be smaller than 60.
20061 | 16 | The compatibility level of this database must be set to 70 or higher to be enabled for merge publishing.
20062 | 16 | Update of columns with the rowguidcol property is not allowed.
20064 | 16 | Cannot drop profile. Either it is not defined, or is defined as the default profile.
20065 | 16 | Cannot drop profile, because it is in use.
20066 | 16 | Profile not defined.
20067 | 16 | The parameter name '%s' already exists for the specified profile.
20068 | 16 | The article cannot be created on table '%s' because it has more than %d columns.
20069 | 16 | Cannot validate a merge article that uses looping join filters.
20070 | 16 | Cannot update subscription row.
20071 | 16 | Cannot find the publication named '%s'.
20072 | 16 | Cannot update Subscriber information row.
20073 | 16 | Articles can only be added or changed at the publisher.
20074 | 16 | Only tables can be published for merge replication.
20075 | 16 | The @status parameter value must be 'active', 'inactive', or 'unsynced'.
20076 | 16 | The @sync_mode parameter value must be 'native' or 'character'.
20077 | 16 | Problem encountered generating replica nickname.
20078 | 16 | The @property parameter value must be 'sync_type', 'priority', or 'description'.
20079 | 16 | Invalid @subscription_type parameter value. Valid options are 'push', 'pull', or 'both'.
20080 | 16 | Cannot publish table '%s' for merge replication because it has a computed column.
20081 | 16 | Publication property '%s' cannot be NULL.
20082 | 16 | Column '%s' cannot be published for replication because it is a computed column.
20083 | 16 | Table '%s' cannot be published for replication because it includes a computed column.
20084 | 16 | Publication '%s' cannot be subscribed to by Subscriber database '%s'.
20086 | 16 | Publication '%s' does not support the nosync type because it contains a table that does not have a rowguidcol column.
20087 | 16 | You cannot push an anonymous subscription.
20088 | 16 | You can only assign priorities that are greater than or equal to 0 and less than 100.
20089 | 16 | Could not get license information correctly.
20090 | 16 | Could not get version information correctly.
20100 | 16 | Cannot drop Subscriber '%s'. There are existing subscriptions.
20500 | 16 | The updatable Subscriber stored procedure '%s' does not exist in sysobjects.
20501 | 16 | Could not insert into sysarticleupdates using sp_articlecolumn.
20502 | 16 | Invalid '%s' value. Valid values are 'read only' or 'sync tran'.
20503 | 16 | Invalid '%s' value in '%s'. The publication is not enabled for updatable Subscribers.
20505 | 16 | Could not drop synchronous update stored procedure '%s' in '%s'.
20506 | 16 | Source table '%s' not found in '%s'.
20507 | 16 | Table '%s' not found in '%s'.
20508 | 16 | Updatable Subscribers: The text/ntext/image values inserted at Subscriber will be NULL.
20509 | 16 | Updatable Subscribers: The text/ntext/image values cannot be updated at Subscriber.
20510 | 16 | Updatable Subscribers: Cannot update identity columns.
20511 | 16 | Updatable Subscribers: Cannot update timestamp columns.
20512 | 16 | Updatable Subscribers: Rolling back transaction.
20515 | 16 | Updatable Subscribers: Rows do not match between Publisher and Subscriber. Refresh rows at Subscriber.
20516 | 16 | Updatable Subscribers: Replica is not updatable.
20517 | 16 | Updatable Subscribers: Update of replica's primary key is not allowed unless published table has a timestamp column.
20518 | 16 | Updatable Subscribers: INSERT and DELETE operations are not supported unless published table has a timestamp column.
20519 | 16 | Updatable Subscribers: INSERT operations on tables with identity or timestamp columns are not allowed unless a primary key is defined at the Subscriber.
20520 | 16 | Updatable Subscribers: UPDATE operations on tables with identity or timestamp columns are not allowed unless a primary key is defined at the Subscriber.
20521 | 16 | sp_MSmark_proc_norepl: Must be a member of the db_owner or setupadmin roles.
20522 | 16 | sp_MSmark_proc_norepl: Invalid object name '%s'.
20523 | 16 | Could not validate the article '%s'. It is not activated.
20524 | 10 | Table '%s' may be out of synchronization. Rowcount difference (actual: %d, expected: %d). Rowcount method %d used (0 = Full, 1 = Fast).
20525 | 10 | Table '%s' is out of synchronization. Rowcounts (actual: %d, expected %d). Checksum difference (actual: %s, expected: %s).
20526 | 10 | Table '%s' passed rowcount (%d) validation. Rowcount method %d used (0 = Full, 1 = Fast).
20527 | 10 | Table '%s' passed rowcount (%d) and checksum validation. (Note: checksum is not compared for any text and image columns.)
20528 | 10 | Log agent startup message.
20529 | 10 | Starting agent.
20530 | 10 | Run agent.
20531 | 10 | Detect nonlogged agent shutdown.
20532 | 10 | Replication Agent Schedule.
20533 | 10 | Replication agents checkup
20534 | 10 | Detects replication agents that are not actively logging history.
20535 | 10 | Removes replication agent history from the distribution database.
20536 | 10 | Replication: Agent failure
20537 | 10 | Replication: Agent retry
20538 | 10 | Replication: Expired subscription dropped
20540 | 10 | Replication: Agent success
20541 | 10 | Removes replicated transactions from the distribution database.
20542 | 10 | Detects and removes expired subscriptions from published databases.
20545 | 10 | Default agent profile
20546 | 10 | Verbose history agent profile.
20547 | 10 | Agent profile for detailed history logging.
20548 | 10 | Slow link agent profile.
20549 | 10 | Agent profile for low bandwidth connections.
20552 | 10 | Could not clean up the distribution transaction tables.
20553 | 10 | Could not clean up the distribution history tables.
20554 | 10 | The agent is suspect. No response within last %ld minutes.
20555 | 10 | 6.x publication.
20556 | 10 | Detected heartbeats for all running replication agents.
20557 | 10 | Agent shutdown. For more information see the SQL Server Agent job history for job '%s'.
20558 | 10 | Table '%s' passed full rowcount validation after failing the fast check. DBCC UPDATEUSAGE will be automatically initiated.
20559 | 10 | Conditional Fast Rowcount method requested without specifying an expected count. Fast method will be used.
20560 | 10 | An expected checksum value was passed, but checksums will not be compared because rowcount only checking was requested.
20561 | 10 | Generated expected rowcount value of %d for %s.
20562 | 10 | User delete.
20563 | 10 | No longer belongs in this partial.
20564 | 10 | System delete.
20565 | 10 | Replication: Subscriber has failed data validation
20566 | 10 | Replication: Subscriber has passed data validation
20567 | 10 | Agent history clean up: %s
20568 | 10 | Distribution clean up: %s
20569 | 10 | Expired subscription clean up
20570 | 10 | Reinitialize subscriptions having data validation failures
20571 | 10 | Reinitializes all subscriptions that have data validation failures.
20572 | 10 | Subscriber '%s' subscription to article '%s' in publication '%s' has been reinitialized after a validation failure.
20573 | 10 | Replication: Subscription reinitialized after validation failure
20574 | 10 | Subscriber '%s' subscription to article '%s' in publication '%s' failed data validation.
20575 | 10 | Subscriber '%s' subscription to article '%s' in publication '%s' passed data validation.
20576 | 10 | Subscriber '%s' subscription to article '%s' in publication '%s' has been reinitialized after a synchronization failure.
20577 | 10 | No entries were found in msdb..sysreplicationalerts.
20578 | 10 | Replication: Agent custom shutdown
20579 | 10 | Generated expected rowcount value of %d and expected checksum value of %s for %s.


Errors 21000 -21999

Error | Severity | Description
21000 | 16 | Cannot subscribe to an inactive publication.
21001 | 16 | Cannot add a Distribution Agent at the Subscriber for a push subscription.
21002 | 16 | The Distribution Agent for this subscription already exists (%s).
21003 | 16 | Changing publication names is no longer supported.
21004 | 16 | Cannot publish the stored procedure '%s' because it is encrypted.
21005 | 10 | For backward compatibility, sp_addpublisher can be used to add a Distribution Publisher. However, you should use sp_adddistpublisher, which is more flexible.
21006 | 16 | Cannot use sp_addpublisher to add a Distribution Publisher this time. Use sp_adddistpublisher instead.
21007 | 16 | Cannot add the remote Distributor at this time. Make sure that the local server is configured as a Distribution Publisher at the Distributor.
21008 | 16 | Cannot uninstall the Distributor because there are Subscribers defined.
21009 | 16 | The specified filter procedure is already associated with a table.
21010 | 16 | Removed %ld replicated transactions consisting of %ld statements in %ld seconds (%ld rows/sec).
21011 | 16 | Deactivated subscriptions.
21012 | 16 | Cannot change the 'allow_push' property of the publication to false. There are push subscriptions on it.
21013 | 16 | Cannot change the 'allow_pull' property of the publication to false. There are pull subscriptions on it.
21014 | 16 | The @optname parameter value must be 'transactional' or 'merge'.
21015 | 16 | The replication option '%s' has been set to TRUE already.
21016 | 16 | The replication option '%s' has been set to FALSE already.
21018 | 16 | There are too many consecutive snapshot transactions in the distribution database. Rerun the Log Reader or clean up the distribution database.
21021 | 16 | Drop the Distributor first before you uninstall replication.
21022 | 16 | Cannot set incompatible publication properties. The 'immediate_sync' property of a publication is dependent on the 'independent agent' property of a publication.
21023 | 16 | '%s' is no longer supported.
21024 | 16 | The stored procedure '%s' is already published as an incompatible type.
21025 | 16 | The string being encrypted cannot have null characters.
21026 | 16 | Cannot have an anonymous subscription on a publication that does not have an independent agent.
21027 | 16 | '%s' replication stored procedures are not installed. Use sp_replicationoption to install them first.
21028 | 16 | Replication components are not installed on this server. Run SQL Server Setup again and select the option to install replication.
21029 | 16 | Cannot drop a push subscription entry at the subscriber unless @drop_push is 'true'.
21030 | 16 | Names of SQL Server replication agents cannot be changed.
21031 | 16 | 'post_script' is not supported for stored procedure articles.
21032 | 16 | Could not subscribe because non-SQL Server Subscriber '%s' does not support 'sync tran' update mode.
21033 | 16 | Cannot drop server '%s' as Distribution Publisher because there are databases enabled for replication on that server.
21034 | 16 | Rows inserted or updated at the Subscriber are not allowed to be outside the article partition.
21035 | 16 | You have successfully updated the Distribution Publisher property '%s'.
21036 | 16 | Another %s agent for the subscription(s) is running.
21037 | 16 | Invalid working directory '%s'.
21038 | 16 | Windows NT Authentication mode is not supported by the server.
21039 | 16 | The destination owner name is not supported for publications that can be subscribed to by non-SQL Server Subscribers.
21040 | 16 | Publication '%s' does not exist.
21041 | 16 | A remote Distribution Publisher is not allowed on this server version.
21042 | 16 | The Distribution Publisher property, 'distributor_password', has no usage and is not supported for a Distributor running on Windows NT.
21043 | 16 | The Distributor is not installed.
21044 | 16 | Cannot ignore the remote Distributor (@ignore_remote_distributor cannot be 1) when enabling the database for publishing or merge publishing.
21045 | 16 | Cannot uninstall the Distributor because there are databases enabled for publishing or merge publishing.
21046 | 16 | Cannot change Distribution Publisher property 'distribution_db' because the remote Publisher is using the current distribution database.
21047 | 16 | Cannot drop the local Distribution Publisher because there are Subscribers defined.
21048 | 16 | Cannot add login '%s' to the publication access list because it does not have access to the distribution server '%s'.
21049 | 16 | The login '%s' does not have access permission on publication '%s'.
21050 | 16 | Only members of the sysadmin or db_owner roles can perform this operation.
21051 | 16 | Could not subscribe because non-SQL Server Subscriber '%s' does not support custom stored procedures.
21052 | 16 | Transactional publications are supported on Windows NT platforms only.
21053 | 16 | The parameter must be 'description', 'status', 'retention', 'sync_mode', 'allow_push', 'allow_pull', 'allow_anonymous', 'enabled_for_internet', 'centralized_conflicts', 'snapshot_ready', or 'default_access'.
21054 | 16 | Updatable Subscribers: RPC to Publisher failed.
21055 | 15 | Invalid parameter %s specified for %s.
21056 | 16 | The subscription to publication '%s' has expired or does not exist.
21057 | 16 | Anonymous Subscribers are not allowed to have updatable subscriptions.
21058 | 16 | An updatable subscription to publication '%s' on Subscriber '%s' already exists.
21059 | 16 | Cannot reinitialize subscriptions of non-immediate-sync publications.
21060 | 16 | Could not subscribe because non-SQL Server Subscriber '%s' does not support parameterized statements.
21061 | 16 | Invalid article status %d specified when adding article '%s'.
21062 | 16 | The row size of table '%s' exceeds the replication limitation of 6000 bytes.
21063 | 16 | Table '%s' cannot participate in updatable subscriptions because it is published for merge replication.
21070 | 16 | This subscription does not support automatic reinitialization (subscribed with the 'no sync' option). To reinitialize this subscription, you must drop and re-create the subscription.
21071 | 10 | Cannot reinitialize article '%s' in subscription '%s:%s' to publication '%s' (subscribed with the 'no sync' option).
21072 | 16 | The subscription has not been synchronized within the maximum retention period. You must reinitialize the subscription to receive data.
21073 | 16 | The publication specified does not exist.
21074 | 16 | The subscription has expired and must be reinitialized at the Publisher.
21075 | 10 | Waiting for the next scheduled snapshot.
21076 | 10 | Waiting for the next scheduled snapshot for article '%s'.
21077 | 10 | Deactivated initial snapshot for anonymous publication(s). New subscriptions must wait for the next scheduled snapshot.
21078 | 16 | Table '%s' does not exist in the Subscriber database.
21079 | 16 | The RPC security information for the Publisher is missing or invalid. Use sp_link_publication to set it.
21080 | 16 | The timestamp column has to be in the vertical partition of the article that is enabled for updatable subscriptions.
21081 | 16 | Server setting 'Allow triggers to be fired which fire other triggers (nested triggers)' has to be on at updatable subscribers.
21082 | 16 | Database property 'IsRecursiveTriggersEnabled' has to be true for subscribing databases at updatable subscribers.
21083 | 16 | Database compatibility level at immediate-updating Subscribers cannot be less than 7.0.
21084 | 16 | Publication '%s' does not allow anonymous subscriptions.
21085 | 16 | The retention period must be less than retention period for the distribution database.
21086 | 16 | The retention period for the distribution database must be greater than the retention period of any existing non-merge publications.
21087 | 16 | Anonymous Subscribers or Subscribers at this server are not allowed to create merge publications.
21107 | 16 | '%ls' is not a table or view.
21108 | 16 | This edition of SQL Server does not support transactional publications.
21109 | 16 | The parameters @xact_seqno_start and @xact_seqno_end must be identical if @command_id is specified.
21110 | 16 | All parameters must be specified if @command_id is specified.
21111 | 16 | '%s' is not a valid parameter for the Snapshot Agent.
21112 | 16 | '%s' is not a valid parameter for the Log Reader Agent.
21113 | 16 | '%s' is not a valid parameter for the Distribution Agent.
21114 | 16 | '%s' is not a valid parameter for the Merge Agent.
21115 | 16 | '%s' is not a valid value for the '%s' parameter. The value must be a positive integer.
21116 | 16 | '%s' is not a valid value for the '%s' parameter. The value must be 1, 2, or 3.
21117 | 16 | '%s' is not a valid value for the '%s' parameter. The value must be 0, 1, or 2.
21118 | 16 | '%s' is not a valid value for the '%s' parameter. The value must be greater than or equal to 0 and less than or equal to 10000.
21119 | 16 | '%s' is not a valid value for the '%s' parameter. The value must be a non-negative integer.
21120 | 16 | Only members of the sysadmin fixed server role and db_owner fixed database role can drop subscription '%s' to publication '%s'.
21121 | 16 | Only members of the sysadmin fixed server role and '%s' can drop the pull subscription to the publication '%s'.
21122 | 16 | Cannot drop the distribution database '%s' because it is currently in use.


System Error Message Details


Error 103

Severity Level 15
Message Text

The %S_MSG that starts with '%.*ls' is too long. Maximum length is %d.

Explanation

If you enclose a character string in double quotation marks that is more than 128 characters, the application may receive this error. When the QUOTED_IDENTIFIERS option is set on (SET QUOTED_IDENTIFIERS ON), Microsoft® SQL Server™ expects quoted identifiers to be enclosed in double quotation marks (“) and data values to be enclosed in single quotation marks (‘). In the case of character parameters of stored procedures, data values enclosed in double quotation marks are accepted by SQL Server if the character string is less than 128 characters. They should be considered syntax errors by SQL Server and generate an error.

You can also see this in ODBC applications using the Microsoft SQL Server ODBC driver versions 2.50.0121 and later. These drivers set QUOTED_IDENTIFIERS ON when run against a SQL Server version 6.x or later server so that the driver’s behavior more closely matches the ANSI and ODBC standards. ODBC applications which use double quotation marks for parameter values may see this behavior after you upgrade to SQL Server 6.x or later and the ODBC 2.50.0121 or later driver.

This behavior has been seen when using stored procedures that contain nested stored procedure execution with parameters delimited in double quotation marks (such as xp_cmdshell) from ODBC applications such as Microsoft Internet Information Service (IIS).

SQL Server does not always flag stored procedure parameters enclosed in double quotation marks if the SET QUOTED_IDENTIFIER ON option has been issued.

Action

Change the procedure call to enclose the parameter values in single quotation marks:

EXECUTE myproc 1, 'abcdefghijklmn'

ODBC applications can also use bound parameter markers instead of providing the values directly using either proprietary Transact-SQL syntax:

SQLExecDirect(hstmt, "EXECUTE myproc ?,?", SQL_NTS);

or, the ODBC standard syntax:

SQLExecDirect(hstmt, "{ call myproc (?,?)}", SQL_NTS);

In these cases, you may be able to work around the problem by placing a SET QUOTED_IDENTIFIER OFF statement at the beginning of the stored procedure. This setting will be in effect only for the scope of the stored procedure and will not affect other statement execution outside of the stored procedure.

CREATE PROCEDURE iisproc

AS

    BEGIN

        DECLARE @stmt varchar(255)

        SET QUOTED_IDENTIFIER OFF

        SELECT @stmt = 'xp_cmdshell "c:\myprog xxxxxxxxxxxxxxxxxxxxxxx"'         EXECUTE (@stmt)

    END

See Also
Errors 1 - 999


Error 107

Severity Level 15
Message Text

The column prefix '%.*ls' does not match with a table name or alias name used in the query.

Explanation

A column prefix was specified that does not correspond to any table name specified in the query. Match the column prefixes against the table names and alias names in the FROM clause.

One common cause of this error is the use of a table name when an alias name for the table is also supplied. When working with a table alias (a correlation name in ANSI terminology), the syntax checking in Microsoft® SQL Server™ complies with the ANSI specification. ANSI states,

A <table name> ... is exposed ... if and only if the <table reference>

does not specify a <correlation name>.

If an alias has been provided for a table name in the FROM clause, you can only use the alias to qualify columns from the table; the table name cannot be used elsewhere in the statement because they are flagged as syntax errors.

As an example of the difference in behavior, assume this script has been executed:

USE Northwind

GO

SELECT Customers.ContactName

FROM Customers cu

WHERE ContactName LIKE 'C%'

GO

SELECT cu.ContactName

FROM Customers cu

WHERE Customers.ContactName LIKE 'C%'

GO

In both SELECT statements, notice the use of Customers to qualify the column ContactName even though a table alias of cu has been provided to substitute for the table name. Both of these queries return this error message:

Server: Msg 107, Level 16, State 3

The column prefix 'Customers' does not match with a table name or alias name used in the query.

Action

Use the column prefix that corresponds to the exposed name of the table.

Rewrite any queries where column names are qualified with the table name. Use the table alias instead. For example, this SELECT statement is equivalent to the ones above and uses a table alias for column qualification:

USE Northwind

GO

SELECT cu.ContactName

FROM Customers cu

WHERE cu.ContactName LIKE 'C%'

GO

See Also
Errors 1 - 999


Error 109

Severity Level 15
Message Text

There are more columns in the INSERT statement than values specified in the VALUES clause. The number of values in the VALUES clause must match the number of columns specified in the INSERT statement.

Explanation

This error occurs when more columns are listed in the INSERT statement than values specified in the VALUES clause. The number of values in the VALUES clause must match the number of columns specified in the INSERT statement.

Do not confuse error 109 with operating-system error 109. Operating-system error 109 means that a named pipe connection has been terminated.

Action

Rewrite the INSERT statement, ensuring that the number of columns specified matches the number of columns in the VALUES clause. For example:

INSERT t1 (col1,col2,col3) VALUES (val1,val2,val3)


Error 137

Severity Level 15
Message Text

Must declare the variable '%.*ls'.

Explanation

This error occurs when a variable is used in a SQL script without first declaring the variable. This example returns error 137:

SET @mycol = 'ContactName'

SELECT @mycol

GO

One of the more complicated causes of this error includes the use of a variable that was declared outside the EXECUTE statement. For example:

USE Northwind

GO

DECLARE @mycol nvarchar(20)

SET @mycol = 'ContactName'

EXECUTE ('SELECT @mycol FROM Customers')

Action

Verify that any variables used in a SQL script are declared before being used elsewhere in the script.

Rewrite the procedure so that it does not reference variables in the EXECUTE statement that were declared outside of it.

USE Northwind

GO

DECLARE @mycol nvarchar(20)

SET @mycol = 'ContactName'

EXECUTE ('SELECT ' + @mycol + ' FROM Customers')

See Also
Errors 1 - 999


Error 156

Severity Level 15
Message Text

Incorrect syntax near the keyword '%.*ls'.

Explanation

This error indicates that the syntax of a Transact-SQL statement is incorrect and that the syntax error was detected near the keyword specified in the error message. The most frequent causes for syntax errors are misspellings of Transact-SQL keywords or operators, and specifying the syntax of a Transact-SQL statement in the wrong order.

One of the more complicated causes for this error may be a compatibility level mismatch for the current database. If the current database has a compatibility level other than 70, SQL Server will not recognize any of the keywords that a database with a compatibility level of 70 would recognize.

Action

First, check the Transact-SQL statement syntax near the keyword specified in the error message. Because Transact-SQL language syntax can be very complex, Microsoft® SQL Server™ may report the syntax error later in the Transact-SQL statement syntax than it actually occurred. Second, reexamine the entire Transact-SQL statement that generated the error. Verify the syntax order of the statement.

Ensure that the database does not have a compatibility level of 65 and has a compatibility level of 70.

See Also

Errors 1 - 999


Error 170

Severity Level 15
Message Text

Line %d: Incorrect syntax near '%.*ls'.

Explanation

This error indicates that the syntax of a Transact-SQL statement is incorrect and that the syntax error was detected near the Transact-SQL syntax element specified in the error message. The most frequent causes for syntax errors are misspellings of Transact-SQL syntax elements or operators, and specifying the syntax of a Transact-SQL statement in the wrong order.

This example produces error 170:

USE Northwind

GO

SELECT &

FROM Categories

ORDER BY CategoryName ASC

Action

First, check the Transact-SQL statement syntax near the syntax element specified in the error message. Because Transact-SQL language syntax can be very complex, Microsoft® SQL Server™ may report the syntax error later in the Transact-SQL statement syntax than it actually occurred. Second, reexamine the entire Transact-SQL statement that generated the error. Verify the syntax order of the statement.

In the above example, changing the ampersand (&) to an asterisk (*) corrects the problem:

USE Northwind

GO

SELECT *

FROM Categories

ORDER BY CategoryName ASC

See Also
Errors 1 - 999


Error 207

Severity Level 16
Message Text

Invalid column name '%.*ls'.

Explanation

This error occurs when a column referenced in a Transact-SQL statement was not found in any table specified in the FROM clause of the query.

Action

Change the column name to a column name present in one of the tables referenced in the query.

This example returns error 207:

USE Northwind

GO

SELECT CategoryName1

FROM Categories

GO

Evaluate the problem by looking at the full command. For the above example, ensure that the SELECT statement contains the name of a valid column name (CategoryName rather than CategoryName1 as specified above) for the specified table.

USE Northwind

GO

SELECT CategoryName

FROM Categories

GO

See Also
Errors 1 - 999


Error 208

Severity Level 16
Message Text

Invalid object name '%.*ls'.

Explanation

This error occurs when an object that does not exist is referenced. If the object exists, you might need to include the owner’s name in the object name.

If the object is not owned by the user attempting to access it, and it is not owned by the database owner, all references to the object must include the owner’s name. For example, if user1 creates a table called test, other users must use the name user1.test when they refer to the table.

The Microsoft® SQL Server™ naming convention for database objects is:

[[[server_name.][database_name].][owner_name].]object_name

The default value for server_name is the current server and the default value for database_name is the current database. The default value for owner_name is the current user. Because owner_name is part of the object name, it is possible for two different users to have tables with the same name in the same database (for example, user1.test and user2.test).

This message can also occur when you reference a temporary table that was created with an EXECUTE statement.

Action

The procedure for handling this error depends on what you know about the object indicated in the error message text.

The appropriate permissions must also be set to allow access to an object. If these permissions are not set, error 229 or 230 occurs.

If you do not know who owns the object
  • Execute sp_help with no parameters to display the object owner.

Or

  • Query the Information Schema Views if the object is a table or view to determine the object owner and type. If the object is not a table or a view, query the sysobjects system table to determine the object owner and type.

For example, to determine the owner and type for the object named table_1, execute the following:

USE master

GO

SELECT TABLE_SCHEMA

FROM INFORMATION_SCHEMA.TABLES

WHERE TABLE_NAME = 'table_1'

GO

If no rows are returned from this query, the object either resides in a different database or does not exist.

If you do not own the object in question
  • Include the object owner in the object name. For example:

    SELECT *

    FROM user1.table_1

    Although using fully qualified object names eliminates this problem, remember that including the fully qualified object name in an application might complicate the maintenance of the application. For example, if all references to a table include the database name, changing the database name could become difficult.

Or

  • Have the database owner create the object. If the owner creates the object, any user can find the object without specifying the owner. However, temporary tables reside in tempdb and are dropped automatically when the user process or server connection that created them is terminated. Users cannot share temporary tables, even if they are created by the database owner.
If the object does not reside in the database
  • Switch context to the correct database using the USE statement. For example:

    USE database_1

Or

  • Qualify the object name with the database name. For example:

    SELECT *

    FROM database_1.user1.table_1

    If you own the object or if the object is owned by the database owner, the owner name is not needed. For example:

    SELECT *

    FROM database_1..table_1

If a temporary table created with an EXECUTE statement is referenced
  • If you must use the EXECUTE statement to create a temporary table, create it as a global temporary table using the syntax ##tablename.
See Also

Errors 1 - 999


Error 229

Severity Level 14
Message Text

%ls permission denied on object '%.*ls', database '%.*ls', owner '%.*ls'.

Explanation

This error occurs when a Microsoft® SQL Server™ user attempts an action, such as executing a stored procedure, or reading or modifying a table, for which the user does not have the appropriate privileges.

Action

Any user (the object owner or system administrator) with full-control over the object in question can grant the necessary privileges to the user requiring access to the object.

See Also

Errors 1 - 999


Error 220

Severity Level 16
Message Text

Arithmetic overflow error for data type %ls, value = %ld.

Explanation

This error occurs when an attempt is made to convert a float or real data type value into a data type that cannot store the result. This error prevents the operation from being completed. For example, if you attempt to place the number 32770 into a variable or column of smallint data type, Microsoft® SQL Server™ returns this error because variables or columns of smallint data type can address integers from 2^15 (–32,768) through 2^15 (32,767).

This example raises the error:

DECLARE @myval smallint

SET @myval = 32770

SELECT @myval

GO

Action

For numeric operations, use the ROUND, CAST, and CONVERT functions to manipulate the value in question to fit into the column or variable. Change the data type of the column or variable in question. In the example described above, change the column or variable from smallint to int).

Here is the corrected example:

DECLARE @myval int

SET @myval = 32770

SELECT @myval

GO

See Also

Errors 1 - 999


Error 245

Severity Level 16
Message Text

Syntax error converting the %ls value '%.*ls' to a column of data type %ls.

Explanation

Microsoft® SQL Server™ returns this message if a character is converted to an integer. For example, these SELECT statements return error 245:

SELECT CONVERT(int, 'A')

-- Or

SELECT CAST('A' AS int)

SQL Server returns this error message because a conversion from a character value to an integer can only be done if it resembles a numeric value. For example, the character 1 (one) can be converted to an integer.

SELECT CONVERT(int, '1')

-- Or

SELECT CAST('1' AS int)

Action

To convert a character to an integer, use the ASCII function, which returns a numerical representation of the character. For example:

SELECT CONVERT(int, ASCII('A'))

-- Or

SELECT CAST(ASCII('A') AS int)

See Also

Errors 1 - 999


Error 259

Severity Level 16
Message Text

Ad hoc updates to system catalogs are not enabled. The system administrator must reconfigure SQL Server to allow this.

Explanation

This error occurs when Microsoft® SQL Server™ detected an attempt to modify the system catalogs directly while the allow updates system configuration option of sp_configure is set to 0.

The allow updates system configuration option allows the system administrator to change the system catalogs directly.

Warnings Severe problems can result from the direct manipulation of the system catalogs. Do not modify the system catalogs unless instructed to do so by your primary support provider.

Action

Before modifying any system catalogs, be sure that you have a valid backup of the database.

Warning Incorrect modification of the system catalogs can result in database corruption or data loss.

If possible, restart SQL Server in single-user mode by using the -m flag of the sqlservr application so that inadvertent modifications do not occur.

To modify system catalogs, use the osql utility to alter the allow updates system configuration setting.

Note Only the system administrator can alter the value for the allow updates system configuration setting.

See Also
Errors 1 - 999 | sp_configure_sp_configure
Reporting Errors to Your Primary Support Provider_Reporting_Errors_to_Your_Primary_Support_Provider | SQL Server Startup Options_SQL_Server_Startup_Options
Setting Configuration Options_Setting_Configuration_Options |


Error 266

Severity Level 16
Message Text

Transaction count after EXECUTE indicates that a COMMIT or ROLLBACK TRANSACTION statement is missing. Previous count = %ld, current count = %ld.

Explanation

If a stored procedure exits with the @@TRANCOUNT value that is not the same as when the stored procedure was entered, Microsoft® SQL Server™ returns error 266.

Note This error can be ignored because it only sends a message to the client and does not affect execution.

This example reproduces the problem:

CREATE PROCEDURE test

AS

SELECT @@TRANCOUNT

ROLLBACK TRANSACTION

SELECT @@TRANCOUNT

GO

BEGIN TRANSACTION

EXECUTE test

GO

Because @@TRANCOUNT is not the same in both SELECT statements, error 266 is generated on return from the stored procedure.

This is expected behavior, but it does not mean that transactions cannot be started, completed, or terminated in a stored procedure. Instead, care must be taken so that the @@TRANSACTION function matches on both entry and exit of the stored procedure.

This problem is more likely to occur when writing nested stored procedures.

Action

There is solution so that the stored procedure works without the error. The following is a list of solutions, with sample code for each:

  1. Perform final COMMIT TRANSACTION or ROLLBACK TRANSACTION statements from the same stored procedure nesting level where the transaction began, as shown by the following examples:

    -- Example 1.a

    CREATE PROCEDURE test1a

    AS

    SELECT @@TRANCOUNT

    GO

    BEGIN TRANSACTION

    EXECUTE test1a

    ROLLBACK TRANSACTION

    GO

    -- Example 1.b

    CREATE PROCEDURE test1c

    AS

    SELECT @@TRANCOUNT

    GO

    CREATE PROCEDURE test1b

    AS

    BEGIN TRANSACTION

    EXEC test1c

    COMMIT TRANSACTION

    GO

    EXECUTE test1b

    GO

  2. If nested transactions are used in a stored procedure, perform matching commits.

    Note The transaction is not committed until @@TRANCOUNT is equal to 0 (zero).

    -- Example 2

    CREATE PROCEDURE test2b

    AS

    SELECT @@TRANCOUNT

    BEGIN TRANSACTION

    SELECT @@TRANCOUNT

    COMMIT TRANSACTION

    SELECT @@TRANCOUNT

    GO

    CREATE PROCEDURE test2a

    AS

    BEGIN TRANSACTION

    EXECUTE test2b

    COMMIT TRANSACTION

    GO

    EXECUTE test2a

    GO

  3. If a rollback is needed and the stored procedure nesting level is different than where the transaction began, use RAISERROR, with a valid user-defined error, and check the @@ERROR function after the EXECUTE statement.

    -- Example 3

    USE master

    EXECUTE sp_addmessage 50001, 16, 'Rollback of transaction in test3'

    GO

    CREATE PROCEDURE test3

    AS

    RAISERROR (50001,16,1)

    GO

    BEGIN TRANSACTION

    EXEC test3

    IF @@error <> 50001

    BEGIN

    PRINT 'Commit'

    COMMIT TRANSACTION

    END

    ELSE

    BEGIN

    PRINT 'Rollback'

    ROLLBACK TRANSACTION

    END

    GO

  4. The exception to this rule is that if a trigger performs a rollback, @@TRANCOUNT need not match its starting value, because the batch is terminated. However, a stored procedure called by a trigger may cause the problem if it terminated the transaction.

    -- Example 4

    CREATE TABLE x (col1 int)

    GO

    CREATE TRIGGER xins

    ON x

    FOR INSERT AS

    ROLLBACK TRANSACTION

    GO

    CREATE PROCEDURE sp_xinsert

    AS

    SELECT @@TRANCOUNT

    INSERT x (col1) VALUES (1)

    SELECT @@TRANCOUNT

    GO

    BEGIN TRANSACTION

    EXECUTE sp_xinsert

    IF @@error <> 0

    BEGIN

    PRINT 'Commit'

    COMMIT TRANSACTION

    END

    ELSE

    BEGIN

    PRINT 'Rollback'

    ROLLBACK TRANSACTION

    END

    GO

    SELECT *

    FROM x

See Also

Errors 1 - 999


Error 268

Severity Level 16
Message Text

Cannot run SELECT INTO in this database. The database owner must run sp_dboption to enable this option.

Explanation

This error occurs when an attempt to use the SELECT INTO statement has not been permitted because the select into/bulkcopy database option is not enabled for this database. The database owner must turn on the select into/bulkcopy database option before the SELECT INTO statement can be completed successfully.

This error can also be triggered by stored procedures.

Caution Enabling the select into/bulkcopy database option permits nonlogged operations to take place. Have a specific backup strategy in place to ensure data integrity after nonlogged operations have been performed. A transaction log cannot be backed up after a nonlogged operation. Use the BACKUP DATABASE statement after nonlogged operations have been performed.

Action

The database owner or system administrator must use the sp_dboption system stored procedure to enable the select into/bulkcopy database option. For example, for the pubs database, you would use the osql command prompt utility to perform the following steps:

  1. Switch to the master database and set the database option for the Northwind database. Type:

    USE master

    GO

    sp_dboption Northwind, 'select into/bulkcopy', true

    GO

    USE Northwind

    GO

    CHECKPOINT

    GO

  2. Verify that the change has taken place correctly. Execute the sp_helpdb system stored procedure on Northwind. The status result column should show the select into/bulkcopy database option as enabled. Type:

    sp_helpdb Northwind

    GO

You may want to review information about the bcp Utility and SELECT INTO statement. In some cases, bcp is a logged operation that can affect your backup strategy and transaction log backup frequency.

See Also

Errors 1 - 999


Error 511

Severity Level 16
Message Text

Cannot create a row of size %d which is greater than the allowable maximum of %d.

Explanation

This error occurs when you attempt to insert a row that is larger than the maximum defined for that table. This error occurs if the row you attempt to insert into a table is too big to fit into a data page.

In Microsoft® SQL Server™, the maximum allowable size of a row in a table is 8060 bytes. A row cannot be split across data pages. A data page is 8 KB in size and consists of the data row and some internal data structures.

Action

Change the data being inserted so it does not exceed the maximum number of bytes (8060) that can be stored in a single row.


Error 515

Severity Level 16
Message Text

Cannot insert the value NULL into column '%.*ls', table '%.*ls'; column does not allow nulls. %ls fails.

Explanation

This error occurs at run time when an attempt is made to use a null value while inserting or updating a column that does not allow null values.

Note This message differs from the following message, which indicates that the attempt has been detected at compile time.

error 233: The column '%.*ls' in table '%.*ls' cannot be null.

This error can also occur if the table that is the target of an INSERT or UPDATE statement in a stored procedure or trigger is being dropped and re-created, and one or more of the table column definition(s) have changed from NULL to NOT NULL.

Action

If this error occurs when you are running an UPDATE or INSERT statement, verify that the data inserted or updated matches the column definition for the affected table.

Inserting or updating a column does not allow null values.

Note In a direct UPDATE or INSERT by value, you will get compile error 233 instead of error 515. Usually 515 errors occur in an INSERT/SELECT or an UPDATE statement that uses data in another table.

If this error occurs when a stored procedure or trigger references a table that has been dropped and re-created with different nullability, drop and re-create the affected stored procedure or trigger.

If you are unable to resolve the problem, contact your primary support provider for assistance.

See Also

Errors 1 - 999


Error 544

Severity Level 16
Message Text

Cannot insert explicit value for identity column in table '%.*ls' when IDENTITY_INSERT is set to OFF.

Explanation

This error occurs when you have attempted to insert a row that contains a specific identity value into a table that contains an identity column. However, SET IDENTITY_INSERT is not enabled for the specified table.

Action

To insert a specific identity row successfully into a table containing an identity column, you must enable SET IDENTITY_INSERT. The following example inserts identity row 2, where iID is defined as the identity column.

USE pubs

GO

IF EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES

        WHERE TABLE_NAME = 'tblTest')

    DROP TABLE tblTest

GO

CREATE TABLE tblTest

( iID    int IDENTITY(1, 1),

  strData nvarchar(15)

)

GO

INSERT INTO tblTest (strData) VALUES (N'Leverling')

INSERT INTO tblTest (strData) VALUES (N'Davolio')

GO

SET IDENTITY_INSERT tblTest ON

GO

-- Insert the specified identity row using a column list.

INSERT INTO tblTest (iID, strData) VALUES (5, N'Callahan')

GO

-- Display the rows in tblTest to see identity values.

SELECT *

FROM tblTest

-- Disable IDENTITY_INSERT.

SET IDENTITY_INSERT tblTest OFF

GO

See Also

Errors 1 - 999


Error 601

Severity Level 12
Message Text

Could not continue scan with NOLOCK due to data movement.

Explanation

When scanning with the NOLOCK locking hint or with the transaction isolation level set to READ UNCOMMITTED, it is possible for the page at the current position of the scan to be deleted. When this happens, Microsoft® SQL Server™ is not able to continue the scan.

Action

This error aborts the query. Either resubmit the query or remove the NOLOCK locking hint.


Error 602

Severity Level 21
Message Text

Could not find row in sysindexes for database ID %d, object ID %ld, index ID %d. Run DBCC CHECKTABLE on sysindexes.

Explanation

This error occurs when Microsoft® SQL Server™ cannot find a row in the sysindexes table for a needed table or index (for example, when executing a stored procedure that references a table that has been dropped).

Action

If the error occurs because a stored procedure references a dropped table, drop and re-create the stored procedure. This error may also occur in conjunction with other error messages that better point to the root cause of the problem. Execute DBCC CHECKTABLE on sysindexes; also execute DBCC CHECKDB.

If the problem persists, contact your primary support provider. Have the output from the DBCC CHECKDB statement available for review.

See Also

Errors 1 - 999


Error 605

Severity Level 21
Message Text

Attempt to fetch logical page %S_PGID in database '%.*ls' belongs to object '%.*ls', not to object '%.*ls'.

Explanation

This fatal error occurs when Microsoft® SQL Server™ detects database corruption. The second object specified in the text not to object ‘%.*ls’ is probably corrupt. Because this error can mask the existence of other errors, execute DBCC CHECKDB to determine the extent of the damage. If DBCC CHECKDB does not report additional errors, the first object mentioned is not corrupt.

SQL Server detects database corruption when it traverses the pages of an object and finds a page in the chain whose object ID does not match that of the object being accessed. There is probably either a damaged page chain, a corrupt Index Allocation Map (IAM), or an invalid entry in the sysobjects system table for that object. A clustered table has one doubly-linked page chain for the table data as well as one for each index level. A nonclustered index has a page chain for each level of the index. Pages in a heap are not linked. The IAM is used to find the pages of a heap.

Although error 605 usually displays two object names, other variations can occur:

  • If instead of an object name the error displays a number greater than 0, it means that an attempt was made to reference an object ID that does not exist in a system table for that object.
  • If the error reports the first object ID as 0, an unallocated page was probably encountered. (There is no object ID equal to 0.)
  • If the error states that a page belongs to object ALLOCATION, some of the allocation structures used by the database might be corrupted.

Usually this error occurs after the corruption has been written to the database on disk, but it can also occur entirely in cache without the damage ever being written to disk. This is known as a transient 605 error and is not associated with data corruption. If error 605 occurs during data access, but subsequent DBCC CHECKDB statements complete without error, the 605 error was probably transient. Transient 605 errors can be caused by the operating system prematurely notifying SQL Server that an I/O operation has completed; the error message is displayed even though no actual data corruption exists.

Nontransient 605 errors are often caused by hardware or disk device driver failure.

Action

Execute DBCC CHECKTABLE on the second object specified in the error message. To determine the full extent of the corruption, execute DBCC CHECKDB as soon as possible. Also check the error log for other errors, which often accompany a 605 error.

If the 605 error is not transient, the problem is severe and you must run DBCC CHECKDB with one of the repair clauses. If the error involves an index page, use the REPAIR_REBUILD clause. If the error involves a data page, it may be necessary to use the REPAIR_ALLOW_DATA_LOSS clause. In the likely event that you cannot allow the loss of data, you will need to restore from a known clean backup. If the problem persists, contact your primary support provider. Have the output from DBCC CHECKDB available for review.

Important If executing DBCC CHECKDB with one of the repair clauses does not correct the index problem or if you are unsure what effect DBCC CHECKDB with a repair clause has on your data, contact your primary support provider.

In addition, run hardware diagnostics and correct any problems. You might find it beneficial to perform a completely new setup on the computer, including reformatting the disk drives and reinstalling the operating system. This eliminates the possibility that a .Dll or .Exe program is corrupted. You can also examine your operating-system error log to see if the error occurred as the result of hardware failure.

Finally, be sure that your system does not have write caching enabled on the disk controller. If you suspect this to be the problem, contact your hardware vendor.

Additional Information

DBCC CHECKDB offers the REPAIR_REBUILD and REPAIR_ALLOW_DATA_LOSS clauses. The REPAIR_REBUILD clause rebuilds corrupt indexes and the REPAIR_ALLOW_DATA_LOSS clause fixes allocation problems. Sometimes, deleting pages is the only way to fix allocation problems. Typically, these pages contain data that was already deleted, but the pages may contain valid data. Therefore, deleting pages is a more risky option than using DBCC CHECKDB with a repair clause. Using DBCC CHECKDB with a repair clause fixes database corruption when a database backup is not available.

If your database is a data warehouse, you may be able to continue operating without the lost data for some time before reloading the missing data. In these cases, use DBCC CHECKDB with the REPAIR_ALLOW_DATA_LOSS clause to fix the damaged database.

You can prevent problems by following these guidelines:

  1. Run SQL Server only on hardware and controllers that are certified for your operating system.
  2. Perform regular backups in conjunction with DBCC CHECKDB statements. DBCC CHECKDB performs all checks that DBCC NEWALLOC and DBCC CHECKALLOC previously did and DBCC CHECKDB is faster. This is the only way to be confident of the state of the database at the time of the backup.
  3. If the data is critical, frequently back up the transaction log. This makes it possible to reduce your window of vulnerability, even in the event of a catastrophic hardware problem, to an hour or less.
  4. In the most critical situations, use a standby server and a continually running batch job to take transaction backups off of the primary computer and continually restore them on the standby computer.
  5. If you have persistent data corruption problems, try to swap the computer, the controllers, and the disk device drivers for components of a different type. This makes it easier to determine whether the problem is platform-specific.
See Also

Errors 1 - 999


Error 624

Severity Level 21
Message Text

Could not retrieve row from page by RID because the requested RID has a higher number than the last RID on the page. %S_RID.%S_PAGE, Dbid %d

Explanation

This error occurs when an attempt to retrieve a row from a data page by specifying the row ID (RID) failed because the requested RID was a higher number than the last RID on the page. This can happen during normal processing, if the leaf page of a corrupt nonclustered index points to an incorrect or nonexistent RID on a data page.

If the error occurs on a system table during a read-only operation while other users are updating system tables (executing DDL), it is probably a transient 624 error (rather than a corrupted index). To confirm that there is no corruption, execute DBCC CHECKTABLE without a repair clause.

Action

The recovery procedure depends on when the error occurred. If problems persist, the following procedures might not be sufficient to clean up the index corruption. In this case, contact your primary support provider. Have the output from either DBCC CHECKTABLE (if investigating possible system table corruption) or DBCC CHECKDB available for review.

If the error occurred during normal processing

Execute DBCC CHECKTABLE with the REPAIR_REBUILD clause. If executing DBCC CHECKTABLE with the REPAIR_REBUILD clause does not correct the problem, drop and re-create the affected index or indexes.

Important If executing DBCC CHECKDB with the REPAIR_REBUILD clause does not correct the index problem or if you are unsure what effect DBCC CHECKDB with the REPAIR_REBUILD clause has on your data, contact your primary support provider.

Index unknown, query known

The fastest way to resolve this problem is to execute DBCC CHECKDB with the REPAIR_REBUILD clause. This fixes any index corruption in the entire database. If the database is so large that you do not want to run DBCC CHECKDB, use these instructions to locate the specific index to drop and re-create.

If you do not know which index is causing the problem but you do know which query encounters the problem, follow the instructions below. If you do not know the index or the query, follow the instructions under the next section, “Index and query both unknown.”

  1. Determine which index should be dropped by reading the showplan output for the query that encounters the error. If you SET SHOWPLAN_TEXT to ON, SET NOEXEC to ON, and then run the query in question, the output indicates which nonclustered index the query is using to access the table in question.

    For example:

    USE pubs

    GO

    SET SHOWPLAN_TEXT ON

    GO

    SET NOEXEC ON

    GO

    SELECT title

    FROM titles

    WHERE title > 'Cooking'

    GO

Here is the result set:

StmtText

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

SET NOEXEC ON

(1 row(s) affected)

StmtText

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

SELECT title

FROM titles

WHERE title > 'Cooking'

(1 row(s) affected)

StmtText

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

  |--Index Seek(pubs..titles.titleind, SEEK:(titles.title > @1) ORDERED)

(1 row(s) affected)

  2. SET NOEXEC to OFF and SET SHOWPLAN_TEXT TO OFF again:

    SET NOEXEC OFF

    GO

    SET SHOWPLAN_TEXT OFF

    GO

  3. Drop and re-create the index identified in Step 1 (in this example, titleind).
Index and query both unknown

If you do not know the index or the query, rebuild all nonclustered indexes on the table as follows:

  1. Look at the output you created with DBCC CHECKDB when you obtained the table name:
    • If the object ID is less than 100, you cannot drop and re-create the indexes. Do not continue with steps 2 or 3. You must restore the database from a known clean backup.
    • If the object ID is 100 or greater, continue with Step 2.
  2. Use sp_helpindex to list all indexes on the table, and then rebuild all the nonclustered indexes using one of the following methods:
    • Drop and re-create each nonclustered index on the table.
    • If the table has a clustered index, drop and re-create it. This causes all nonclustered indexes to be rebuilt automatically. If your table is large, you might not have the space to do this. Generally, 1.2 times of the size of the table must be available.
  3. After the appropriate index has been re-created, run DBCC CHECKTABLE on the table to confirm that the problem has been resolved.
See Also

Errors 1 - 999


Error 625

Severity Level 21
Message Text

Could not retrieve row from logical page %S_PGID by RID because the entry in the offset table (%d) for that RID (%d) is less than or equal to 0.

Explanation

This error occurs when an object to which this row belongs is corrupt. The corruption was detected during the reading of a specific row from that logical page. This corruption can occur as a result of:

  • Hardware problems, especially problems with the hard drive, controller or hardware write caching.
  • Other corruption in the database.
Action

Execute DBCC CHECKDB to determine the full extent of the corruption. Also check the error log for other errors such as 25xx messages, which often accompany this error.

If DBCC CHECKDB issues other corruption messages, resolve those messages first; that may take care of this error. Execute DBCC CHECKDB with the REPAIR_REBUILD clause to repair the damage.

Important If executing DBCC CHECKDB with the REPAIR_REBUILD clause does not correct the index problem or if you are unsure what effect DBCC CHECKDB with the REPAIR_REBUILD clause has on your data, contact your primary support provider.

If executing DBCC CHECKDB with the REPAIR_REBUILD clause does not resolve all corruption problems, determine which table is corrupt by examining the page in the error message. If the page is associated with an index, you may be able to resolve the problem by dropping and then re-creating the index. If the page is a data page and a clean current backup is available, restore the database from the backup.

If no backup is available, select the table into another table or bulk copy data out of the table, drop the table, re-create it, and then select data back in to the table.

If you suspect a hardware problem, run hardware diagnostics and correct any problems. You might find it beneficial to perform a completely new setup, including reformatting the disk drives and reinstalling the operating system. This eliminates the possibility that a .DLL or .EXE program is corrupted. Also examine the Microsoft® Windows NT™ application log to see if the error occurred as the result of hardware failure.

Finally, be sure that your system does not have write caching enabled on the disk controller. If you suspect this to be the problem, contact your hardware vendor.

See Also

Errors 1 - 999


Error 644

Severity Level 21
Message Text

Could not find the index entry for RID '%.*hs' in index page %S_PGID, index ID %d, database '%.*ls'.

Explanation

This error occurs when the nonclustered index indicated by the index ID is corrupt. The corruption is detected when a process tries to delete a nonexistent row.

Action

Execute DBCC CHECKDB without a repair clause to determine the extent of the damage. Then, execute DBCC CHECKDB with REPAIR_REBUILD clause to correct the damage. If problems persist, either drop and re-create the index (as shown below) or contact your primary support provider.

Important If executing DBCC CHECKDB with the REPAIR_REBUILD clause does not correct the index problem or if you are unsure what effect DBCC CHECKDB with the REPAIR_REBUILD clause has on your data, contact your primary support provider.

To drop and re-create the index:

  1. Record the value of index page and index ID specified in the error text.
  2. Identify which table and index correspond to the index page number.
  3. Note the object ID.

    If the object with the error is a system table (the object ID is less than 100), you cannot drop the index. Execute DBCC CHECKDB with the REPAIR_REBUILD clause or restore the database from a known clean backup.

  4. If the object ID is greater than 100, drop and re-create the index using the table name and index name obtained in Step 1. In most cases, this will clear the corruption.
  5. Execute DBCC CHECKDB with the REPAIR_REBUILD clause on the affected database to verify that all problems have been resolved.

If problems persist, this procedure might not be sufficient to clean up the index corruption. In this case, contact your primary support provider. Have the output from DBCC CHECKDB available for review.

See Also

Errors 1 - 999


Error 701

Severity Level 19
Message Text

There is insufficient system memory to run this query.

Explanation

The memory requirements for the set of tasks Microsoft® SQL Server™ is attempting to perform exceeds the amount of available memory. Either increase the amount of server memory or reduce the server workload.

Action

To decrease the server workload, reduce the number of users currently using SQL Server. To prevent additional users from logging in to SQL Server, pause the server.

To increase server memory:

  1. Check the settings for both min server memory (MB) and max server memory (MB).

    If max server memory (MB) is a value close to the value of min server memory (MB), then increase the max server memory (MB) value.

  2. Check the size of the virtual memory paging file.

    If possible, increase the size of the file.

  3. Shut down any other applications running, if applicable, on the server.
  4. View the current memory usage information in Windows NT Performance Monitor.

    To view current memory usage information in preparation for tuning memory configuration, use the Total Server Memory (KB) Performance Monitor Counter of the SQLServer:General Statistics object.

  5. Add additional memory to the server.
See Also

Errors 1 - 999


Error 813

Severity Level 20
Message Text

Logical page %S_PGID in database ID %d is already hashed.

Explanation

This error occurs when Microsoft® SQL Server™ attempts to hash logical page %S_PGID of database ID%d and the page is already in the SQL Server hash table.

This error usually occurs as a side effect of other data corruption that can usually be detected by executing DBCC CHECKDB without a repair clause.

Action

Review the SQL Server error log, and then execute DBCC CHECKDB with the appropriate repair clause on the database. If the error involves an index page, use the REPAIR_REBUILD clause. If the error involves a data page, it may be necessary to use the REPAIR_ALLOW_DATA_LOSS clause. In the likely event that you cannot allow the loss of data, you will need to restore from a known clean backup. If the problem persists, contact your primary support provider. Have the output from DBCC CHECKDB available for review.

Important If executing DBCC CHECKDB with one of the repair clauses does not correct the index problem or if you are unsure what effect DBCC CHECKDB with a repair clause has on your data, contact your primary support provider.

Verify with your hardware vendor that the disk subsystem being used by SQL Server is at the currently supported and recommended firmware and hardware level.

If DBCC CHECKDB finds no errors, or if errors are found and corrected so that subsequent DBCC statements indicate no errors, but this error reoccurs, contact your primary support provider. Have the SQL Server error logs and the output from DBCC CHECKDB and sp_configure, available for review.

See Also
Errors 1 - 999 | Setting Configuration Options_Setting_Configuration_Options
Reporting Errors to Your Primary Support Provider_Reporting_Errors_to_Your_Primary_Support_Provider | sp_configure_sp_configure


Error 822

Severity Level 21
Message Text

Could not start I/O for request %S_BLKIOPTR.

Explanation

Microsoft® SQL Server™ encountered an error while attempting to initiate a read or write request. This error can occur for any of the following reasons:

  • A database file is off-line.
  • A database file has been removed or renamed.
  • A database file is inaccessible for another reason (such as insufficient permissions).

The parameter in the error message refers to an internal structure and does not help determine which database file is involved. However, other error messages appearing in the error log just before error 822 usually indicate the file involved.

Action

Examine the availability and condition of the file involved using your standard operating-system procedures, and be sure the file is accessible.

Because error 822 marks the database as suspect, SQL Server cannot recover the database upon restarting. If you know that the database was marked suspect because the file was unavailable, you can reset the status of the database to allow recovery to continue.

Caution Do not use these procedures if there are other errors in the error log, near the error 822 message, that suggest that the database might have been marked suspect for some other reason.

Reset the suspect status by executing sp_resetstatus. This is the safest method. After you execute sp_resetstatus, restart SQL Server.

Here are two examples of error 822 and the associated messages from the log. Examining the error messages that occurred just before error 822 usually helps determine the type of problem.

Device missing

In this example, the device C:\Mssql7\data\mydb_data.mdf did not exist when SQL Server started, causing access to the device to fail:

kernel   udopen: Operating system error 2(The system cannot find the file specified.) during the creation/opening of physical device C:\MSSQL7\data\mydb_Data.MDF.

kernel   FCB::Open failed: Could not open device C:\MSSQL7\data\mydb_Data.MDF for virtual device number (VDN) 1.

spid9    Device activation error. The physical file name 'C:\MSSQL7\data\mydb_Data.MDF' may be incorrect.

To correct an error like this, be sure that the virtual device appearing in the error message exists, and correct whatever error prevented SQL Server from finding it. For example, it might have been renamed or moved while SQL Server was not running.

If the virtual device no longer exists, you must restore from known clean backups. Merely creating an empty device with the correct name will not solve this problem.

Permission problems

Permission problems can occur if the device is on an NTFS partition.

In this example, the permissions on C:\MSSQL7\DATA\ MYDB_DATA.MDF were incorrect, so SQL Server could not access it:

kernel   udopen: Operating system error 2(The system cannot find the file specified.) during the creation/opening of physical device C:\MSSQL7\data\mydb_Data.MDF.

kernel: dopen: open "c:\mssql7\data\mydb_data.mdf", Permission denied

kernel   FCB::Open failed: Could not open device C:\MSSQL7\data\mydb_Data.MDF for virtual device number (VDN) 1.

spid9    Device activation error. The physical file name 'C:\MSSQL7\data\mydb_Data.MDF' may be incorrect.

To correct an error like this, change the object ownership for the device to Administrator, and be sure that the account that SQL Server was started under has read and write permissions on the object.

See Also

Errors 1 - 999


Error 823

Severity Level 24
Message Text

I/O error %ls detected during %S_MSG of %S_BUF.

Explanation

Microsoft® SQL Server™ encountered an I/O error on a read or write request made to a device. This error usually indicates disk problems. The parameters in the error message refer to internal structures and don’t often help determine which device is involved. However, additional kernel messages in the error log, recorded before error 823, should indicate which device is involved.

Action

Check the accessibility and condition of the device in question. After you have identified and corrected the problem, execute DBCC CHECKDB to ensure that no other damage was caused by the bad device.

Important If executing DBCC CHECKDB with one of the repair clauses does not correct the index problem or if you are unsure what effect DBCC CHECKDB with a repair clause has on your data, contact your primary support provider.

In addition, run hardware diagnostics and correct any problems.

See Also

Errors 1 - 999


Error 844

Severity Level 10
Message Text

Time out occurred while waiting for buffer latch type %d, bp %#x, page %S_PGID, stat %#x, object ID %d:%d:%d, waittime %d. Continuing to wait.

Explanation

When under a heavy stress load or high I/O conditions, your system may produce this message.

Action

This message can usually be ignored; however, if you receive repeated messages where the wait time increases, it may indicate an internal server problem. Contact your system administrator. The system administrator should check the waittype, waittime, lastwaittype, and the waitresource columns of sysprocesses to see what activities each SPID is performing.

See Also
Errors 1 - 999


Error 845

Severity Level 17
Message Text

Time out occurred while waiting for buffer latch type %d for page %S_PGID, database ID %d, object ID %d, index ID %d.

Explanation

When under a heavy stress load or high I/O conditions, your system may produce this message.

Action

This message can usually be ignored; however, if you receive repeated messages where the wait time increases, it may indicate an internal server problem. Contact your system administrator. The system administrator should check the waittype, waittime, lastwaittype, and the waitresource columns of sysprocesses to see what activities each SPIDs is performing.

See Also
Errors 1 - 999


Error 911

Severity Level 16
Message Text

Could not locate entry in sysdatabases for database '%.*ls'. No entry found with that name. Make sure that the name is entered correctly.

Explanation

This error occurs when attempting to change database context (with a USE statement) to a database that does not exist or when the default database established for a login does not exist. In the latter case, the user login then attempts to access the master database.

Action

To obtain a list of databases, execute sp_helpdb or issuing this query:

SELECT name

FROM master..sysdatabases

The list returned will contain the databases that exist on the Microsoft® SQL Server™ installation. Either create a missing database or connect to an existing one. To correct login-level errors, it may be necessary to execute sp_defaultdb.

See Also

Errors 1 - 999


Error 913

Severity Level 22
Message Text

Could not find database ID %d. Database may not be activated yet or may be in transition.

Explanation

This error can occur if there is a problem with the view resolution process. During execution of various compiled objects in a database that reference the database dbid (such as stored procedures and views), it is a normal process to resolve the dbid with other structures within the database. When a compiled object is first created, the dbid where the object is located is embedded in the compiled code. For example, when a view is accessed or a stored procedure is executed, the rights to access the view or execute the stored procedure are checked.

Action

If the error occurs when a stored procedure or view is accessed, you may be able to correct the problem by simply dropping and re-creating the database object (stored procedure or view).

If this error continues to occur, contact your primary support provider and have the Microsoft® SQL Server™ error log and any additional information relevant to the circumstances when the error occurred available for review.

See Also

Errors 1 - 999


Error 924

Severity Level 14
Message Text

Database '%.*ls' is already open and can only have one user at a time.

Explanation

This error occurs when trying to access a database that is already in use by another user or session. Microsoft® SQL Server™ detected an attempt to access a database that is in single-user mode.

Action

Verify that the database in question is actually in single-user mode by executing this query (substitute your database name for <database>).

sp_helpdb <database>

GO

If the database is truly in single-user mode, the status result set column heading will list single user as the access mode.

To see what login is accessing the database, execute sp_who and scan the dbname result set column heading for the specified database.

If single-user mode privilege is a problem, contact your system administrator and ask to have the single-user mode database option set to multiuser. The system administrator can do so by executing sp_dboption from the master database, as shown here:

sp_dboption database, 'single user', false

See Also

Errors 1 - 999


Error 926

Severity Level 14
Message Text

Database '%.*ls' cannot be opened. It has been marked SUSPECT by recovery. See the SQL Server errorlog for more information.

Explanation

This informational message occurs when an attempt to open or use a database that has a sysdatabases.status column value greater than or equal to 256 and less than 1024.

The database is marked as suspect because it failed the recovery process that brings a database to a consistent transactional state during startup or during the RESTORE DATABASE or RESTORE LOG procedures.

Action

Inspect the Microsoft® SQL Server™ error log and determine the cause of the error. If SQL Server has been restarted since the failed recovery, look at previous SQL Server error logs to see the reason why recovery failed. Correct the underlying problem. If you are unable to resolve this problem, contact your primary support provider. Have the SQL Server error log available for review.

See Also

Errors 1 - 999


Error 1002

Severity Level 16
Message Text

Line %d: Specified scale %d is invalid.

Explanation

This error occurs when the scale of a decimal or numeric column does not fall between the allowable minimum and maximum values based on the precision of the column.

Action

Specify the precision with p, which must be between 1 and the maximum precision, and the scale with s, which must be between 0 and p. If you do not specify the precision, Microsoft® SQL Server™ uses a default precision of 18. If you do not specify the scale, SQL Server uses a default scale of 0.


Error 1105

Severity Level 17
Message Text

Could not allocate space for object '%.*ls' in database '%.*ls' because the '%.*ls' filegroup is full.

Explanation

The specified filegroup has run out of free space.

Action

You can:

  • Free disk space on any disk containing a file in the filegroup mentioned in the 1105 error message. Freeing disk space allows the files in the filegroup to grow.

Or

  1. Free disk space on a different disk drive.
  2. Move the data files in the filegroup with an insufficient amount of free disk space to the disk drive in Step 1.
  3. Detach the database by executing sp_detach_db.
  4. Attach the database by executing sp_attach_db, pointing to the moved files.

Or

  • Either add a data file to the specified database by using the ADD FILE clause of the ALTER DATABASE statement, or enlarge the data file by using the MODIFY FILE clause of the ALTER DATABASE statement, specifying the SIZE and MAXSIZE syntax.
See Also

Errors 1000 - 1999


Error 1203

Severity Level 20
Message Text

Process ID %d attempting to unlock unowned resource %.*ls.

Explanation

This error occurs when Microsoft® SQL Server™ is engaged in some activity other than normal post-processing cleanup and it finds that a particular page it is attempting to unlock is already unlocked. The underlying cause for this error may be related to structural problems within the affected database. SQL Server manages the acquisition and release of pages to maintain concurrency control in the multiuser environment. This mechanism is maintained through the use of various internal lock structures that identify the page and the type of lock present. Locks are acquired for processing of affected pages and released when the processing is completed.

Action

Execute DBCC CHECKDB against the database in which the object belongs. If DBCC CHECKDB reports no errors, attempt to reestablish the connection and execute the command.

Important If executing DBCC CHECKDB with one of the repair clauses does not correct the index problem or if you are unsure what effect DBCC CHECKDB with a repair clause has on your data, contact your primary support provider.

See Also

Errors 1000 - 1999


Error 1204

Severity Level 19
Message Text

SQL Server has run out of LOCKS. Rerun your statement when there are fewer active users, or ask the system administrator to reconfigure SQL Server with more LOCKS.

Explanation

This error occurs when there are not enough system locks to complete the current command.

Action

Either execute the command again, when activity on the server is low, or have the system administrator increase the number of locks by executing sp_configure from the master database.

To view the current configuration:

sp_configure locks

GO

This reports the minimum, maximum, current run, and configuration values. To increase the number of locks, run sp_configure again, specifying the number of locks to be configured. For example, to configure 10,000 locks:

sp_configure locks, 10000

GO

RECONFIGURE WITH OVERRIDE

GO

Stop and restart Microsoft® SQL Server™ so the changes can take effect. Locks are allocated at system startup.

If the number of locks cannot be increased at the current time, and the single action requires more locks than the server is currently configured for, you may be able to reduce the number of locks required for the operation. For example, try the following:

  • For large UPDATE statements, break the updates into smaller units that will affect only a subset of records at a time. For example, you could use the primary key, changing the single UPDATE statement from:

    UPDATE employees

    SET salary = salary * 1.05

    WHERE employee_id BETWEEN 1000 AND 9999

    GO

to several UPDATE statements:

UPDATE employees

SET salary = salary * 1.05

WHERE employee_id BETWEEN 1000 AND 4999

GO

UPDATE employees

SET salary = salary * 1.05

WHERE employee_id BETWEEN 5000 AND 9999

GO

  • For a maintenance type of task or for a global update, consider putting the database into single-user mode (if it is feasible to keep other users out of the database). Single-user mode does not set locks, so you will not run out of locks, and the operation will run somewhat faster (because you save the locking overhead).
  • For a large bcp operation, the entire operation is treated as a single transaction. When you use the batch parameter (-b), bcp will treat the operation in small transactions with the number of rows specified. At the end of each small transaction, the system resources held by that transaction are freed, so fewer locks are needed.
See Also

Errors 1000 - 1999


Error 1205

Severity Level 13
Message Text

Your transaction (process ID #%d) was deadlocked with another process and has been chosen as the deadlock victim. Rerun your transaction.

Explanation

This error occurs when Microsoft® SQL Server™ encounters a deadlock. A deadlock occurs when two (or more) processes attempt to access a resource that the other process holds a lock on. Since each process has a request for another resource, neither process can be completed. When a deadlock is detected, SQL Server rolls back the command that has the least processing time and returns this error message 1205 to the client application. This error is not “fatal” and may not cause the batch to be terminated.

Action

In some instances, a deadlock condition will cause a DB-Library function (such as dbsqlexec, dbsqlok, dbresults, or dbnextrow) to return FAIL. It is always the responsibility of the program to check the return codes from each DB-Library function. If FAIL is returned by one of these DB-Library functions, the program should cancel the batch and not attempt to continue. In some cases, it is possible to continue execution of subsequent functions in the batch. However, because a deadlock situation occurred and the functions that caused it were rolled back, later functions in the batch will probably fail with a more serious error, such as “object not found.”

In other instances, a deadlock condition will not cause a DB-Library function to return FAIL. In these cases, the program must check for error message 1205 in the message handler and use the dbsetuserdata function to communicate this to the application The program must then check for the deadlock indicator after every DB-Library call and should cancel the batch if a deadlock is detected.

While it may seem unnecessary to cancel a batch after receiving a 1205 deadlock message, it is necessary because the server does not always terminate the batch in a deadlock situation. If the batch is not canceled, any attempt to submit a new batch can result in a DB-Library error 10038 “Results Pending.”

You can also use the SET DEADLOCK_PRIORITY statement (LOW or NORMAL). SET DEADLOCK_PRIORITY controls how the session reacts when in a deadlock situation. If set to LOW, the process will be the preferred victim of a deadlock situation. If set to NORMAL, the session will use the default deadlock-handling method.

If a deadlock situation continues, it is often useful to use trace flag 1204 to gather more information. Trace flag 1204 prints out the deadlock chains and victim, as shown in this sample output:

*** Deadlock Detected ***

 ==> Process 7 chosen as deadlock victim

 == Deadlock Detected at: 1998-09-10 16:39:29.17

 == Session participant information:

 SPID: 7 ECID: 0 Statement Type: UPDATE

 Input Buf: update t1 set c1 = c1  where  c1 = 2

 SPID: 8 ECID: 0 Statement Type: UPDATE

 Input Buf: update t1 set c1 = c1  where  c1 = 1

 == Deadlock Lock participant information:

 == Lock: KEY: 2:117575457:1 (010001000000)

 Database: tempdb

 Table: t1

 Index: i1

  - Held by: SPID 7 ECID 0 Mode "S"

  - Requested by: SPID 8 ECID 0 Mode "X"

 == Lock: KEY: 2:117575457:1 (020002000000)

 Database: tempdb

 Table: t1

 Index: i1

  - Held by: SPID 8 ECID 0 Mode "S"

  - Requested by: SPID 7 ECID 0 Mode "X"

This deadlock information can be interpreted as follows:

  • The first section displays the deadlock victim and time of deadlock along with the sessions involved in the deadlock. For each session, the current SPID, statement type, and a portion of the input buffer is displayed.
  • The second section displays details about the locks involved in the deadlock. From the output above, note that the deadlock involves key locks on table t1, index i1. The deadlock output shows which processes own the locks involved in the deadlock and which sessions are waiting for the locks to be granted as well as the associated lock modes.
  • The process that has generated the least amount of log volume will, by default, be chosen as the deadlock victim and be rolled back automatically. To influence which session is rolled back, set the DEADLOCK_PRIORITY for a session.
See Also

Errors 1000 - 1999


Error 1505

Severity Level 14
Message Text

CREATE UNIQUE INDEX aborted because a duplicate key was found. Most significant primary key is '%S_KEY'.

Explanation

This error occurs when you attempt to create a unique index and more than one row contains the duplicate value. Microsoft® SQL Server™ has detected a uniqueness violation and cancels the CREATE INDEX operation.

For example, the creation for the index below would be canceled due to the uniqueness violation at row 3. The BUCHANAN STEVEN combination is already located in row 1.

TABLE:     tblTest

Row      strLastName     strFirstName    strCity        strState

1        BUCHANAN        STEVEN          BOISE          ID

2        SUYAMA          MICHAEL         BUTTE          MT

3        BUCHANAN        STEVEN          SEATTLE        WA

4        DAVOLIO         NANCY           SAN FRANCISCO  CA

CREATE UNIQUE NONCLUSTERED INDEX

idxUniqueNames ON

tblText(strLastName, strFirstName)

Action

You must review your index objective. If your index does not need to be unique, remove the UNIQUE keyword and reissue the CREATE INDEX statement. However, if you still want to create a unique index, you must query the table in question and remove the rows in error.

To find the duplicate rows, issue a GROUP BY statement:

SELECT * FROM tblTest

GROUP BY strLastName, strFirstName

See Also
Errors 1000 - 1999


Error 1508

Severity Level 14
Message Text

CREATE INDEX aborted because a duplicate row was found. Primary key is '%S_KEY'.

Explanation

This error occurs when you attempt to create a clustered index and a duplicate row is encountered in the table.

The following example produces error 1508 when the index creation process reaches row 3, which is an exact duplicate of row 1:

TABLE:     tblTest

Row      strLastName     strFirstName    strCity        strState

1        BUCHANAN        STEVEN          BOISE          ID

2        SUYAMA          MICHAEL         BUTTE          MT

3        BUCHANAN        STEVEN          BOISE          ID

4        DAVOLIO         NANCY           SAN FRANCISCO  CA

CREATE CLUSTERED INDEX

idxClusteredName ON

tblText(strLastName)

Action

You must decide whether to allow or prevent duplicate rows in the table. To allow duplicate rows, you should add the ALLOW_DUP_ROW keyword to the CREATE INDEX statement. Be cautious when using IGNORE_DUP_ROW, because it physically removes duplicate data from the table. Also note that when creating clustered indexes, the amount of space required can be 120 percent to 150 percent of the original table size.

The following example creates the clustered index while allowing the duplicate rows to remain in the table:

CREATE CLUSTERED INDEX

idxClusteredName ON

tblText(strLastName)

WITH ALLOW_DUP_ROW

See Also
Errors 1000 - 1999


Error 1510

Severity Level 17
Message Text

Sort failed. Out of space or locks in database '%.*ls'.

Explanation

This error occurs when you attempt to create an index and there is not enough space in the database to complete the operation or no more locks are currently available.

Creating indexes can require 1.2 times the original table size when building a clustered index (this amount is in addition to the table size–but just during the time that CREATE INDEX is processing). This space must be available in the indicated database or in the segment on which you were attempting to create the index.

Action

When there is not enough space in the database, you may be able to select a specific filegroup on which to place the index. To locate a specific filegroup and to check the size available on the filegroup, execute sp_helpfilegroup:

sp_helpfilegroup 'PRIMARY'

Or use the ALTER DATABASE statement to increase the overall database size. Note that after you increase the size of the database, you may not be allowed to decrease the size.

If your database has no more locks available, execute sp_configure to increase the number of locks. This example increases the amount of locks to 10,000:

sp_configure 'locks', 10000

GO

RECONFIGURE

GO

For the configuration option to take effect, stop and restart the Microsoft® SQL Server™ service. For user convenience, you may want to pause the service and allow current user activity to gracefully finish before officially stopping the service.

See Also

Errors 1000 - 1999


Error 1530

Severity Level 16
Message Text

CREATE INDEX with DROP_EXISTING was aborted because a row was out of order. Most significant offending primary key is '%S_KEY'. Explicitly drop and create the index instead.

Explanation

This error occurs when you try to create an index using the DROP_EXISTING clause of the CREATE INDEX statement on a column or columns containing data that is not in sorted order. When this error occurs, no index is created.

The DROP_EXISTING clause speeds creation of an index when the data in the table is already in sorted order. The space required to build a clustered index is less when the DROP_EXISTING clause is used.

The DROP_EXISTING clause speeds index creation only for clustered indexes or unique nonclustered indexes. Creating a nonunique, nonclustered index with the DROP_EXISTING clause may succeed, but there is no improvement in performance.

Action

Use either of these strategies:

  • Execute CREATE INDEX with the DROP_EXISTING clause.
  • Drop and re-create the index without any clauses.

You can also use the SORTED_DATA_REORG clause, which physically reorganizes the data.

See Also
Errors 1000 - 1999


Error 1702

Severity Level 16
Message Text

CREATE TABLE failed because column '%.*ls' in table '%.*ls' exceeds the maximum of %d columns.

Explanation

This error occurs when you try to create a table with more than 1,024 columns. The maximum number of definable columns per table is 1,024.

Column names must follow the rules for identifiers. They must be unique within a given table, but you can use the same column name in different tables in the same database.

Action

Reduce the number of columns in the table to 1,024 or less.

See Also

Errors 1000 - 1999


Error 1803

Severity Level 17
Message Text

CREATE DATABASE failed. Could not allocate enough disk space for a new database on the named disks. Total space allocated must be at least %d MB to a accommodate copy of the model database.

Explanation

This error occurs when there is not enough space on the device to create the tempdb database.

Action

The procedure for handling this error depends on whether the error occurred on a user database or on tempdb.

If the error occurred on a user database
  • Create the database on a different disk.

Or

  • Delete some files to free space on the disk.
If the error occurred on tempdb

If you moved tempdb from one device back to any default device and you don’t have enough space on the device (2 MB), Microsoft® SQL Server™ will attempt to create tempdb on another device. If you do not have a device with at least 2 MB free, SQL Server will not start. Start SQL Server using the -f minimum configuration option.

You can create a new device with at least 2 MB or free at least 2 MB on the device. If you create a new device, make sure it is specified as a default device, as in this example:

sp_diskdefault new_device_name, defaulton

If no default is specified, SQL Server sends an “out of memory” message (you can ignore this message) and then moves tempdb to RAM automatically.

See Also
Errors 1000 - 1999


Error 1814

Severity Level 10
Message Text

Could not create tempdb. If space is low, extend the amount of space and restart.

Explanation

This error occurs when there is not enough space on the device to create the tempdb database.

Action

You can create a new device with at least 2 MB or free at least 2 MB on the device. If you create a new device, make sure it is specified as a default device, as in the following example:

sp_diskdefault new_device_name, defaulton

If no default device is specified, Microsoft® SQL Server™ sends an “out of memory” message (you can ignore this message) and then moves tempdb to RAM automatically.

See Also

Errors 1000 - 1999


Error 1902

Severity Level 16
Message Text

Cannot create more than one clustered index on table '%.*ls'. Drop the existing clustered index '%.*ls' before creating another.

Explanation

This error occurs when a table can have only one clustered index, but it can have many nonclustered indexes. Microsoft® SQL Server™ uses the clustered index to sort rows so that their physical order is the same as their logical (indexed) order. The bottom (leaf level) of a clustered index contains the actual data pages of the table.

In a nonclustered index, the physical order of the rows is not the same as the indexed order. In a nonclustered index, the bottom (leaf level) contains pointers to rows on data pages, which creates an extra level between the index structure and the data itself.

Action

Use the sp_helpindex system stored procedure to examine the existing indexes on the table. If a clustered index already exists, you must drop it before creating another clustered index.

See Also

Errors 1000 - 1999


Error 1903

Severity Level 16
Message Text

%d is the maximum allowable size of an index. The composite index specified is %d bytes.

Explanation

This error occurs when the sum of the lengths of the columns that make up the composite index exceeds 900 bytes.

A composite index is an index that uses from 2 to 16 columns. For example, the following shows a composite index using objects from the Northwind database:

USE Northwind

GO

CREATE INDEX CompanyNameCity

ON Customers (CompanyName, City)

GO

In this example, CompanyName is defined as nvarchar(40) and City as nvarchar(15). Each character requires 2 bytes of storage, so the total length of this composite index is 110 bytes (2* (40 + 15)). Note that when using varchar columns, the index will assume the maximum length of the varchar column to calculate the length of the composite index.

Action

Examine the lengths of the columns in your composite index and make sure that the total does not exceed 900 bytes.

See Also

Errors 1000 - 1999


Error 1904

Severity Level 16
Message Text

Cannot specify more than %d column names for index key list. %d specified.

Explanation

This error occurs when more than 16 columns are used to create a composite index. A composite index is an index that uses from 2 to 16 columns.

The following example shows a composite index using objects from the pubs database:

USE pubs

GO

CREATE INDEX idxPubNameCity

ON publishers (pub_name, city)

GO

Action

Modify the CREATE INDEX statement to use no more than 16 columns.

See Also
Errors 1000 - 1999


Error 1910

Severity Level 16
Message Text

Cannot create more than %d indexes or column statistics on one table.

Explanation

This error occurs when either:

  • A table already has 250 indexes.

Or

  • A table has a large number of indexes, and statistics are either being created or updated. Microsoft® SQL Server™ makes an entry in sysindexes for each set of column-level statistics that are either created or updated, if the base column does not already have an index.

The following example produces this error message by updating statistics on a table with 250 indexes:

USE pubs

GO

IF EXISTS(SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES

        WHERE TABLE_NAME = 'TestCols')

    DROP TABLE TestCols

GO

DECLARE @counter int, @stmt varchar(255)

SET @counter = 1

CREATE TABLE TestCols

 (

  c1 int IDENTITY(1, 1),

  c2 char(255)

 )

-- Creating 250 indexes.

WHILE (@counter < 251)

    BEGIN

        IF (@counter = 1)

            CREATE UNIQUE CLUSTERED INDEX Ind1 ON TestCols (c1)

        ELSE

        BEGIN

            SELECT @stmt = 'CREATE INDEX t1Ind' + LTRIM(STR(@counter)) +

                ' ON TestCols (c1)'

            EXEC (@stmt)

        END

        SET @counter = @counter + 1

    END

-- Updating Statistics. Returns error 1910.

UPDATE STATISTICS TestCols (c2) WITH COLUMNS, FULLSCAN

Action

Either:

  • Modify the CREATE INDEX statement to use no more than 250 indexes.

Or

  • Remove any unused, nonclustered indexes to create or update statistics successfully.
See Also

Errors 1000 - 1999


Error 1916

Severity Level 16
Message Text

CREATE INDEX options %ls and %ls are mutually exclusive.

Explanation

This error occurs when you attempt to create an index with two mutually exclusive CREATE INDEX statement clauses. The index is not created when this error occurs.

This table shows when to use the CREATE INDEX clauses:

Index type | Clause
Unique clustered | IGNORE_DUP_KEY
Nonclustered | None
Unique nonclustered | IGNORE_DUP_KEY

Action

Select the correct clauses for the CREATE INDEX statement.

See Also

Errors 1000 - 1999


Error 2501

Severity Level 16
Message Text

Could not find table named '%.*ls'. Check sysobjects.

Explanation

This error is usually caused by some form of corruption in the database. This often happens when a table is being dropped and a serious error occurs that causes the drop to fail.

Action

Executing DBCC CHECKDB and DBCC CHECKCATALOG can indicate other problems in the database. Restore your database from backup or contact your primary support provider for assistance.

You may also be able to use bcp to copy out other tables. But because this problem is often caused by other problems in the database, problems can occur when you copy out other tables.

See Also

Errors 2000 - 2999


Error 2511

Severity Level 16
Message Text

Table Corrupt: Object ID %d, Index ID %d. Keys out of order on page %S_PGID, slots %d and %d.

Explanation

This error occurs when an index is not ordered correctly. The %S_PGID variable can be a data page (for clustered indexes), an index page, or a leaf page.

Action

The fastest way to resolve this problem is to execute DBCC CHECKDB with the REPAIR_REBUILD clause. This fixes any index corruption in the entire database. If the database is so large that you do not want to run DBCC CHECKDB, use these instructions to locate the specific table that is corrupt. Then, execute DBCC CHECKTABLE with the REPAIR_REBUILD clause for that table.

Important If executing DBCC CHECKDB or DBCC CHECKTABLE with the REPAIR_REBUILD clause does not correct the index problem or if you are unsure what effect either of these DBCC statements with the REPAIR_REBUILD clause has on your data, contact your primary support provider.

Follow these steps:

  1. Note the object ID.
  2. If the object with the error is not a system table (its object ID is more than 100), continue with the next step.

    If the object with the error is a system table (its object ID is less than 100), you cannot drop the index. Restore the database from a known clean backup.

  3. Find the name of the index involved, as follows:

    USE master

    GO

    SELECT name

    FROM sysindexes

    WHERE indid = index_id

    AND id = object_id

  4. Drop and re-create the index.
  5. Run DBCC CHECKTABLE on the affected table to verify that all problems have been resolved at the table level.

If problems persist, contact your primary support provider. Have the output from either DBCC CHECKDB or DBCC CHECKTABLE available for review.

See Also

Errors 2000-2999


Error 2513

Severity Level 16
Message Text

Table Corrupt: Object ID %ld (object '%.*ls') does not match between '%.*ls' and '%.*ls'.

Explanation

This error occurs when the DBCC CHECKCATALOG statement deletes a database object in one system table and this is not expected in another. Most often, this occurs when one or more rows in the syscolumns, syscomments, sysindexes, or sysdepends tables have no corresponding rows in sysobjects. This error can also occur if an operation affecting the system table, such as deletion of a user table, was interrupted.

Action

Although this error seldom interferes with database use, it is a good idea to restore the affected system table.

Warnings Severe problems can result from the direct manipulation of the system catalogs. Do not modify the system catalogs unless instructed to do so by your primary support provider.

Follow these steps to restore the consistency of the system tables:

  1. Display the offending rows by executing a query in the problem database against the two tables mentioned in the message. For example, if the message reports one or more mismatches between syscolumns and sysobjects:

    USE master

    GO

    SELECT * FROM syscolumns

    WHERE syscolumns.id NOT IN

    (SELECT sysobjects.id FROM sysobjects)

  2. Enable updates to system tables by enabling the allow updates configuration option.

    Before modifying any system catalogs, be sure that you have a valid backup of the database.

    Warning Incorrect modification of the system catalogs can result in database corruption or data loss.

  3. Make sure that the rows displayed in Step 1 correspond to reported 2513 errors, and then delete them from the first table mentioned in the message text.
  4. If the number of rows affected by the delete does not match the number found in Step 1, roll back the transaction. If the numbers match, commit it.
  5. To confirm that the mismatches are fixed, reexecute DBCC CHECKCATALOG. Then, disable the allow updates configuration option.
See Also

Errors 2000-2999


Error 2535

Severity Level 16
Message Text

Table Corrupt: Page %S_PGID is allocated to object ID %d, index ID %d, not to object ID %d, index ID %d found in page header.

Explanation

The DBCC CHECKALLOC statement detected a mismatch in the object ID between an allocation structure (extent) and sysindexes.

Note Occasionally, DBCC CHECKALLOC reports this error when no real error condition exists. Execute DBCC CHECKALLOC in single-user mode if you suspect the 2535 error is incorrect.

Action

Follow these steps:

  1. Examine the index ID associated with the page number in the message to determine whether the error occurred on the table data or on an index.
  2. Restore the database:
    • If the object ID is less than or equal to 100, the error is on a system table. Restore the database from a clean backup.
    • If the object ID is greater than 100, the error is on a user table.
    • If this error occurs on table data (the index ID = 1), restore the database from a clean backup.
    • If the error occurs on an index, you can usually correct it by dropping and re-creating the index. If dropping and re-creating the index is not feasible, or if you cannot drop the index, contact your primary support provider for assistance.

If the problem persists, contact your primary support provider for assistance. Have the output of the appropriate DBCC statements available for review.

See Also

Errors 2000-2999


Error 2601

Severity Level 14
Message Text

Cannot insert duplicate key row in object '%.*ls' with unique index '%.*ls'.

Explanation

This error occurs when you attempt to put duplicate index values into a column or columns that have a unique index. Microsoft® SQL Server™ does not allow two rows to have the same index value (including NULL) in columns that have a unique index. SQL Server checks for duplicate values when the index is created and each time the table is modified using the INSERT or UPDATE statement.

Action

If you need duplicate index values in the indexed column(s), drop the unique index and create a nonunique index.

To use a unique index on data that contains duplicate values, you must change some values to prevent the duplication. You can change the data already in the table by using the SELECT or UPDATE statement, or you can change the data to be inserted.

See Also

Errors 2000-2999


Error 2750

Severity Level 16
Message Text

Column or parameter #%d: Specified column precision %d is greater than the maximum precision of %d.

Explanation

This error occurs when the precision of a float, decimal, or numeric column exceeds the maximum value for the specified data type.

For decimal and numeric data types, Microsoft® SQL Server™ normally supports a maximum precision of 28 digits for compatibility with various front ends, such as Microsoft Visual Basic®. However, if a precision greater than 28 is desired, use the /p parameter of the sqlservr application from a Win32® command prompt.

Action

Define the column to have a precision that falls within the allowable precision range for that data type.


Error 2751

Severity Level 16
Message Text

Column or parameter #%d: Specified column scale %d is greater than the specified precision of %d.

Explanation

This error occurs when the scale of a decimal or numeric column exceeds the precision value for that column.

For decimal and numeric data types, Microsoft® SQL Server™ normally supports a maximum precision of 28 digits for compatibility with various applications. However, if a precision greater than 28 is desired, use the /p parameter of the sqlservr application from a Win32® command prompt.

Action

Specify the precision with p, which must be between 1 and the maximum precision, and the scale with s, which must be between 0 and p. If you do not specify the precision, SQL Server uses a default precision of 18. If you do notspecify the scale, SQL Server uses a default scale of 0.

See Also

Errors 2000-2999


Error 2812

Severity Level 16
Message Text

Could not find stored procedure '%.*ls'.

Explanation

An attempt was made to execute a stored procedure that does not exist. If the procedure does exist (it appears when sp_help is run with no parameters), the error might have occurred because you did not fully qualify the procedure name. If the procedure is not owned by the user attempting to execute it, and it is not owned by the database owner (dbo), all references to it must include the owner name. For example, suppose user1 creates a procedure called proc1. Any users must add the owner name before the procedure name, as shown in the following example:

EXECUTE user1.proc1

Naming conventions for database objects are as follows:

[[[server_name.][database_name].][owner_name].]object_name

The default value for database_name is the current database; the default value for owner_name is the current user. If the current user is not the owner, the current user must specify the owner name when using the procedure. Because the owner name is part of the object name, two different users can have procedures with the same object name in the same database (for example user1.proc1 and user2.proc1).

The only exceptions to this naming convention are system procedures, which can be executed from any database. System procedures reside in the master database, are owned by the system administrator, and have names that begin with sp_. System procedures reference the system tables for the current database.

Action

If you do not know who owns the procedure, use sp_help to display the owner. If you run sp_help without any parameters, it displays objects owned by other users. To determine which procedures exist in a database and who owns them, use the following:

USE master

GO

SELECT name,owner = USER_NAME(uid)

FROM sysobjects

WHERE type = 'P'

GO

If the procedure does not appear in the output of this query, the procedure is either in a different database or does not exist.

If you do not own the procedure in question, you can avoid error 2812 by qualifying the procedure name with the owner name, as shown in the following example:

EXECUTE user1.proc1

For procedures used by many users of a database, it is usually easiest if the dbo creates the procedure. This allows any user to find the procedure without specifying an owner name.

If the procedure is not in the database where it is executed, you can avoid this error by fully qualifying the procedure name with the database name, as shown in the following example:

EXECUTE database_1.user1.proc1

The owner name is not needed if you or the dbo own the procedure. For example:

EXECUTE database_1..proc1

Execute permission must be provided so that other users can execute this procedure, but no permissions are required to see the text of the procedure.

If this error occurs on system procedures, it might be resolved by running INSTMSTR.SQL. This reinstalls all system procedures and initializes various other structures.

See Also

Errors 2000-2999


Error 3023

Severity Level 16
Message Text

Backup, CHECKALLOC, bulk copy, SELECT INTO, and file manipulation (such as CREATE FILE) operations on a database must be serialized. Reissue the statement after the current backup, CHECKALLOC, or file manipulation operation is completed.

Explanation

These operations may not be performed at the same time as a backup operation:

  • File management operations such as the ALTER DATABASE statement with either the ADD FILE or REMOVE FILE clauses; INSERT, UPDATE, or DELETE statements.
  • Shrink database or shrink file.
  • CREATE INDEX.
  • Nonlogged operations such as bulk load, SELECT INTO, WRITETEXT, and UPDATETEXT. The database option select into/bulkcopy must be enabled for these operations to be nonlogged.

If a backup is started when one of these operations is in progress, the backup ends. If a backup is running and one of these operations is attempted, the operation fails.

Action

Reissue the operation after the conflicting operation has completed.

See Also

Errors 3000-3999


Error 3036

Severity Level 16
Message Text

Database '%ls' is in warm-standby state (set by executing RESTORE WITH STANDBY) and cannot be backed up until the entire load sequence is completed.

Explanation

Your standby database has not been recovered and may not be backed up. Usually, you recover this database only if your primary fails and you switch operations to the standby. Until this occurs, rely on backups taken from the primary server.

See Also

Errors 3000-3999


Error 3101

Severity Level 16
Message Text

Database in use. The system administrator must have exclusive use of the database to run the restore operation.

Explanation

This error occurs when you attempt to load a database backup while users are accessing the database. You cannot use the RESTORE DATABASE statement while the database is in use by any user, including yourself.

Action

Wait until all users have finished using the database, and then use the RESTORE DATABASE statement. Make sure that you are not in the database being loaded when you issue the RESTORE DATABASE command. Although not required, it is best to run the RESTORE DATABASE statement from the master database.

See Also

Errors 3000-3999


Error 3120

Severity Level 16
Message Text

The database you are attempting to restore was backed up under a different sort order ID (%d) than the one currently running on this server (%d), and at least one of them is a non-binary sort order.

Explanation

This error occurs when attempting to restore a database with a different sort order from that of the backed up database. This error occurs when using any sort order except binary sort order.

A database cannot be restored into Microsoft® SQL Server™ using RESTORE DATABASE unless these items match between the database and the server:

  • Sort order
  • Collation sequence
  • Unicode locale ID
  • Unicode comparison style

Important SQL Server does not support concurrent mixed sort orders. Only the same sort order can be used by both the server and data to be imported or restored.

Action

Change the mismatched items to be the same.

For example, if the database uses sort order x and the backup to load uses sort order y, then use either bcp, BULK INSERT, or Data Transformation Services (DTS) to save the database in the x sort order. Then, reinstall SQL Server. After reinstalling SQL Server, load the database with the y sort order. Finally, use either bcp, BULK INSERT, or DTS to restore the data with the x sort order.

See Also
Errors 3000-3999 Error 3149


Error 3143

Severity Level 16
Message Text

The data set on device '%ls' is not a SQL Server backup set.

Explanation

The backup being restored conforms to the Microsoft Tape Format, but is not a Microsoft® SQL Server™ backup. The backup may have been written by another software product.

Action

To determine the contents of the backup, consider using RESTORE HEADERONLY.

See Also

Errors 3000-3999


Error 3149

Severity Level 16
Message Text

The database you are attempting to restore was backed up under a different Unicode locale ID (%d) or Unicode comparison style (%d) than the Unicode locale ID (%d) or Unicode comparison style (%d) currently running on this server.

Explanation

This error occurs when attempting to restore a database with a different sort order from that of the backed up database. This error occurs when using any sort order except binary sort order.

A database cannot be restored using RESTORE DATABASE unless these items match between the database and the server:

  • Sort order
  • Collation sequence
  • Unicode locale ID
  • Unicode comparison style

Important Microsoft® SQL Server™ does not support concurrent mixed sort orders. Only the same sort order can be used by both the server and data to be imported or restored.

Action

Change the mismatched items to be the same.

For example, if the database uses sort order x and the backup to load uses sort order y, then use either bcp, BULK INSERT, or Data Transformation Services (DTS) to save the database in the x sort order. Then, reinstall SQL Server. After reinstalling SQL Server, load the database with the y sort order. Finally, either bcp, BULK INSERT, or DTS to restore the data with the x sort order.

See Also
Errors 3000-3999 Error 3120


Error 3154

Severity Level 16
Message Text

The backup set holds a backup of a database other than the existing '%ls' database.

Explanation

The backup set is a backup of a database with the same name as the database to which you are restoring. However, the database being restored was created by a different CREATE DATABASE statement than the database in the backup set. Even though the databases have the same name, they are in fact different databases.

Action

Either overwrite the existing database by reissuing the RESTORE DATABASE command using the WITH REPLACE clause, or restore the backup set to a different database name. If you restore the backup set to a different database name, ensure that the files that will be created do not already exist and are not being used by another database. If you chose the wrong backup set to restore, select a backup of the existing database and restore it.

See Also

Errors 3000-3999


Error 3155

Severity Level 16
Message Text

The RESTORE operation cannot proceed because one or more files have been added or dropped from the database since the backup set was created.

Explanation

You must begin the restore sequence by restoring a full database backup created after files were added or removed from the database. You may not roll forward across file creation or deletion operations.

See Also

Errors 3000-3999


Error 3206

Severity Level 16
Message Text

No entry in sysdevices for backup device '%.*ls'. Update sysdevices and rerun statement.

Explanation

You have attempted to use a logical device that is not a backup device.

Action

Either define the device using sp_addumpdevice, or refer to the physical device directly by specifying the TAPE = or DISK = syntax of the BACKUP statement.

See Also
Errors 3000-3999 Error 3209


Error 3209

Severity Level 16
Message Text

'%.*ls' is not a backup device. Check sysdevices.

Explanation

You have attempted to use a logical device that is not a backup device.

Action

Either define the device using sp_addumpdevice, or refer to the physical device directly by specifying the TAPE = or DISK = syntax of the BACKUP statement.

See Also
Errors 3000-3999 Error 3206


Error 3227

Severity Level 16
Message Text

The volume on device '%ls' is a duplicate of stripe set member %d.

Explanation

The media family spans multiple volumes. The restore operation has already processed the data on the volume specified in the error message.

Action
  • Remove the volume and insert the next volume which has not yet been processed.
See Also

Errors 3000-3999


Error 3242

Severity Level 16
Message Text

The file on device '%ls' is not a valid Microsoft Tape Format backup set.

Explanation

The backup device does not contain data in Microsoft Tape Format.

Either:

  • The contents of the device were not written by the BACKUP statement.
  • The device contains a Microsoft® SQL Server™ version 6.x database dump. SQL Server 7.0 cannot restore backups from earlier versions of SQL Server.
  • The contents of the device have been damaged.
See Also

Errors 3000-3999


Error 3247

Severity Level 16
Message Text

The volume on device '%ls' has the wrong media sequence number (%d). Remove it and insert volume %d.

Explanation

The media family spans multiple volumes. The restore operation expected to process the volume specified in the error message, but found a different volume value instead.

Action

Remove the specified volume and insert the volume with the requested value.

See Also

Errors 3000-3999


Error 3249

Severity Level 16
Message Text

The volume on device '%ls' is a continuation volume for the backup set. Remove it and insert the volume holding the start of the backup set.

Explanation

The media family spans multiple volumes. The backup set to be processed by the restore operation starts on an earlier volume than the one inserted into the named device.

Action

Remove the volume and insert the volume containing the start of the target backup set. To determine which backup sets are contained on which volumes, use RESTORE HEADERONLY.

See Also

Errors 3000-3999


Error 3251

Severity Level 10
Message Text

The RAID stream on device '%ls' has been finished. The device will now be re-used for one of the remaining RAID streams.

Explanation

The restore operation allows a media set to be restored with fewer physical devices than was used to create it (also known as backing it up). This message means that the restore operation has completely processed the media family on the named device, and is now ready to reuse the device to restore one of the remaining media families.

Action

Remove the volume from the named device and insert the first volume of a media family that has not yet been processed.

See Also

Errors 3000-3999


Error 3256

Severity Level 16
Message Text

The backup set on device '%ls' was aborted while it was being created and is incomplete. RESTORE sequence is terminated abnormally.

Explanation

The BACKUP operation that created the backup set did not finish successfully. You may only restore backup sets that were created successfully. For example, the backup may have been terminated with an attention message. The backup set is not complete, and the restore operation must terminate.

Action

If you were restoring a database backup, restore a different database backup, and use log backups to roll forward. If you were restoring a log backup, apply the next log backup, the log backup made following the incomplete backup, instead.

See Also

Errors 3000-3999


Error 3258

Severity Level 16
Message Text

The volume on device '%ls' belongs to a different media set.

Explanation

The volume on the named device does not belong to the same RAID media set as the other volumes being processed.

Action

For tape media sets, remove the offending volume and insert the next volume of the media family.

For disks, reissue the command. Name only those backup devices that were part of the same RAID media set.

See Also

Errors 3000-3999


Error 3263

Severity Level 10
Message Text

Cannot use the volume on device '%ls' as a continuation volume. It is sequence number %d of family %d for the current media set. Insert a new volume, or sequence number %d of family %d for the current set.

Explanation

The RAID media set spans multiple volumes. Initializing the volume currently in the named device would destroy the integrity of the RAID media set because the volume has already been used as a member of the media set.

Action

Remove the volume and insert a fresh tape that can be overwritten.

See Also

Errors 3000-3999


Error 3267

Severity Level 16
Message Text

Insufficient resources to create UMS scheduler.

Explanation

When attempting a backup or restore operation, this error message indicates that the server is too busy to perform the backup or restore operation.

Action

Retry the operation after reducing the server load.

See Also

Errors 3000-3999


Error 3414

Severity Level 10
Message Text

Database '%.*ls' (database ID %d) could not recover. Contact Technical Support for further instructions.

Explanation

During startup, Microsoft® SQL Server™ could not complete the recovery of the specified database.

Action

To determine why recovery failed, examine the error log for any errors prior to error 3414. It is important to examine errors that occurred before the first occurrence of error 3414 because subsequent attempts to start the server might not give the detailed error information you need to diagnose the problem. If you do not have sufficient information to recover from the previous errors, you can recover from known clean backups, or you can contact your primary support provider for assistance. Note that you cannot use the database until whatever caused the error has been corrected.

See Also

Errors 3000-3999


Error 3604

Severity Level 10
Message Text

Duplicate key was ignored.

Explanation

This error occurs when you attempt to insert a row that has an index value that violates the uniqueness property (UNIQUE with IGNORE_DUP_KEY) on an existing index.

Microsoft® SQL Server™ ignores the statement that caused the error and continues processing the transaction.

Action

No action is necessary unless you want to insert that row into the table. If so, you can drop and re-create the index without the UNIQUE clause, or you can change the data causing the uniqueness violation.

See Also

Errors 3000-3999


Error 3627

Severity Level 16
Message Text

Could not create worker thread.

Explanation

When attempting a backup or restore operation, this error message indicates that the server is too busy to perform the backup or restore operation.

Action

Retry the operation after reducing the server load.

See Also

Errors 3000-3999


Error 4207

Severity Level 16
Message Text

BACKUP LOG is not allowed while the select into/bulk copy option is enabled. Use BACKUP DATABASE or disable the option using sp_dboption.

Explanation

This error occurs when you perform a nonlogged operation on a database, such as bcp or SELECT INTO, followed by a BACKUP LOG to a dump device. Because there is data in your database that has not been logged and the log therefore cannot be used to properly recover the database, the BACKUP LOG operation is not allowed. For example, if a user executes a SELECT INTO followed by an UPDATE statement, the SELECT INTO operation is not logged, and the UPDATE results cannot be recovered from the log.

Note that simply enabling the select into/bulkcopy option does not, in itself, cause this condition. The option must be set and a nonlogged operation executed before this error message is reported.

Backing up the database creates a new savepoint on which subsequent transaction logs are based. Therefore, backing up the database ensures that the nonlogged changes are recoverable and backing up the transaction log to a device is once again allowed.

Action

You must perform a BACKUP DATABASE. Disabling the select into/bulkcopy option using sp_dboption will not allow you to back up the log (even though the message says this is an option). To clear the 4207 error condition, you must back up the database.

You might need to use BACKUP LOG WITH TRUNCATE_ONLY until you can perform a full database backup. If you must do this, you lose the ability to recover up-to-the-minute data changes in case of a media failure.

See Also

Errors 4000-4999


Error 4208

Severity Level 16
Message Text

BACKUP LOG is not allowed while the trunc. log on chkpt. option is enabled. Use BACKUP DATABASE or disable the option using sp_dboption.

Explanation

If the trunc. log on chkpt. database option is enabled, the log is truncated when periodic checkpoints occur. Only full database and differential database backups are allowed because the log has been truncated and any log backups made would be unusable.

Action

To maintain your database by performing only full and differential database backups, leave the trunc. log on chkpt. database option enabled and use BACKUP DATABASE.

To maintain a full set of transaction log backups to guarantee that no change to the database is lost in the event of a failure, disable the trunc. log on chkpt. database option, backup the database using BACKUP DATABASE, and begin taking periodic transaction log backups.

See Also
Errors 4000-4999 Setting Database Options_Setting_Database_Options


Error 4214

Severity Level 10
Message Text

There is no current database backup. This log backup cannot be used to roll forward a preceding database backup.

Explanation

To restore the database after failure, you must begin either with a full database backup, or with a partial or complete set of file backups. Either this database has never been backed up or a BACKUP LOG statement was executed after an ALTER DATABASE statement, which added or removed one or more files, was performed. Therefore, the log backup just completed is not useful.

Action

Perform a full database backup before backing up the log.

See Also

Errors 4000-4999


Error 4305

Severity Level 16
Message Text

This backup set cannot be restored because the database has not been rolled forward far enough. You must first restore all earlier logs before restoring this log.

Explanation

The restore operation found a gap between the last restore and the transaction log that you attempted to apply.

Action

Locate the missing, earlier transaction log backups and apply these first. Transaction logs must be restored in the same order in which they were backed up.

See Also

Errors 4000-4999


Error 4306

Severity Level 16
Message Text

The preceding restore operation did not specify WITH NORECOVERY or WITH STANDBY. Restart the restore sequence, specifying WITH NORECOVERY or WITH STANDBY for all but the final step.

Explanation

After the database has been recovered, no further restore operations may be performed.

Action

To recover a database, start the sequence over and use the NORECOVERY clause on all RESTORE statements except the last. If you are maintaining a standby server and want to bring up the database in read-only mode between restore operations, use the STANDBY clause of RESTORE instead of the NORECOVERY clause.

See Also

Errors 4000-4999


Error 4318

Severity Level 16
Message Text

File '%ls' has been rolled forward to LSN %.*ls. This log terminates at LSN %.*ls, which is too early to apply the WITH RECOVERY option. Reissue the RESTORE LOG statement WITH NORECOVERY.

Explanation

You have attempted to recover the database to its state at the time the current log backup was made. However, at least one file has been modified since this backup was created. Recovery is not possible because the database would be left in an inconsistent state.

Action

To recover the database to its most recent state, reissue the RESTORE LOG statement with the NORECOVERY clause and continue to apply transaction logs, recovering only when you have rolled far enough forward.

To recover the database to the point-in-time at the end of this log backup, use RESTORE DATABASE to restore the indicated file to an earlier state and roll it forward.

See Also

Errors 4000-4999


Error 5013

Severity Level 16
Message Text

The master and model databases cannot have files added to them. ALTER DATABASE was aborted.

Explanation

This error occurs when you attempt to extend either the master or model databases by adding database files.

Action

Extend the master or model databases only when necessary. The master database will grow automatically, if needed. If there is no room on the disk drive where the master files reside, either delete other files to make more disk space or replace the disk drive with a larger disk drive. If you need to expand the model database, ensure that there is available disk space on the disk drive where the model data files currently reside.

See Also

Errors 5000-5999


Error 5701

Severity Level 10
Message Text

Changed database context to '%.*ls'.

Explanation

This is an informational message indicating that the database context has changed. This message is returned anytime a USE database statement is executed.

Action

None needed.

See Also
Errors 5000-5999


Error 5808

Severity Level 16
Message Text

Ad hoc updates to system catalogs not recommended. Use the RECONFIGURE WITH OVERRIDE statement to force this configuration.

Explanation

This error message occurs in one of these two situations:

  • When a user tries to use the sp_configure system stored procedure with the allow updates option
  • When a user tries to set a configuration parameter to a value that Microsoft® SQL Server™ recognizes as likely to interfere with performance or smooth operation

When the allow updates option is enabled, SQL Server allows direct updates to the system tables, so any user who can log on as the SQL Server system administrator can update the system tables directly with ad-hoc queries and can create stored procedures that update the system catalog. Incorrect changes to the system tables can cause unrecoverable database corruption or data loss.

Warning Severe problems can result from the direct manipulation of the system catalogs. Do not modify the system catalogs unless instructed to do so by your primary support provider.

Action

Before modifying any system catalogs, be sure that you have a valid backup of the database.

Warning Incorrect modification of the system catalogs can result in database corruption or data loss.

If possible, restart SQL Server in single-user mode by using the -m flag of the sqlservr application so that inadvertent modifications do not occur.

To modify system catalogs, use the osql utility to alter the allow updates system configuration setting.

Note Only the system administrator can alter the value for the allow updates system configuration setting.

See Also

Errors 5000-5999


Error 6103

Severity Level 17
Message Text

Could not do cleanup for the killed process. Received message %d.

Explanation

This error message occurs when another error caused a user connection to terminate abnormally. The message number that caused this error will be printed in the error 6103 message.

Action

Examine and resolve the “received message” reported in this error message.

See Also

Errors 6000-6999


Error 7130

Severity Level 16
Message Text

%ls WITH NO LOG is not valid at this time. Use sp_dboption to set the 'select into/bulk copy' option on for database '%.*ls'.

Explanation

This error occurs upon executing either the UPDATETEXT or WRITETEXT statements, or either the dbupdatetext or dbwritetext routines in a database that does not have the sp_dboption system stored procedure’s select into/bulkcopy option enabled. Because these are nonlogged operations, the option must be enabled.

Often, UPDATETEXT, WRITETEXT, dbupdatetext, and dbwritetext are run against a temporary table. The select into/bulkcopy option must be enabled in tempdb, or these will not run successfully.

Action

Enable the sp_dboption system stored procedure’s select into/bulkcopy option for all databases affected by the query that contains a nonlogged operation. To do this, the system administrator and database owners should follow these steps:

  1. Enable the option:

    USE master

    GO

    sp_dboption database_name, 'select into/bulkcopy',true

    GO

    USE database_name

    GO

    CHECKPOINT

    GO

  2. Verify that the change is active:

    sp_helpdb database_name

    GO

  3. Execute the nonlogged operation.
  4. When the nonlogged operation is complete, backup the database.

    Caution After executing a nonlogged operation, do not back up the transaction log. Although the procedure may appear to succeed, you may have been backing up only empty text pages. Whenever you make nonlogged changes to your database, you must use the BACKUP DATABASE statement, because changes made by the nonlogged operation cannot be recovered from transaction logs.

  5. Return the database to its original condition by disabling the select into/bulkcopy option:

    USE master

    GO

    sp_dboption database_name, 'select into/bulkcopy',false

    GO

    USE database_name

    GO

    CHECKPOINT

    GO

  6. Verify that the change is active:

    sp_helpdb database_name

    GO

See Also

Errors 7000-7999


Error 7304

Severity Level 16
Message Text

Could not create a new session on OLE DB provider '%ls'.

Explanation

Information to come later.

Action

Information to come later.

See Also

Errors 7000-7999


Error 8102

Severity Level 16
Message Text

Cannot update identity column '%.*ls'.

Explanation

You have specifically attempted to alter the value of an identity column in the SET portion of the UPDATE statement. You can only use the identity column in the WHERE clause of the UPDATE statement.

Action

Updating of the identity column is not allowed. To update an identity column, you can use the following techniques:

To reassign all identity values, bulk copy the data out, drop and re-create the table with the proper seed and increment values. Then bulk copy the data back into the newly created table. When bcp inserts the values it will appropriately increase the values and redistribute the identity values. You can also use the INSERT INTO and sp_rename commands to accomplish the same action.

To reassign a single row you must delete the row and insert it using the SET IDENTITY_INSERT tblName ON clause.

See Also

Errors 8000-8999


Error 8106

Severity Level 16
Message Text

Table '%.*ls' does not have the identity property. Cannot perform SET operation.

Explanation

You have attempted to use the SET IDENTITY_INSERT property on a table that does not contain an identity column.

Action

Double-check the table in question by using the sp_help tblName stored procedure to verify the identity column information.

See Also

Errors 8000-8999


Error 8163

Severity Level 16
Message Text

The text, ntext, or image data type cannot be selected as DISTINCT.

Explanation

When querying, Microsoft® SQL Server™ does not allow the use of SELECT DISTINCT on a text, ntext, or image column. For example, this query fails, returning error 8163:

USE Northwind

SELECT DISTINCT Description

FROM Categories

Action

Remove references to any text, ntext, or image columns when using SELECT DISTINCT.

See Also

Errors 8000-8999


Error 8645

Severity Level 17
Message Text

A time out occurred while waiting for memory resources to execute the query. Re-run the query.

Explanation

If the query wait configuration option is -1, then Microsoft® SQL Server™ waited 25 times the estimated query cost for the memory required to run the query. If query time is a nonnegative value, then SQL Server waited this amount of time, in seconds, for the memory required to run the query. The query timed out and it has not been executed.

Action

You can:

  • Free memory on the server.
    • Check the size of the virtual memory paging file.

      If possible, increase the size of the file.

    • Shut down any other applications running, if applicable, on the server.
  • Add additional memory to the server.
  • Reduce the server workload.

    To decrease the server workload, reduce the number of users currently using SQL Server. To prevent additional users from logging in to SQL Server, pause the server.

  • Create one or more indexes.
  • Increase the query wait configuration value.
See Also

Errors 8000-8999


Error 8651

Severity Level 17
Message Text

Could not perform the requested operation because the minimum query memory is not available. Decrease the configured value for the 'min memory per query' server configuration option.

Explanation

SQL Server has computed the amount of memory that this query requires to complete. This amount of required memory is not currently available; the min memory per query option may be too high.

Action

Resubmit the query. If resubmitting the query does not allow the query to run, you can:

  • Add additional memory to the server
  • Create one or more indexes,
  • Reduce the value of min memory per query.
  • Increase the query wait configuration option if it is a nonzero value.
See Also

Errors 8000-8999


Error 8906

Severity Level 16
Message Text

Page %S_PGID in database ID %d is allocated in the SGAM %S_PGID and PFS %S_PGID, but was not allocated in any IAM. PFS flags '%hs'.

Explanation

SQL Server has found an allocation error in the specified database.

Action

Either restore from a known clean backup or execute DBCC CHECKDB with the REPAIR_ALLOW_DATA_LOSS clause. For example:

DBCC CHECKDB('pubs', REPAIR_ALLOW_DATA_LOSS)

If the error involves an index page, use the REPAIR_REBUILD clause. If the error involves a data page, it may be necessary to use the REPAIR_ALLOW_DATA_LOSS clause. In the likely event that you cannot allow the loss of data, you will need to restore from a known clean backup. If the problem persists, contact your primary support provider. Have the output from DBCC CHECKDB available for review.

Important If executing DBCC CHECKDB with one of the repair clauses does not correct the index problem or if you are unsure what effect DBCC CHECKDB with a repair clause has on your data, contact your primary support provider.

If DBCC CHECKDB with the REPAIR_ALLOW_DATA_LOSS clause does not resolve the allocation error, contact your primary support provider.

See Also

Errors 8000-8999


Error 8908

Severity Level 16
Message Text

Table Corrupt: Database ID %d, object ID %d, index ID %d. Chain linkage mismatch. %S_PGID->next = %S_PGID, but %S_PGID->prev = %S_PGID.

Explanation

This error occurs when Microsoft® SQL Server™ detects an inconsistency in the page linkage of one of the page chains associated with a table, for example, when a page’s next pointer points to a page whose previous pointer points back to a different page. There is one doubly-linked page chain for the table data as well as one for each index level.

Important This is a serious error and must be corrected immediately.

If DBCC statements detect this error during run-time processing, error 605 will also occur.

Action

Determine which table is corrupt by examining the current page in the error message. Execute DBCC CHECKDB without a repair clause to determine the extent of the corruption. Then, execute DBCC CHECKDB with the appropriate repair clause to repair the corruption. If the page is associated with an index, it is sometimes possible to resolve the problem by dropping the index. In most cases, you must recover the database from a known clean backup.

If the error involves an index page, use the REPAIR_REBUILD clause. If the error involves a data page, it may be necessary to use the REPAIR_ALLOW_DATA_LOSS clause. In the likely event that you cannot allow the loss of data, you will need to restore from a known clean backup. If the problem persists, contact your primary support provider. Have the output from DBCC CHECKDB available for review.

Important If executing DBCC CHECKDB with one of the repair clauses does not correct the index problem or if you are unsure what effect DBCC CHECKDB with a repair clause has on your data, contact your primary support provider.

You should also examine your operating-system error log file, in addition to the SQL Server error log, to determine if hardware errors might have caused the corruption.

If the problem persists, contact your primary support provider. Have the output from the DBCC CHECKDB statement available for review.

See Also

Errors 2000 - 2999


Error 8925

Severity Level 16
Message Text

Table Corrupt: Cross object linkage: Page %S_PGID, slot %d, in object ID %d, index ID %d, refers to page %S_PGID, slot %d, in object ID %d, index ID %d.

Explanation

This error occurs when Microsoft® SQL Server™ detects an inconsistency in the page linkage of one of the page chains associated with a table. One of the pages has been found to be linked in more than one page chain when it should be linked in only one chain. There is one doubly-linked page chain for the table data, as well as one for each index level.

Important This is a serious error and must be corrected immediately.

If DBCC CHECKDB without a repair clause detects this error during run-time processing, error 605 can also occur.

Action

Follow these steps to resolve the error:

  1. Examine the index ID associated with the page number indicated in the message to determine whether the error occurred on the table data or on an index.
  2. Restore the database:
    • If the object ID is less than or equal to 100, the error is on a system table. Restore the database from a clean backup.
    • If the object ID is greater than 100, the error is on a user table.
    • If this error occurs on table data (the index ID = 0), restore the database from a clean backup.
    • If the error occurs on an index, you can usually correct it by dropping and re-creating the index. If dropping and re-creating the index is not feasible, or if you cannot drop the index, contact your primary support provider for assistance.

If the problem persists, contact your primary support provider for assistance. Have the output of the appropriate DBCC statements available for review.

See Also

Errors 2000 - 2999


Error 8952

Severity Level 16
Message Text

Table Corrupt: Database '%ls', index '%ls.%ls' (ID %d) (index ID %d). Extra or invalid key for the keys:

Explanation

This error message indicates that one or more indexes are damaged and must be repaired or dropped.

Action

Repair indexes by executing DBCC CHECKDB with either the REPAIR_ALLOW_DATA_LOSS, REPAIR_FAST, or REPAIR_REBUILD clauses. To determine which repair clause best suits your needs, consult DBCC CHECKDB before executing it.

Important If executing DBCC CHECKDB with one of the repair clauses does not correct the index problem or if you are unsure what effect DBCC CHECKDB with a repair clause has on your data, contact your primary support provider.

See Also
Error 8956 Errors 8000-8999


Error 8956

Severity Level 16
Message Text

Index row (%d:%d:%d) with values (%ls) points to the data row identified by (%ls).

Explanation

If Microsoft® SQL Server™ returns this error message, it always follows error 8952.

This error message indicates that one or more indexes are damaged and must be repaired or dropped.

Action

Repair indexes by executing DBCC CHECKDB with either the REPAIR_ALLOW_DATA_LOSS, REPAIR_FAST, or REPAIR_REBUILD clauses. To determine which repair clause best suits your needs, consult DBCC CHECKDB before executing it.

Important If executing DBCC CHECKDB with one of the repair clauses does not correct the index problem or if you are unsure what effect DBCC CHECKDB with a repair clause has on your data, contact your primary support provider.

See Also
Error 8952 Errors 8000-8999


Error 8976

Severity Level 16
Message Text

Table Corrupt: Object ID %d, index ID %d. Page %S_PGID not allocated or corrupt. Parent %S_PGID and previous %S_PGID refer to it.

Explanation

This error means that a page is not allocated to an object that references it. When the index is used, Microsoft® SQL Server™ returns either error 605 or error 823.

Important This error is serious. Data corruption is possible.

Pages encountering error 8976 may not be included in a database backup, because database backups are performed by reading allocation pages and not by traversing page chains. Correct this error before backing up the database.

Action

If a known clean backup is available, restore the database from the backup.

If no clean backup is available, use DBCC CHECKDB or DBCC CHECKFILEGROUP to determine the extent of the problem. Then, use DBCC CHECKDB with the appropriate repair clause to repair the damage. If the Object ID is 1 or 2 and the index ID is 1, or the table is sysfiles1, then DBCC CHECKDB cannot repair the page.

Important If either executing DBCC CHECKDB with one of the repair clauses does not correct the index problem or if you are unsure what effect DBCC CHECKDB with a repair clause has on your data, contact your primary support provider.

For indexes (0 < Index ID < 255)

The problem can be resolved by dropping and re-creating the index in question. After the index is rebuilt, run DBCC CHECKALLOC to verify that the problem no longer exists. If it persists, call your primary support provider.

See Also

Errors 8000-8999


Error 9002

Severity Level 19
Message Text

The log file for database '%.*ls' is full. Back up the transaction log for the database to free up some log space.

Explanation

The specified transaction log file has run out of free space.

Action

You can:

  • Free disk space on any disk drive containing the log file for the related database. Freeing disk space allows the recovery system to grow the log file automatically.

Or

  1. Free disk space on a different disk drive.
  2. Move the transaction log files with an insufficient amount of free disk space to the disk drive in Step 1.
  3. Detach the database by executing sp_detach_db.
  4. Attach the database by executing sp_attach_db, pointing to the moved files.

Or

  • Either add a log file to the specified database by using the ADD FILE clause of the ALTER DATABASE statement, or enlarge the log file by using the MODIFY FILE clause of the ALTER DATABASE statement, specifying the SIZE and MAXSIZE syntax. Adding an additional log file allows the existing log to grow.
See Also

Errors 9000-9999


Error 17050

Severity Level 16
Message Text

initerrlog: Could not open error log file '%1'. Operating system error = %2.

Explanation

When installing Microsoft® SQL Server™ on an NTFS partition, make sure that the NTFS file permissions allow read-write access. Otherwise, this error message may appear in the Microsoft Windows NT application log (for each installation attempt).

Action

Ensure that the NTFS file permissions allow read-write access. In addition, the SYSTEM account should have full-control rights to the computer. It is recommended that everyone using the computer have full-control rights, but that the NTFS partition not be shared.

See Also
Errors 17000 - 17999


Error 18456

Severity Level 14
Message Text

Login failed for user '%ls'.

Explanation

You do not have permission to log in to the server.

Action

Contact a member of the sysadmin fixed server role to request login permission.

See Also

Errors 18000 - 18999


Error 18458

Severity Level 14
Message Text

Login failed. The maximum simultaneous user count of %d licenses for this server has been exceeded. Additional licenses should be obtained and registered through the Licensing application in the Windows NT Control Panel.

Explanation

This error occurs when the server is set for Per Server licensing and the number of attempted client connections exceeds the number of Client Access Licenses for this server.

Action

Obtain additional Client Access Licenses or reduce the number of simultaneous client connection attempts.

See Also

Errors 18000 - 18999


Error 18459

Level 14
Message Text

Login failed. The maximum workstation licensing limit for SQL Server access has been exceeded.

Explanation

This error occurs when the server is set for Per Seat licensing and a connection is attempted from a client computer that does not have a Client Access License.

Action

Obtain a Client Access License for the client computer.

See Also

Errors 18000 - 18999


Read/Write Error

Message Text

kernel: operating system error %d (%s) encountered

Explanation

Microsoft® SQL Server™ failed to read from or write to the specified location on disk. This failure is usually a result of a physical disk problem like a bad sector on the disk drive or a failure of the disk drive or controller.

Action

Identify the device with the problem by selecting the row from sysfiles that has the same disk name indicated in the error message:

USE master

GO

SELECT name, filename

FROM master..sysfiles

GO

The output from this query should provide the physical name of the damaged disk. Examine the disk as soon as possible and correct any problems. After the disk drive or controller problem is resolved, restore from a backup, if available. If no backup is available, execute DBCC CHECKDB with the REPAIR_DATA_LOSS clause to deallocate the damaged pages from the database.

Warning Using the REPAIR_ALLOW_DATA_LOSS clause of DBCC CHECKDB may cause a loss of data if the disk damage was to a data or text page. If the hardware problem is not corrected properly before executing DBCC CHECKDB, the damaged pages will be reallocated and this problem will continue.

After executing DBCC CHECKDB with the REPAIR_ALLOW_DATA_LOSS clause, back up the repaired data, fix the hardware errors, and reload the previously backed up data.


Server Is Unnamed

Message Text

server: server is unnamed

Explanation

This informational message is displayed during Microsoft® SQL Server™ startup if the SQL Server installation has not been given a name using the sp_addserver system procedure. The server name referred to here is stored in the sysservers system table as well as in the @@SERVERNAME function. This name is used primarily for managing server-to-server communication and does not absolutely need to match the computer name of the server (but it usually should, for ease of use of replication and other multiple server actions).

Action

No action is required for this message. The system administrator can prevent this message by assigning a name to the server using the sp_addserver procedure, as follows:

sp_addserver sql_server_name, local

(Under Windows NT, the setup program automatically gives SQL Server the same name as the server computer.)

The @@SERVERNAME function will not reflect the name until SQL Server is restarted. Subsequently, each time SQL Server is started, the new name is displayed. For example, if the SQL Server is named MYSERVER, the message would read:

server: server name is 'MYSERVER'

Although the server name is used during server-to-server communications, specifying a name does not, in itself, facilitate this communication, and therefore does not represent a security risk. Naming all servers makes the SQL Server error logs easy to identify because the server name is contained within each log.


MAPI Error Values Overview

These MAPI error values are used by SQL Mail.

MAPI Constant | Description
MAPI_USER_ABORT | User abort.
MAPI_E_FAILURE | General MAPI failure.
MAPI_E_LOGIN_FAILURE | MAPI login failure.
MAPI_E_DISK_FULL | Disk full.
MAPI_E_INSUFFICIENT_MEMORY | Insufficient memory.
MAPI_E_ACCESS_DENIED | Access denied
MAPI_E_TOO_MANY_SESSIONS | Too many sessions.
MAPI_E_TOO_MANY_FILES | Too many files were specified.
MAPI_E_TOO_MANY_RECIPIENTS | Too many recipients were specified.
MAPI_E_ATTACHMENT_NOT_FOUND | A specified attachment was not found.
MAPI_E_ATTACHMENT_OPEN_FAILURE | Attachment open failure.
MAPI_E_ATTACHMENT_WRITE_FAILURE | Attachment write failure.
MAPI_E_UNKNOWN_RECIPIENT | Unknown recipient: Parameter '%s', recipient '%s'
MAPI_E_BAD_RECIPTYPE | Bad recipient type.
MAPI_E_NO_MESSAGES | No messages.
MAPI_E_INVALID_MESSAGE | Invalid message.
MAPI_E_TEXT_TOO_LARGE | Text too large.
MAPI_E_INVALID_SESSION | Invalid session.
MAPI_E_TYPE_NOT_SUPPORTED | Type not supported.
MAPI_E_AMBIGUOUS_RECIPIENT | A recipient was specified ambiguously.
MAPI_E_MESSAGE_IN_USE | Message in use.
MAPI_E_NETWORK_FAILURE | Network failure.
MAPI_E_INVALID_EDITFIELDS | Invalid edit fields.
MAPI_E_INVALID_RECIPS | Invalid recipients.
MAPI_E_NOT_SUPPORTED | Not supported.


DB-Library Error Message Overview

This appendix describes all DB-Library error messages and severity levels. The information in this appendix is divided into two tables. The following table lists the errors alphabetically, along with their severities. The table under DB-Library Error Severities section summarizes the error severity levels. Number values corresponding to the errors are passed to the currently installed, user-supplied error handler. To access these error definitions, include the Sqlfront.h and Sqldb.h header files in your program.

The following error values are defined in the header file Sqlfront.h. Errors with a severity of EXCOMM also have a network-related error message appended to the dberrstr value. In addition, EXCOMM errors have network-specific error information in oserr and oserrstr.

Error number | Error/ Error severity | Description
10000 | SQLEMEM EXRESOURCE | Unable to allocate sufficient memory.
10001 | SQLENULL EXPROGRAM | NULL DBPROCESS pointer encountered.
10002 | SQLENLOG EXCONSISTENCY | NULL LOGINREC pointer encountered.
10003 | SQLEPWD EXUSER | Login incorrect.
10004 | SQLECONN EXCOMM | Unable to connect: SQL Server is unavailable or does not exist.
10005 | SQLEDDNE EXINFO | DBPROCESS is dead or not enabled.
10006 | SQLENULLO EXCONSISTENCY | Attempt to login with NULL LOGINREC.
10007 | SQLESMSG EXSERVER | General SQL Server error: Check messages from SQL Server.
10008 | SQLEBTOK EXCOMM | Bad token from SQL Server: Datastream processing out of synchronization.
10009 | SQLENSPE EXPROGRAM | General nonspecific DB-Library error.
10010 | SQLEREAD EXCOMM | Read from SQL Server failed.
10011 | SQLECNOR EXPROGRAM | Column number out of range.
10012 | SQLETSIT EXINFO | Attempt to call dbtsput with an invalid timestamp.
10013 | SQLEPARM EXCONSISTENCY | Invalid parameter in DB-Library function reference.
10014 | SQLEAUTN EXPROGRAM | Attempt to update the timestamp of a table with no timestamp column.
10015 | SQLECOFL EXCONVERSION | Data conversion resulted in overflow.
10016 | SQLERDCN EXCONVERSION | Requested data conversion does not exist.
10017 | SQLEICN EXPROGRAM | Invalid value for computeid or invalid compute column number.
10019 | SQLENTXT EXPROGRAM | Attempt to get text point/timestamp from a nontext column.
10020 | SQLEDNTI EXPROGRAM | Attempt to use dbtxtsput to put a new text timestamp into a column whose data type is neither SQLTEXT nor SQLIMAGE.
10021 | SQLETMTD EXPROGRAM | Attempt to send too much TEXT data through dbmoretext.
10022 | SQLEASEC EXPROGRAM | Attempt to send an empty command buffer to the SQL Server.
10023 | SQLENTLL EXUSER | Name too long for LOGINREC field.
10024 | SQLETIME EXTIME | SQL Server connection timed out.
10026 | SQLEMODE EXCOMM | Network connection not in correct mode – invalid SQL Server connection.
10027 | SQLEOOB EXCOMM | Error in sending out-of-band data to SQL Server.
10028 | SQLEITIM EXPROGRAM | Illegal timeout value specified.
10029 | SQLEDBPS EXRESOURCE | Maximum number of DBPROCESSes already allocated.
10030 | SQLEIOPT EXPROGRAM | Attempt to use invalid dboption.
10031 | SQLEASNL EXPROGRAM | Attempt to set fields in a null LOGINREC.
10032 | SQLEASUL EXPROGRAM | Attempt to set unknown LOGINREC field.
10033 | SQLENPRM EXPROGRAM | NULL parameter not allowed for this dboption.
10034 | SQLEDBOP EXPROGRAM | Invalid or out of range dbn parameter.
10035 | SQLENSIP EXPROGRAM | Negative starting index passed to dbstrcpy.
10036 | SQLECNULL EXPROGRAM | NULL destination variable not allowed.
10037 | SQLESEOF EXCOMM | Unexpected EOF from SQL Server.
10038 | SQLERPND EXPROGRAM | Attempt to initiate a new SQL Server operation with results pending.
10039 | SQLECSYN EXCONVERSION | Attempt to convert data stopped by syntax error in source field.
10040 | SQLENONET EXCOMM | DB-Library network communications layer not loaded.
10041 | SQLEBTYP EXPROGRAM | Unknown bind type passed to DB-Library function.
10042 | SQLEABNC EXPROGRAM | Attempt to bind to a nonexistent column.
10043 | SQLEABMT EXPROGRAM | User attempted a dbbind with mismatched column and variable types.
10044 | SQLEABNP EXPROGRAM | Attempt to bind using NULL pointers.
10045 | SQLEBNCR EXPROGRAM | Attempt to bind user variable to a nonexistent compute row.
10046 | SQLEAAMT EXPROGRAM | User attempted a dbaltbind with mismatched column and variable types.
10047 | SQLENXID EXNONFATAL | The server did not grant us a distributed-transaction ID.
10048 | SQLEIFNB EXPROGRAM | Illegal field number passed to bcp_control.
10049 | SQLEKBCO EXINFO | 1000 rows successfully bulk copied to host file.
10050 | SQLEBBCI EXINFO | Batch successfully bulk copied to SQL Server.
10051 | SQLEKBCI EXINFO | 1000 rows sent to SQL Server.
10052 | SQLEBCWE EXNONFATAL | I/O error while writing bcp datafile.
10053 | SQLEBCNN EXUSER | Attempt to bulk copy a null value into a server column that does not accept null values.
10054 | SQLEBCOR EXCONSISTENCY | Attempt to bulk copy an oversized row to SQL Server.
10055 | SQLEBCPI EXPROGRAM | Call bcp_init before any other bcp routines.
10056 | SQLEBCPN EXPROGRAM | Use bcp_bind, bcp_collen, and bcp_colptr only after calling bcp_init with the copy direction set to DB_IN.
10057 | SQLEBCPB EXPROGRAM | Do not use bcp_bind after bcp_init has been passed a non-null input filename.
10058 | SQLEVDPT EXUSER | For bulk copy, all variable-length data must have either a length-prefix or a terminator specified.
10059 | SQLEBIVI EXPROGRAM | Use bcp_columns and bcp_colfmt only after bcp_init has been passed a valid input file.
10060 | SQLEBCBC EXPROGRAM | Call bcp_columns before bcp_colfmt.
10061 | SQLEBCFO EXUSER | Host files must contain at least one column: bcp.
10062 | SQLEBCVH EXPROGRAM | Call bcp_exec only after bcp_init has been passed a valid host file.
10063 | SQLEBCUO EXRESOURCE | Unable to open host datafile: bcp.
10064 | SQLEBUOE EXRESOURCE | Unable to open error file: bcp.
10065 | SQLEBWEF EXNONFATAL | I/O error while writing bcp error file.
10066 | SQLEBTMT EXPROGRAM | Attempt to send too much text data with bcp_moretext.
10067 | SQLEBEOF EXNONFATAL | Unexpected EOF encountered in bcp datafile.
10068 | SQLEBCSI EXCONSISTENCY | Host-file columns may be skipped only when copying into the server.
10069 | SQLEPNUL EXCONSISTENCY | NULL program pointer encountered.
10070 | SQLEBSKERR EXCONSISTENCY | Cannot seek in data file.
10071 | SQLEBDIO EXPROGRAM | Bad bulk-copy direction.
10072 | SQLEBCNT EXUSER | Attempt to use bulk copy with a nonexistent server table.
10073 | SQLEMDBP EXPROGRAM | Attempt to set maximum number of DPPROCESS lower than 1.
10075 | SQLCRSINV EXPROGRAM | Invalid cursor statement.
10076 | SQLCRSCMD EXPROGRAM | Attempt to call cursor functions when there are commands waiting to be executed.
10077 | SQLCRSNOIND EXINFO | One of the tables involved in the cursor statement does not have a unique index.
10078 | SQLCRSDIS EXPROGRAM | Cursor statement contains one of the disallowed phrases COMPUTE, UNION, FOR BROWSE, or SELECT INTO.
10079 | SQLCRSAGR EXPROGRAM | Aggregate functions are not allowed in a cursor statement.
10080 | SQLCRSORD EXPROGRAM | Only fully keyset driven cursors can have ORDER BY, GROUP BY, or HAVING PHRASES.
10081 | SQLCRSMEM EXPROGRAM | Keyset or window scroll size exceeds the memory limitations of this machine.
10082 | SQLCRSBSKEY EXPROGRAM | Keyset cannot be scrolled backward in mixed cursors with a previous fetch type.
10083 | SQLCRSNORES EXINFO | Cursor statement generated no results.
10084 | SQLCRSVIEW EXPROGRAM | A view cannot be joined with another table or a view in a cursor statement.
10085 | SQLCRSBUFR EXPROGRAM | Row buffering should not be turned on when using cursor functions.
10086 | SQLCRSFROWN EXINFO | Row number to be fetched is outside valid range.
10087 | SQLCRSBROL EXPROGRAM | Backward scrolling cannot be used in a forward scrolling cursor.
10088 | SQLCRSFRAND EXPROGRAM | Fetch types RANDOM and RELATIVE can only be used within the keyset of keyset driven cursors.
10089 | SQLCRSFLAST EXPROGRAM | Fetch type LAST requires fully keyset driven cursors.
10090 | SQLCRSRO EXPROGRAM | Data locking or modifications cannot be made in a READONLY cursor.
10091 | SQLCRSTAB EXPROGRAM | Table name must be determined in operations involving data locking or modifications.
10092 | SQLCRSUPDTAB EXPROGRAM | Update or insert operations using bind variables require single table cursors.
10093 | SQLCRSUPDNB EXPROGRAM | Update or insert operations cannot use bind variables when binding type is NOBIND.
10094 | SQLCRSVIIND EXPROGRAM | The view used in the cursor statement does not include all the unique index columns of the underlying tables.
10095 | SQLCRSNOUPD EXINFO | Update or delete operation did not affect any rows.
10096 | SQLCRSOS2 EXPROGRAM | Cursors are not supported for this server.
10097 | SQLEBCSA EXPROGRAM | The BCP hostfile %s contains only %ld rows. Skipping all of these rows is not allowed.
10098 | SQLCRSRO EXPROGRAM | Data locking or modifications cannot be made in a READONLY cursor.
10099 | SQLEBCNE EXPROGRAM | The table %s contains only %ld rows. Copying up to row %ld is not possible.
10100 | SQLEBCSK EXPROGRAM | The table %s contains only %ld rows. Skipping all of these rows is not allowed.
10101 | SQLEUVBF EXPROGRAM | Attempt to read unknown version of bcp format file.
10102 | SQLEBIHC EXPROGRAM | Incorrect host-column number found in bcp format file.
10103 | SQLEBWFF EXRESOURCE | I/O error while reading bcp format file.
10104 | SQLNUMVAL EXPROGRAM | The data stored in the DBNUMERIC/DBDECIMAL structure is invalid.
10105 | SQLEOLDVR EXPROGRAM | The SQL Server’s TDS is obsolete with this version of DB-Library.


DB-Library Error Severities

The following table lists all error severities with their numerical equivalents and an explanation of the type of error. When an error occurs or when a message is sent, these numerical equivalents are passed to the currently installed, user-supplied error handler.

Error severity levels are defined in the Sqlfront.h header file. Your program must include Sqlfront.h if it refers to these severity levels.

Error severity | Severity number | Description
EXINFO | 1 | Informational, nonerror.
EXUSER | 2 | User error.
EXNONFATAL | 3 | Nonfatal error.
EXCONVERSION | 4 | Error in DB-Library data conversion.
EXSERVER | 5 | The server has returned an error flag.
EXTIME | 6 | Timeout period exceeded while waiting for a response from the server – the DBPROCESS is still alive.
EXPROGRAM | 7 | Coding error in user program.
EXRESOURCE | 8 | Running out of resources – the DBPROCESS may be dead.
EXCOMM | 9 | Failure in communication with server – the DBPROCESS is dead.
EXFATAL | 10 | Fatal error – the DBPROCESS is dead.
EXCONSISTENCY | 11 | Internal software error – notify your primary support provider.


Error 10008 (DB-Library)

DB-Library Severity Level 9
Message Text

Bad token from SQL Server: Datastream processing out of synchronization.

Explanation

This error occurs when DB-Library cannot interpret the Tabular Data Stream (TDS) sent from Microsoft® SQL Server™. A DB-Library application communicates with SQL Server over the network using a TDS. The TDS is a specification for the communication of data and other messages between SQL Server and the DB-Library client. The network libraries used by SQL Server and the DB-Library client provide the interface for the transmission of TDS over a particular network protocol. The network protocol used is independent from the TDS as long as there is an appropriate interface network library that supports the network protocol, whether it is a named pipe connection or a socket connection. Each DB-Library application parses this TDS automatically to extract useful information (for example, query result rows) or to generate requests of, or responses to, SQL Server in a format that is mutually understood.

There are two main causes for this error:

  • The data sent by SQL Server over the network named pipe or socket has been corrupted. This is usually caused by a network problem involving either network hardware or software.
  • The network can generate errors or messages unknown to DB-Library; as a consequence, this error can be generated.
Action

Inspect the Windows NT Event Viewer system and application logs. These logs may provide information that indicates whether the problem is related to the server network protocol, the network card, or the system configuration. Review the SQL Server–specific entries in the application log or the SQL Server error log for relevant network-related errors that correspond in time with the occurrence of the 10008 error seen on the client. If this review does not provide enough information to resolve the problem, special network monitoring tools and a review of the client’s configuration may be necessary.

If the problem persists, contact your primary network support provider for assistance.

Programmers using the SQL Server Programmer’s Toolkit (for DB-Library) can handle error 10008 by adding conditional statements to test for the occurrence of this error. When error 10008 is seen in the DB-Library error handler, additional processing can include closing the current DBPROCESS connection, opening a new connection, and then resending the query.


Error 10024 (DB-Library)

DB-Library Severity Level 6
Message Text

SQL Server connection timed out.

Explanation

This error message is returned from DB-Library when the query time-out setting for the application’s connection to Microsoft® SQL Server™ is too low. The query is terminated when it takes longer to complete than the time allocated.

Action

Check the application for configuration settings, and increase the query time-out setting. If this is a custom application, you can adjust the query time-out setting by using either the dbsettime() function in C or the SqlSetTime% function in DB-Library for Visual Basic.


Error 10053 (DB-Library)

DB-Library
Severity Level 2
Message Text

Attempt to bulk copy a null value into a server column that does not accept null values.

Explanation

This error occurs when you attempt to bulk copy a null value into a table column that does not accept null values. This usually occurs when the column is changed from NULL to NOT NULL after previous bulk copies.

Action

If the source file being bulk copied is character data, the file can be edited and the column value changed to an appropriate value for the column definition. You can also change the current definition of the table or create a separate table with a column definition that allows null values.


Error 10054 (DB-Library)

DB-Library Severity Level 11
Message Text

Attempt to bulk copy an oversized row to SQL Server.

Explanation

This error occurs during a bulk copy operation when a row or rows in the source data file do not match the row as defined for the destination database table. It can occur due to a missing end-of-line marker. It can also occur if there are more column delimiters in the source data file than currently exist in the destination database table, or if the source data file is corrupt.

Action

Verify that the source data file matches the column definitions for the database table. Or, create a new table to match the current data file, bulk copy the data into the database, and then manipulate the data using Transact-SQL statements.

You can either manipulate the source data file or create a format file to facilitate the data transfer. You can manipulate character-based data files by using a text editing tool that accommodates the data file size and will not add special hidden characters during a save operation. The editing tool can then be used to manipulate the source data file by adding or deleting characters as necessary so that the source data file matches the table definition. You can also create a format file. The generated format file can be manipulated by a text editing tool and changed so that character positions/columns in the source data file are ignored. Native format files are more difficult to manipulate.

The alternatives to manipulating the native format source data file and/or a format file are limited due to the storage of data types other than character in a binary type format. It can be difficult to manipulate this file type with any editing tool, and it is more difficult to generate and manipulate a format file. You can use the
-F or the -L command-line flags to specify the first and last row in the source data file that is to be bulk copied into SQL Server. If the source data file contains a few oversized rows, these flags can be used to bulk copy up to the oversized row followed by a bulk copy operation from the row following the oversized row to the end of the data file.

If you are unable to resolve this error, contact your primary support provider for assistance.


Distributed Queries Error Message Overview

This group of topics discusses troubleshooting tips and techniques for distributed queries against various OLE DB providers. On an error condition against an OLE DB provider, Microsoft® SQL Server™ outputs two sets of error messages:

  • Provider error messages (indicated by one or more error messages surrounded by square brackets), which are returned by the OLE DB provider.
  • SQL Server error messages.

SQL Server uses the OLE DB provider’s error object and its interfaces to return the provider’s error messages. If the provider does not support the error object and its interfaces for the given error context, provider error messages are not available.

The following topics describe and resolve the most commonly received SQL Server error messages related to distributed queries.

In addition to using these error message topics to resolve problems with distributed queries, use SQL Server Profiler to trace the OLE DB Errors event class. The OLE DB Errors event class outputs the OLE DB interface and method for the provider returning an error and the error code returned by the method invocation. The hexadecimal error code can be looked up in the Oledberr.h header file (located in the \DevTools\Include directory of the target SQL Server installation directory, by default, C:\Mssql7) to determine the meaning of the error code, by default, the OLE DB Errors event class does not show up in SQL Server Profiler. For more information about seeing the OLE DB Errors event class and other advanced errors using SQL Server Profiler, see Advanced Options.

This table lists all distributed queries error messages.

Error | Severity | Description
7303 | 16 | Could not initialize data source object of OLE DB provider '%ls'. %ls
7306 | 16 | Could not open table '%ls' from OLE DB provider '%ls'. %ls
7314 | 16 | OLE DB provider '%ls' does not contain table '%ls'.
7321 | 16 | An error occurred while preparing a query for execution against OLE DB provider '%ls'. %ls
7356 | 16 | OLE DB provider '%ls' supplied inconsistent metadata for a column. Metadata information was changed at execution time.
7357 | 16 | Could not process object '%ls'. The OLE DB provider '%ls' indicates that the object has no columns.
7391 | 16 | The operation could not be performed because the OLE DB provider '%ls' does not support distributed transactions.
7392 | 16 | Could not start a transaction for OLE DB provider '%ls'.
7399 | 16 | OLE DB provider '%ls' reported an error. %ls
7403 | 16 | Could not locate registry entry for OLE DB provider '%ls'.
7413 | 16 | Could not perform a Windows NT authenticated login because delegation is not available.
8114 | 16 | Error converting data type %ls to %ls.
8501 | 16 | MS DTC on server '%.*ls' is unavailable.


Error 7303

Severity Level 16
Message Text

Could not initialize data source object of OLE DB provider '%ls'. %ls

Explanation

This error message indicates that the OLE DB data source object could not be initialized.

Action

This error message can occur because of one of these problems.

Problem | Resolution
One of the initialization parameters specified in sp_addlinkedserver (data_source, location, provider_string, or catalog) is incorrect for this provider. | Verify that these parameters defined for the linked server, specified by executing sp_addlinkedserver, are correct for the given provider. Check the provider’s documentation for the appropriate values for these parameters.
Login and password sent to the provider is invalid. | Verify that there is a valid login and password configured for the linked server and the current SQL Server login through sp_addlinkedsrvlogin.

See Also

Errors 7000 - 7999


Error 7306

Severity Level 16
Message Text

Could not open table '%ls' from OLE DB provider '%ls'. %ls

Explanation

This error message is returned if the OLE DB provider does not support the interfaces and OLE DB properties required for the UPDATE, DELETE, and INSERT statements.

Action

In this scenario, a trace on OLE DB Errors would output additional information on the specific missing OLE DB support. For example, in the case of Microsoft® SQL Server™, the INSERT, UPDATE, and DELETE statements are not supported on the remote table if the table does not have a unique index defined on it. In this case, SQL Server Profiler would output the following information:

OLE/DB Provider 'SQLOLEDB' IOpenRowset::OpenRowset returned 0x80040e21:

[PROPID=DBPROP_BOOKMARKS VALUE=True STATUS=DBPROPSTATUS_OK], [PROPID=DBPROP_IRowsetLocate

VALUE=True STATUS=DBPROPSTATUS_OK], [PROPID=DBPROP_IRowsetChange VALUE=True

STATUS=DBPROPSTATUS_CONFLICTING], [PROPID=DBPROP_UPDATABILITY VALUE=1 STATUS=DBPROPSTATUS_OK]

This error message indicates the status of each OLE DB property that was requested on the rowset opened against the table being updated. This information indicates that all properties required by SQL Server to perform this query, except the DBPROP_IRowsetChange property, were satisfied by the provider.

See Also

Errors 7000 - 7999


Error 7314

Severity Level 16
Message Text

OLE DB provider '%ls' does not contain table '%ls'.

Explanation

Either the specified table or columns do not exist or the login used to connect to the provider does not have the required permissions on the table or columns.

This message occurs on case-sensitive servers.

Action

Verify that the table or columns specified exist. Verify that the appropriate permissions are granted on the table or columns specified.

If the table was originally created in Oracle without quotation marks, specify the table name in the distributed query using all uppercase letters. If the table was originally created in Oracle with quotation marks, specify the table name in the distributed query using all lowercase letters.

See Also

Errors 7000 - 7999


Error 7321

Severity Level 16
Message Text

An error occurred while preparing a query for execution against OLE DB provider '%ls'. %ls

Explanation

Indicates a possible syntax error in the pass-through query’s query string parameter.

Action

Verify that the query string is free of syntax errors (with respect to the query language supported by the OLE DB provider).

See Also

Errors 7000 - 7999


Error 7356

Severity Level 16
Message Text

OLE DB provider '%ls' supplied inconsistent metadata for a column. Metadata information was changed at execution time.

Explanation

This error indicates that there was inconsistent metadata reported by the provider on a given table between compilation time and execution time of the query. This typically occurs because the provider returns inconsistent metadata between the OLE DB schema rowset COLUMNS (during compilation) and that metadata reported by the IColumnsInfo interface on the table’s rowset.

Action

Consult SQL Server Profiler to determine which table column caused this error.

See Also

Errors 7000 - 7999


Error 7357

Severity Level 16
Message Text

Could not process object '%ls'. The OLE DB provider '%ls' indicates that the object has no columns.

Explanation

Either the specified table or columns do not exist or the login used to connect to the provider does not have the required permissions on the table or columns.

Action

Verify that the table or columns specified exist. Verify that the appropriate permissions are granted on the table or columns specified.

See Also

Errors 7000 - 7999


Error 7391

Severity Level 16
Message Text

The operation could not be performed because the OLE DB provider '%ls' does not support distributed transactions.

Explanation

This error can occur while processing an INSERT, UPDATE, or DELETE statement inside an explicit or implicit transaction. This indicates that the OLE DB provider does not support distributed transactions, which is needed for data modification statements inside an explicit or implicit transaction. A data modification statement can be executed against such a provider only in the case where the statement is a transaction by itself.

Action

Verify that the OLE DB provider specified supports distributed transactions. If the provider does not support distributed transactions, rewrite the data modification statement not to use distributed transactions.

See Also

Errors 7000 - 7999


Error 7392

Severity Level 16
Message Text

Could not start a transaction for OLE DB provider '%ls'.

Microsoft® SQL Server™ also returns this error message if the provider is a SQL Server-specific provider:

Only one transaction can be active on this session.

Explanation

The OLE DB provider returned error 7392 because only one transaction can be active for this session. This error indicates that a data modification statement is being attempted against an OLE DB provider when the connection is in an explicit or implicit transaction, and the OLE DB provider does not support nested transactions. SQL Server requires this support so that, on certain error conditions, it can terminate the effects of the data modification statement while continuing with the transaction.

Action

SET XACT_ABORT is ON. This causes SQL Server to terminate the surrounding transaction when there is an error while processing the data modification statement. If SET XACT_ABORT is ON, SQL Server does not require nested transaction support from the OLE DB provider.

See Also

Errors 7000 - 7999


Error 7399

Severity Level 16
Message Text

OLE DB provider '%ls' reported an error. %ls

Cannot start your application. The workgroup information file is missing or opened exclusively by another user.

Explanation

This error message returned by the Microsoft OLE DB Provider for Jet indicates one of the following:

  • The Microsoft® Access database is not a secured database and the login and password specified was not Admin with no password.
  • The Access database is secured and the HKEY_LOCAL_MACHINE\Software\Microsoft\Jet\4.0\SystemDB registry key is not pointing to the correct Access workgroup file. Secured Access databases have a corresponding workgroup file, including the full path, which should be indicated by the above registry key.
Action

Verify that there is a login mapping for the current Microsoft SQL Server™ login to Admin with no password.

If the Access database being accessed is secured, make sure that the above registry key points to the full pathname of the Access workgroup file.

See Also

Errors 7000 - 7999


Error 7403

Severity Level 16
Message Text

Could not locate registry entry for OLE DB provider '%ls'.

Explanation

This error message indicates that either:

  • The OLE DB provider is not registered properly.

Or

  • The name of the provider used in the provider_name parameter of sp_addlinkedserver (or specified in the OPENROWSET function) is incorrect.
Action

Verify that the provider has been registered correctly and that the provider_name parameter uses the PROGID of the provider.

See Also

Errors 7000 - 7999


Error 7413

Severity Level 16
Message Text

Could not perform a Windows NT authenticated login because delegation is not available.

Explanation

This error message indicates that a distributed query is being attempted for a Microsoft® Windows NT™ authenticated login without an explicit login mapping. In an operating system environment where security delegation is not supported, Windows NT authenticated logins need an explicit mapping to a remote login and password created using sp_addlinkedsrvlogin.

Action

Create explicit mapping to a remote login and password using sp_addlinkedsrvlogin.

See Also

Errors 7000 - 7999


Error 8114

Severity Level 16
Message Text

Error converting data type %ls to %ls.

Explanation

If the error text refers to both DBTYPE_DATE and datetime, respectively, this error message indicates that a DBTYPE_DATE OLE DB data type column from a remote table could not be converted to a datetime value in Microsoft® SQL Server™. The DBTYPE_DATE column most likely has a value outside the range supported by the datetime data type (datetime values must be from January 1, 1753, through December 31, 9999). Because the range of values of the DBTYPE_DATE data type is larger than that of the SQL Server datetime data type, such errors can occur if the column contains values outside of the range supported by SQL Server.

Action

Remove the remote table column of DBTYPE_DATE data type from the query select list or predicate list.

See Also

Errors 7000 - 7999


Error 8501

Severity Level 16
Message Text

MS DTC on server '%.*ls' is unavailable.

Explanation

This error can occur while processing an INSERT, UPDATE, or DELETE statement inside an explicit or implicit transaction. This error typically indicates that the MSDTC service is not running on the local server. Data modification statements in an explicit or implicit transaction require the MSDTC service to be running and the provider’s support of distributed transactions.

Action

Use SQL Server Service Manager to verify that the MSDTC service has been started on the server. For more information, see your Microsoft Distributed Transaction Coordinator documentation.

See Also

Errors 7000 - 7999


Embedded SQL for C Message Overview

When developing and running Embedded SQL for C (ESQL/C) programs, you will see different status and error messages. All message numbers that are returned by ESQL/C are negative numbers.

The messages in the following table are generated by ESQL/C. Because the messages are not generated by Microsoft® SQL Server™, they do not appear in the sysmessages table.

Message number | Run time/ compile time | Description
4998 | C | Attempt to connect to the specified database sever failed.
19031 | C | Unable to open bindfile.
19051 | C | Too many sections.
19101 | R | Statement too long.
19103 | R | Illegal %s value %s. Non-numeric %s value %s. (Invalid number for the timeout value.)
19104 | R/C | Incorrect SQL statement syntax.
19199 | C | ESQL keyword(s) detected in PREPARE statement.
19306 | C | Host variable used but not declared.
19313 | R | Too few host variables.
19324 | C | Host variable may not be used in this context.
19408 | R | Invalid SQL data type for SQL_TYP_DECIMAL.
19413 | R | Data overflow occurred during decimal data conversion.
19422 | R | Unknown SQL Server data type.
19423 | R | Invalid destination data type.
19501 | R | No cursor declared.
19505 | C | Duplicate cursor name: %s.
19508 | R | Cursor is not positioned on a row.
19514 | R | Cursor is not prepared.
19517 | R | Cursor open attempted for non-SELECT prepared statement.
19521 | R | Open cursor failure for section %d of plans.
19523 | R | Failure to locate/close cursor. Section %d, plan %s.
19524 | R | Table for this cursor not updatable.
19525 | R | Attempt to fetch on unopened cursor.
19526 | R | No access plan for this cursor.
19527 | R | Could not get section for this cursor.
19528 | R | Connection for section %d of plan %s has NULL DBPROCESS.
19701 | R | NULL connection name.
 |  | Connection %s not found.
19702 | R | Connection name not found.
 |  | Attempt to close nonexistent connection.
19703 | R | Failed to get DBPROCESS. Autoconnect failure.
19706 | R | Login failure in section %d.
19707 | R | Duplicate connection name.
19822 | R | Improperly initialized user SQLDA.
19911 | C | The SQL data type specified for a host variable is invalid.
19913 | C | The token identifier has already been used.
19917 | C | Invalid or incorrect option to sqlainit().
19946 | C | Cursor %s not declared.
19953 | C | Invalid call type.
19955 | R | Text not found in %s section %u.
19956 | R | Access plan section or statement text not found.
19957 | R | Access plan or statement text not found.
19994 | R | Can’t run next BEGIN DECLARE sections. Statement ignored.
19995 | R | END DECLARE encountered without preceding BEGIN DECLARE statement. Statement ignored.
19999 | C | An internal error occurred.


ODBC Message Overview

SQLERROR returns SQLSTATE values as defined by the X/Open and SQL Access Group SQL CAE specification (1992). SQLSTATE values are strings that contain five characters. The following table lists SQLSTATE values that a driver can return for SQLError.

The character string value returned for SQLSTATE consists of a two-character class value followed by a three-character subclass value. A class value of 01 indicates a warning and is accompanied by a return code of SQL_SUCCESS_WITH_INFO. Class values other than 01, except for the class IM, indicate an error and are accompanied by a return code of SQL_ERROR. The class IM is specific to warnings and errors that derive from the implementation of ODBC. The subclass value 000 in any class is for implementation defined conditions within the given class. The assignment of class and subclass values is defined by SQL-92.

Note Although successful execution of a function is indicated typically by a return value of SQL_SUCCESS, the SQLSTATE 00000 also indicates success.

SQLSTATE | ODBC API (Driver Manager) error
00000 | Success
01000 | General warning
01002 | Disconnect error
01004 | Data truncated
01006 | Privilege not revoked
01S00 | Invalid connection string attribute
01S01 | Error in row
01S02 | Option value changed
01S03 | No rows updated or deleted
01S04 | More than one row updated or deleted
01S05 | Cancel treated as FreeStmt/Close
01S06 | Attempt to fetch before the result returned the first rowset
07001 | Wrong number of parameters
07006 | Restricted data type attribute violation
07S01 | Invalid use of default paramater
08001 | Unable to connect to data source
08002 | Connection in use
08003 | Connection not open
08004 | Data source rejected establishment of connection
08007 | Connection failure during transaction
08S01 | Communication link failure
21S01 | Insert value list does not match column list
21S02 | Degree of derived table does not match column list
22001 | String data right truncation
22002 | Indicator variable required but not supplied
22003 | Numeric value out of range
22005 | Error in assignment
22008 | Datetime field overflow
22012 | Division by zero
22026 | String data, length mismatch
23000 | Integrity constraint violation
24000* | Invalid cursor state
25000 | Invalid transaction state
28000 | Invalid authorization specification
34000 | Invalid cursor name
37000 | Syntax error or access violation
3C000 | Duplicate cursor name
40001 | Serialization failure
42000 | Syntax error or access violation
70100 | Operation aborted
IM001 | Driver does not support this function
IM002 | Data source name not found and no default driver specified
IM003 | Specified driver could not be loaded
IM004 | Driver's SQLAllocEnv failed
IM005 | Driver's SQLAllocConnect failed
IM006 | Driver's SQLSetConnectOption failed
IM007 | No data source or driver specified; dialog prohibited
IM008 | Dialog failed
IM009 | Unable to load translation DLL
IM010 | Data source name too long
IM011 | Driver name too long
IM012 | DRIVER keyword syntax error
IM013 | Trace file error
S0001 | Base table or view already exists
S0002 | Base table not found
S0011 | Index already exists
S0012 | Index not found
S0021 | Column already exists
S0022 | Column not found
S0023 | No default for column
S1000 | General error
S1001 | Memory allocation failure
S1002 | Invalid column number
S1003 | Program type out of range
S1004 | SQL data type out of range
S1008 | Operation canceled
S1009 | Invalid argument value
S1010 | Function sequence error
S1011 | Operation invalid at this time
S1012 | Invalid transaction operation code specified
S1015 | No cursor name available
S1090 | Invalid string or buffer length
S1091 | Descriptor type out of range
S1092 | Option type out of range
S1093 | Invalid parameter number
S1094 | Invalid scale value
S1095 | Function type out of range
S1096 | Information type out of range
S1097 | Column type out of range
S1098 | Scope type out of range
S1099 | Nullable type out of range
S1100 | Uniqueness option type out of range
S1101 | Accuracy option type out of range
S1103 | Direction option out of range
S1104 | Invalid precision value
S1105 | Invalid parameter type
S1106 | Fetch type out of range
S1107 | Row value out of range
S1108 | Concurrency option out of range
S1109 | Invalid cursor position
S1110 | Invalid driver completion
S1111 | Invalid bookmark value
S1C00 | Driver not capable
S1DE0 | No data at execution values pending
S1T00 | Timeout expired
* In SQL Server Enterprise Manager, you may receive the “Invalid cursor state” error message when Microsoft® SQL Server™ runs out of resources while attempting to save selected tables or a database diagram. This error is returned because of insufficient space in your database or transaction log to complete the save process. To correct this problem, check to see if the database or the transaction log is full. If so, increase the size of the database to accommodate the change. Check other system resources or contact your system administrator.

In addition to the standard ODBC error messages located in your ODBC Programmer’s Reference documentation, the SQL Server ODBC driver version 3.70 can return error messages for certain SQLSTATE values, as shown in this table.

SQLSTATE | SQL SERVER DRIVER ERROR | Description
01000 | %ld rows sent to SQL Server. Total sent: %ld. | A batch size of rows have been sent to SQL Server using the BCP API.
01000 | %ld rows successfully bulk-copied to host-file. Total received: %ld. | A batch size of rows have been written to the host file using the BCP API.
01000 | Access to database configured in the DSN has been denied. Default used. | Either the database does not exist or the user does not have permission to access the database. The default database configured for the login ID was used.
01000 | An error has occurred during an attempt to access the log file, logging disabled. | The log file for driver statistics or long-running queries could not be used. The logging of driver statistics or long-running queries has been disabled.
01000 | Connected to backup server. | The SQL Server version 6.5 primary server was not available, so the connection was made to the fallback server.
01000 | Language configured in the DSN is not supported. Default used. | Either the language name is invalid or the language is not installed on the server. The default language configured for the login ID was used.
01000 | Null bit data forced to zero. | A bit field containing a NULL is being loaded to a server that does not support NULL bit data. The field was set to zero.
01000 | Procedure executed with 'EXEC'. No output parameters returned. | The procedure could not be executed as an RPC and output parameters were specified. Because the procedure had to be executed with EXEC, no output parameters will be stored.
01000 | SQL Debugging disabled. | SQL Debugging could not be enabled, probably because the SQL Server is not configured for SQL debugging.
01000 | The ODBC catalog stored procedures installed on server %s are version %s; version %02d.%02d.%4.4d or later is required to ensure proper operation. Please contact your system administrator. | Install the ODBC catalog stored procedures by executing \Msqql7\Install\Instcat.sql.
01000 | Zero length data forced to length 1. | A zero-length binary or character field is being loaded into SQL Server version 6.5 or earlier that does not support zero-length data. The field was forced to a 1 byte blank or binary zero.
01S02 | Cursor concurrency changed. | The application requested a concurrency that could not be honored because of the type of request or query. A different concurrency was used instead.
01S02 | Cursor type changed. | The application requested a cursor type that could not be honored because of the type of request or query. A different cursor type was used instead.
01S02 | Packet size change not honored by server, server size used. | The application requested a nondefault packet size that could not be supported by SQL Server. The server default size was used instead.
01S02 | Packet size changed. | The application requested a nondefault packet size that was outside of the limits of allowable size. Either the smallest or largest packet size was used instead, depending if the requested size was too small or too large.
01S02 | Login timeout changed. | The application requested a login time-out that was too large. The maximum login time-out was used instead.
07006 | Conversions not allowed using bcp_moretext. | The application using bcp_moretext must have the same field type as it does the column type.
08004 | Server rejected the connection; Access to selected database has been denied. | Either the database does not exist or the user does not have permission to access the database.
08004 | Server rejected the connection; Language specified is not supported. | Either the language name is invalid or the language is not installed on SQL Server.
HY024 | Database is invalid or cannot be accessed. | Either the database does not exist or the user does not have permission to access the database.
IM006 | Packet size change not supported by server, default used. | The application requested a nondefault packet size that SQL Server does not support. The client default size was used.
HY000 | All bound columns are read-only. | There must be an updatable column to use SQLSetPos or SQLBulkOperations to change or insert a row.
HY000 | An old netlib (%s) has been detected. Please delete it and restart the application. | The netlib that was being loaded was out of date. The driver requires a newer netlib. The problem could be a netlib in the current directory of the application, which is being loaded instead of the one in the system directory, or it could be that the netlib was not installed properly or is corrupted. If the netlib specified in the error text exists elsewhere than in the Windows system directory, delete it. If the netlib exists only in the system directory, install the client utilities on the client and restart the application.
HY000 | Attempt to bulk-copy a NULL value into a Server column which does not accept NULL values. | The field contains a NULL value, but the column does not allow NULL values.
HY000 | Attempt to bulk-copy an oversized column to the SQL Server. | The length supplied for a column is larger than the column definition in the table.
HY000 | Attempt to read unknown version of BCP format file. | The header line in the bcp format file was not version 4.2, 6.0, or 7.0.
HY000 | Bad bulk-copy direction. Must be either IN or OUT. | The bcp_init call did not specify a valid direction for the eDirection parameter.
HY000 | Bad terminator. | The terminator string supplied in bcp_bind is invalid.
HY000 | Bcp host-files must contain at least one column. | No columns were selected to be loaded.
HY000 | Cannot generate SSPI context. | The driver could not obtain an SSPI context required for integrated security. The native error will contain the Win32 error code.
HY000 | Cannot initialize SSPI package. | The driver could not obtain an SSPI context required for integrated security. The native error will contain the Win32 error code.
HY000 | Communication module is not valid. Driver has not been correctly installed. | The network library .dll is corrupted. Install the client utilities on the client and restart the application.
HY000 | Connection is busy with results for another hstmt. | The SQL Server ODBC driver allows only one active hstmt.
HY000 | Connection is not enabled for BCP. | The application using the BCP API must set the SQLSetConnectAttr or SQL_SS_COPT_BCP attribute before connecting.
HY000 | Failure during closing of connection. | The ConnectionClose function in the network library failed. This problem is typically caused by a network or SQL Server problem.
HY000 | For BCP, all variable-length data must have either a length-prefix or a terminator specified. | bcp_bind was called with SQL_VARYLEN_DATA, but neither a prefix length nor a terminator was specified.
HY000 | Host-file columns may be skipped only when copying into the server. | A bcp out format file specified that a column should be skipped. This is not allowed. Either create a view containing only the desired columns and bcp out from that view, or use the -Q flag to provide a SELECT statement selecting only the desired columns.
HY000 | Incorrect host-column number found in BCP format-file. | The format file contains a column number greater than the number of columns in the table.
HY000 | I/O error while reading bcp data-file. |
HY000 | I/O error while reading BCP format file. |
HY000 | I/O error while writing bcp data-file. |
HY000 | I/O error while writing bcp error-file. |
HY000 | Invalid option. | The eOption parameter to bcp_control was not valid.
HY000 | Non-default parameter not allowed after default parameter. | Parameters to a stored procedure cannot have a non-default value after any preceding parameter has been specified with the default value.
HY000 | Not enough columns bound. | For a bcp out, not all columns of the table were bound. Either create a view which contains only the desired columns and bcp out from that view or, use the -Q flag to provide a SELECT statement selecting only the desired columns.
HY000 | ODBC BCP/Driver version mismatch. | The sqlsrv32.dll and odbcbcp.dll .dlls do not have identical versions. Install the client utilities on the client and restart the application.
HY000 | Protocol error in TDS stream. | The TDS stream from the server is invalid. This problem is typically caused by a SQL Server problem. Check the SQL Server error log.
HY000 | Table contains less rows than first row count. | A starting row number was supplied, but the table on the server did not contain that number of rows. No rows were copied to the host-file.
HY000 | Table contains less rows than last row count. | An ending row number was supplied, but the table on the server did not contain that number of rows.
HY000 | Table has no text/image columns. | bcp_moretext was called, but the table does not contain any text or image columns.
HY000 | TDS buffer length too large. | The TDS stream from the server is invalid. This problem is typically caused by a SQL Server problem. Check the SQL Server error log.
HY000 | Text column data incomplete. | The summation of the lengths supplied by bcp_moretext did not match the length supplied in bcp_bind or bcp_collen.
HY000 | The BCP host-file contains less rows than first row count. | A starting row number was supplied, but the host-file did not contain that number of rows. No rows were loaded.
HY000 | The row length exceeds SQL Server's maximum allowable size. | The summation of the data lengths for a row is larger than the maximum row size.
HY000 | The stored procedure required to complete this operation could not be found on the server (they were supplied with SQL Server). Please contact your system administrator. | Install the ODBC catalog stored procedures by executing \Msqql7\Install\Instcat.sql.
HY000 | Unable to load communication module. Driver has not been correctly installed. | The network library .dll specified for the connection does not exist on this client. Install the client utilities on the client and restart the application.
HY000 | Unable to open BCP host data-file. | The file name specified in the bcp_init call does not exist or is opened by another application.
HY000 | Unable to open BCP error-file. | The error file name specified in the bcp_init call does not exist or is opened by another application.
HY000 | Unable to read driver version. | The driver was unable to read the version block in its .DLL. Install the client utilities on the client and restart the application.
HY000 | Unexpected EOF encountered in BCP data-file. | During a bcp in operation, end-of-file was detected on the data file while in the middle of processing the last row. This is typically caused by having a different number of columns, types, nullability, or sizes between the original table and the table being loaded.
HY000 | Unicode conversion failed. | An error occurred during conversion to or from a Unicode string. The native error will contain the Win32 error code.
HY000 | Unicode conversion failed. The code page of the SQL server must be installed on the client system. | The server code page must exist on the client for proper operation. Either clear the Auto Translate check box for the DSN or install the code page of the server on the client. The server code page can be determined by running EXEC sp_server_info 18.
HY000 | Unknown token received from SQL Server. | The TDS stream from the server is invalid. This error is typically caused by a problem on the server. Check the SQL Server error log.
HY000 | Warning: Partial insert/update. The insert/update of a text or image column(s) did not succeed. | A failure during insertion or update of a text, image, or ntext column occurred. That column will not contain the proper data. Rollback the transaction, if possible.


Open Data Services Error Message Overview

When using Open Data Services, you may see one or more of these error messages.

Error | Severity | Description
17809 | 10 | Could not connect. The maximum number of '%1!ld!' configured user connections are already connected. The system administrator can change the maximum to a higher value using sp_configure.
17824 | 16 | Could not write to ListenOn connection '%1!hs!', loginname '%2!ls!', hostname '%3!ls!'. Connection closed.


Error 17809

Severity Level 10
Message Text

Could not connect. The maximum number of '%1!ld!' configured user connections are already connected. The system administrator can change the maximum to a higher value using sp_configure.

Explanation

This error results when all configured user connections are in use and a request to create another Microsoft® SQL Server™ process occurs. SQL Server is not configured with enough user connections to support all requests. There is one process slot structure (PSS) for each configured user connection.

Action

Use the sp_configure system procedure to increase the number of user connections:

  1. Set the new number for user connections. Type:

    sp_configure 'user connections', new_number

    GO

  2. Instruct SQL Server to accept the values by using the RECONFIGURE statement:

    RECONFIGURE

    GO

  3. Restart SQL Server to activate the changes.

Depending on the exact configuration of your SQL Server installation, each user connection requires 37 KB of memory, whether or not it is in use. Gradually increase the number of user connections until this error no longer occurs. When you change the user connections parameter, you may need to increase the memory parameter.


Error 17824 (ODS)

Severity Level 16
Message Text

Could not write to ListenOn connection '%1!hs!', loginname '%2!ls!', hostname '%3!ls!'. Connection closed.

Explanation

Usually indicates that the specified client disconnected.

Action

Inspect the Windows NT Event Viewer system and application logs for information that may indicate whether or not the problem is related to the server network protocol, network card, or system configuration. Review the Microsoft® SQL Server–specific entries in the application log or the SQL Server error log for relevant network-related errors that may occur in conjunction with this error. If this review does not provide enough information to resolve the problem, special network monitoring tools and a review of the client’s configuration may be needed.

If the problem persists, contact your primary network support provider for assistance.

See Also

Errors 17000 - 17999


Cursors

Microsoft® SQL Server™ statements produce a complete result set, but there are times when the results are best processed one row at a time. Opening a cursor on a result set allows processing the result set one row at a time. SQL Server version 7.0 also introduces assigning a cursor to a variable or parameter with a cursor data type.

Cursor operations are supported on these statements:

DECLARE CURSOR | CLOSE
DECLARE @local_variable | DEALLOCATE
OPEN | UPDATE
SET | DELETE
FETCH | CREATE PROCEDURE

These system functions and system stored procedures also support cursors:

@@CURSOR_ROWS | sp_describe_cursor
@@FETCH_STATUS | sp_describe_cursor_columns
CURSOR_STATUS | sp_describe_cursor_tables
sp_cursor_list |


Error 8101

Severity Level 16
Message Text

An explicit value for the identity column in table '%.*ls' can only be specified when a column list is used and IDENTITY_INSERT is ON.

Explanation

You have attempted to insert a row containing a specific identity value into a table that contains an identity column. However, you did not provide a column list or have SET IDENTITY_INSERT enabled for the specified table.

Action

To insert a specific identity row in a table containing an identity column successfully you must provide a column list and SET IDENTITY_INSERT to ON. The following example inserts identity row 2, where iID is defined as the identity column.

Table: tblTest

iID         strData

1           King

3           Suyama

-- Enable IDENTITY_INSERT.

SET IDENTITY_INSERT tblTest ON

GO

-- Insert the specified identity row using a column list .

INSERT INTO tblTest (iID, strData) values (2, 'Davolio')

GO

-- Disable IDENTITY_INSERT .

SET IDENTITY_INSERT tblTest OFF

GO

See Also

Errors 8000-8999


Topic Unavailable in Transact-SQL Help

This topic is available only in SQL Server Books Online.


 About protecting a Microsoft Access project and a Microsoft SQL Server database

About protecting a Microsoft Access project and a Microsoft SQL Server database

This topic provides reference information about:

Securing a Microsoft SQL Server database

Securing an Access project file

Securing data access pages

Securing Visual Basic for Applications (VBA) code

Securing an application

Securing a Microsoft SQL Server database

Secure SQL Server database objects You can secure data and other database objects that are stored in an SQL Server database (tables, views, stored procedures, and database diagrams) by doing the following:

  • Encrypt views, stored procedures and triggers. You can Encrypt views using the Properties dialog box in the View window to prevent a user from changing the view. You can also encrypt stored procedures and triggers when you edit them by using Transact-SQL Statements (for example, CREATE PROCEDURE...WITH ENCRYPTION).

    Important Once you encrypt a view, you can't change the design of that view. If you anticipate the need to revise an encrypted view, save the SQL in a text file in a secure location before you encrypt it. When you need to revise the encrypted view, you can:

    • Delete the old encrypted view.

    • Create a new view with the same name.

    • Cut and paste the SQL from the saved text file into the SQL pane of the new view.

    • Revise the new view as desired.

    • Save the revised SQL in a new text file in a secure location.

    • Encrypt the new view.
  • Implement full security features using the SQL Server Enterprise Manager. See the SQL Server documentation.

Control SQL Server logins From a Microsoft Access project, you can administer basic security tasks by using the Database Security command (Tools menu, Database Security) to add, edit, or delete server logins, database users, and database roles. You must have SQL Server installed on the same computer as the Access project for these commands to work.

SQL Server provides two security methods for validating logins to the SQL Server database:

  • SQL Server security, which uses SQL Server user names and passwords.

  • Windows NT integrated security, which uses Windows NT account user names. In this case, Windows NT authenticates a user at log in, and SQL Server accepts Windows NT accounts without requiring a secure log in.

If you want to use SQL Server security, select the Use a specific username and password checkbox on the Connection tab of the Data Link Properties dialog box. With this option, you can also choose to not save or save the user name or password with the Access project. Clear the Allow saving of password check box to require users to log in to the SQL Server database each time they open the Access project. Select the Allow saving of password check box, if you want to create an application that doesn't require a user to repeatedly log in to the SQL Server database.

If you wish to use Windows NT authentication to connect from an Access project to an SQL Server database, select the Use Windows NT Integrated Security checkbox on the Connection tab of the Data Link Properties dialog box. You don't need to provide a password because SQL Server uses your network login identity.

Learn about creating an Access project.

Learn about modifying the connection to an Access project.

More information For more information about SQL Server security, see the Microsoft Office 2000/Visual Basic Programmer's Guide or see the SQL Server documentation.

Return to top

Securing an Access project file

Unlike a Microsoft Access database, you can't secure forms, reports, or macros using user-level security, nor can you set a password on the Access Project file. In practice, you distribute copies of an Access project file to your users from a read-only shared folder on a network server or by e-mailing the Access project file. Users should protect their copy of the Access project using their computer's file system and periodically make a backup copy if they add their own forms or reports. If their copy of the Access project file is accidentally or unintentionally altered, users can recopy the file from their backup copy or its central location.

Return to top

Securing data access pages

To protect a data access page and the data it accesses, do the following:

  • Protect the Access project containing the data access page's shortcut, and the data access page's corresponding HTML file by using the file system security of the computer where you have stored these files.

  • Protect the database connected to the data access page by securing the database against unauthorized users, controlling the level of access to the data once a user logs in, and not saving the database password with the data access page.

  • Prevent unauthorized access from a malicious script by using Internet Explorer security options and using three-tier data access.

Learn about protecting a data access page.

Return to top

Securing Visual Basic for Applications (VBA) code

You can protect Visual Basic for Applications (VBA) code in modules and modules behind forms and reports with a password, which you enter once per session. The password prevents unauthorized users from editing, cutting, pasting, copying, exporting, and deleting VBA code.

To protect the intellectual property of your code, you can remove editable VBA code from your database and prevent modifications to the design of forms, reports, and modules by saving it as an ADE file.

Learn about protecting VBA code.

Return to top

Securing an application

Finally, you can prevent curious or malicious end users from accidentally or intentionally damaging your application by hiding database objects from the database window and setting several startup options to control the applications appearance and behavior and protect menus and command bars.

Note that because tables, views, database diagrams, or stored procedures reside in the SQL Server database, you cannot hide these objects in the database window.

Return to top


Protect Visual Basic for Applications code with a password or by creating an ADE file

Learn about protecting Visual Basic for Applications code

Protect Visual Basic for Applications code with a password

Work with ADE files


Secure a Microsoft Access project

What do you want to do?

Learn about protecting a Microsoft Access project and a Microsoft SQL Server database

Protect Visual Basic for Applications code with a password or by creating an ADE file

Protect data access pages

Protect a Microsoft Access application by hiding objects in the database window and using startup options


Work with ADE files

What do you want to do?

Learn about ADE files

Make an ADE file

Learn about references and ADE files


 Clear all the fields in the Filter By Form or Server Filter By Form window

Clear all the fields in the Filter By Form or Server Filter By Form window

  • Click Clear Grid [image] on the toolbar.


 Create an Access project connected to an existing Microsoft SQL Server database

Create an Access project connected to an existing Microsoft SQL Server database

You can create a Microsoft Access project that is connected to a Microsoft SQL Server 6.5, SQL Server 7.0, or Microsoft Data Engine (MSDE) database.

  1. On the File menu, click New.

  2. In the New dialog box, click the General tab, and then click Project (Existing Database).

  3. In the File New Database dialog box, click a location in the Save In box, and type a name in the File Name box; make sure that Microsoft Access Projects (*.adp) appears in the Save As Type box, and then click Create.

  4. On the Connection tab in the Data Link Properties dialog box, enter a server name and the information necessary to log on to the server, and then select the database on the server. For additional information, click Help in the Data Link Properties dialog box.

Note If you are using MSDE on a personal computer, the default server name is the name of your computer, and the default logon ID is sa. Learn more about using MSDE.


 Create an Access project that is not connected to a Microsoft SQL Server database

Create an Access project that is not connected to a Microsoft SQL Server database

You may want to create a Microsoft Access project that is not based on a Microsoft SQL Server database. For example, you can create an Access project application and wait until after you have distributed copies of it before connecting to a Microsoft SQL Server database.

  1. On the File menu, click New.

  2. In the New dialog box, click the General tab, and then click Project (Existing Database).

  3. In the File New Database dialog box, click a location in the Save In box, and then type a name in the File Name box; make sure that Microsoft Access Projects (*.adp) appears in the Save As Type box, and then click Create.

  4. In the Data Link Properties dialog box, click Cancel.


 Create a SQL Server database and connect an Access project to it

Create a SQL Server database and connect an Access project to it

You can use the Microsoft SQL Server Database Wizard to create a Microsoft SQL Server 6.5, Microsoft SQL Server 7.0, or Microsoft Data Engine (MSDE) database. At the same time, you can create a Microsoft Access project that is based on that database.

  1. On the File menu, click New.

  2. In the New dialog box, click the General tab, and then click Project (New Database).

  3. In the File New Database dialog box, click a location in the Save In box, and type a name in the File Name box; make sure that Microsoft Access Projects (*.adp) appears in the Save As Type box, and then click Create.

  4. In the Microsoft SQL Server Database Wizard, type the name of the server you would like to use, the logon ID and password of an account with CREATE DATABASE privileges on the server, and the name of the new SQL Server database. Click Next.

  5. If you are creating a Microsoft SQL Server 6.5 database, enter the database device and size, the transaction log device and size, the database size, and the log size.

  6. Click Finish.

Notes

  • If you are using MSDE on a personal computer, the server name is the name of your computer, and the default logon ID is sa. Learn more about using MSDE.


 Create a specific server filter that's automatically applied when a form or report is opened

Create a specific server filter that's automatically applied when a form or report is opened

You can't use a server filter with a form bound to a stored procedure.

  1. Open a form in Design view.

  2. Display the property sheet for the form, and then set the ServerFilter property to a string expression consisting of a WHERE clause without the WHERE keyword. For example, to find all the records where the Country field contains the value "USA," enter Country = 'USA'.


Delete an Or tab in the Filter By Form or Server Filter By Form window

  1. Click the Or tab you want to delete.

  2. On the Edit menu, click Delete Tab.


 Use Filter By Form after records are retrieved for a form or datasheet

Use Filter By Form after records are retrieved for a form or datasheet

  1. Open a table, query, or form in Datasheet view or open a form in Form view.

  2. Click Filter By Form [image] on the toolbar to switch to the Filter By Form window. (If Server Filter By Form is enabled, Filter By Form will be disabled.)

  3. You can specify criteria for the form, subform, or datasheet that's displayed. Each subform has its own Look For and Or tabs.

  4. Click the field in which you want to specify the criteria that records must meet to be included in the filtered set of records.

  5. Enter your criteria by selecting the value that you're searching for from the list in the field (if the list includes field values), or by typing the value into the field.
    • To find records in which a check box, toggle button, or option button is or is not selected, click the check box or button until it's the way you want. To return it to a neutral position so that it won't be used as criteria for filtering records, continue clicking the check box or button until it's grayed.

    • To find records in which a particular field is empty or not empty, type Is Null or Is Not Null into the field. (You can select these options from the list in fields with a Text or Image data type, and in calculated fields in queries. If the list in all fields displays Is Null and Is Not Null instead of values from the underlying table, the option to display values in the Filter By Form window is unchecked in the Options dialog box. You can change the Filter By Form settings to display field values in the list.)

    • To find records by using a criteria expression, type the expression into the appropriate field. Use the syntax for the ADO Filter property.

    If you specify values in more than one field, the filter returns records only if they contain the same values that you specified in each of those fields.

  6. To specify alternative values that records can have, and include those values in the filter's results, click the Or tab for the datasheet, form, or subform that you're filtering, and enter more criteria.

    7. The filter returns records if they have all the values that are specified on the Look For tab, or all the values specified on the first Or tab, or all the values specified on the second Or tab, and so on.

  7. Click Apply Filter [image] on the toolbar.

Notes

  • When you close a form, Microsoft Access saves its filter. You can reapply the filter when you need it, the next time you open the form. When you close the datasheet for a table or query, however, the filter is lost. You'll have to recreate the filter the next time you need it.

  • If you created a filter on a subform, this filter is also available when you open the form for the subform independently.

  • Filter By Form is not enabled if Server Filter by Form is enabled.


 Filter by selecting values in a form or datasheet after records are retrieved

Filter by selecting values in a form or datasheet after records are retrieved

  1. In a field on a form, subform, or datasheet, find one instance of the value that you want records to contain in order to be included in the filter's results.

  2. How you select the value determines what records the filter returns. Select the value, and then click Filter By Selection [image] on the toolbar.

    Repeat step 2 until you have the set of records you want.

Notes

  • When you close a form, Microsoft Access saves its filter. You can reapply the filter when you need it, the next time you open the form. When you close the datasheet for a table, view, or stored procedure, however, the filter is lost. You'll have to recreate the filter the next time you need it.

  • If you created a filter on a subform, that filter is also available when you open the form for the subform independently.

  • You can also filter for records that do not have a certain value. After selecting a value, right-click it, and then click Filter Excluding Selection.


 Filter records by entering criteria in place in a form or datasheet

Filter records by entering criteria in place in a form or datasheet

  1. Open a table, query, or form in Datasheet view, or a form in Form view.

  2. Do one of the following:
    • To specify the exact field value that you want the filtered records to contain, right-click in the field in the datasheet, form, or subform you're filtering, and then in the Filter For box on the shortcut menu, type the value. For example, to find all the records that have London in the City field, right-click in the City field, and then type London in the Filter For box.

    • To specify more complex criteria, type the complete expression using the syntax for the ADO Filter property.
  3. Do one of the following:
    • To apply the filter and close the shortcut menu, press ENTER.

    • To apply the filter and keep the shortcut menu displayed (so that you can specify additional criteria for the field), press TAB. Enter new criteria, and then press TAB again. Repeat until you have just the records you want.

Note When you close a form, Microsoft Access saves its filter. You can reapply the filter when you need it, the next time you open the form. When you close the datasheet for a table, view, or stored procedure, however, the filter is lost. You'll have to recreate the filter the next time you need it.


 Optimize Filter By Form for all tables, queries, and forms, or Server Filter By Form for all forms

Optimize Filter By Form for all tables, queries, and forms, or Server Filter By Form for all forms

For Filter By Form, these settings affect all tables and queries, and all text box controls whose FilterLookup property is set to Database Default. For Server Filter By Form, these settings affect all text box controls whose FilterLookup property is set to Database Default.

  1. On the Tools menu, click Options.

  2. Click the Edit/Find tab, and then set the Filter By Form Defaults according to the performance that you want to achieve.
    • If the list of values takes too long to display, you can prevent the list from retrieving the unique values for each field by clearing the Records in local snapshot check box, which affects the Filter By Form window, and Records at server, which affects the Server Filter By Form window.

    • If lists aren't displaying the values from fields, check under Show List Of Values In to make sure that the appropriate boxes are selected, or try increasing the number in the Don't Display Lists Where More Than This Number Of Records Read box so that it's greater than or equal to the maximum number of unique values in any field in the underlying table or other record source.


 Optimize Filter by Form or Server Filter By Form performance for a specific form

Optimize Filter by Form or Server Filter By Form performance for a specific form

For each text box control on a form, you can specify whether the values stored in the field appear on its list in the Filter By Form window or Server Filter By Form window.

  1. Open a form in Design view.

  2. Display the property sheet for any text box control.

  3. In the FilterLookup property box, set the property to the setting that will achieve the performance you want.
    • If the list takes too long to display in the Filter By Form window or Server Filter By Form window, either set the FilterLookup property to Never, or set it to Database Default and then make the appropriate changes in the Options dialog box (Tools menu).

    • If the list in the Filter By Form window or Server Filter By Form window isn't displaying the values that are stored in that field, or it's only displaying some of the values, make sure the FilterLookup property isn't set to Never. If the FilterLookup property is set to Database Default or Always, make the appropriate changes in the Options dialog box (Tools menu).


 Optimize performance in the Filter By Form or Server Filter by Form window

Optimize performance in the Filter By Form or Server Filter by Form window

If the lists in fields in the Filter By Form window or Server Filter By Form window take too long to display or they aren't displaying values from the underlying table, you can change their performance. You can change Filter By Form performance for all tables, queries, and forms, or change performance for a specific form; you can change Server Filter By Form performance for all forms or for a specific form. For both types of windows, you can prevent the lists from displaying the underlying table's field values, or change the record limit that determines if the list displays a field's values.

What do you want to do?

Optimize Filter By Form performance for all tables, queries, and forms in the database or optimize Server Filter By Form for all forms

Optimize Filter By Form or Server Filter By Form performance for a specific form


 Sort records locally in Form or Datasheet view

Sort records locally in Form or Datasheet view

  1. In Form view or Datasheet view, click the field you want to use for sorting records. To sort records in a subform, click the field you want to sort.

  2. Do one of the following:
    • To sort in ascending order, click Sort Ascending [image] .

    • To sort in descending order, click Sort Descending [image] .

Notes

  • In a form, you can sort on only one field at a time; in a datasheet, you can select two or more adjacent columns at the same time, and then sort them. Microsoft Access sorts records starting with the leftmost selected column.

  • When you insert new records or edit existing ones, the sort order is automatically removed. You can resort the records when you're done.

  • When you save a form, Microsoft Access saves the sort order. When you save a table or query, the local sort order is lost.


 Use Server Filter By Form to retrieve a subset of records for a form

Use Server Filter By Form to retrieve a subset of records for a form

When using Server Filter By Form, no data is retrieved for the form until you specify the values that you want the filtered records to contain. You can specify criteria for the form or subform that's displayed. Each subform has its own Look For and Or tabs.

  1. In the Server Filter By Form window, click the field in which you want to specify the criteria that records must meet to be included in the filtered set of records.

  2. Enter your criteria by selecting the value that you're searching for from the list in the field (if the list includes field values), or by typing the value into the field.
    • To find records in which a check box, toggle button, or option button is or is not selected, click the check box or button until it's the way you want. To return it to a neutral position so that it won't be used as criteria for filtering records, continue clicking the check box or button until it's grayed.

    • To find records in which a particular field is empty or not empty, type Is Null or Is Not Null into the field. (You can select these options from the list in fields with a Text or Image data type, and in calculated fields in queries. If the list in all fields displays Is Null and Is Not Null instead of values from the underlying table, the option to display lists in the Server Filter By Form window is unchecked in the Options dialog box. You can change the Server Filter By Form settings to display field values in the list.)

    • To find records by using a criteria expression, type the expression into the appropriate field using SQL Server expression syntax.

    If you specify values in more than one field, the filter returns records only if they contain the same values that you specified in each of those fields.

  3. To specify alternative values that records can have, and include those values in the filter's results, click the Or tab for the form or subform you're filtering, and enter more criteria.

    The filter returns records if they have all the values that are specified on the Look For tab or all the values specified on the first Or tab, or all the values specified on the second Or tab, and so on.

  4. Click Apply Server Filter [image] on the toolbar.

Notes

  • Each time you apply the filter, Microsoft Access automatically sets the form's ServerFilter property to a string expression that represents the filter that you defined in the Server Filter By Form window.

  • If you created a filter on a subform, that filter is also available when you open the form for the subform independently.

  • If you're using Server Filter By Form, you can't use Filter By Form.


Ways to select values for a filter to affect what records are returned

You can select all or part of a value in a field. How you select the value determines which records the filter returns.

Selecting | Finds records in which | Example
The entire contents of a field (or placing the insertion point in a field without selecting anything) | The entire contents of that field matches the selection. | You select the value "Berlin" in the City field. The filter returns all records that have Berlin as the city.
Part of a value starting with the first character in a field | The value in that field starts with the same characters that you selected. | In the CompanyName field that contains the value "France restauration," you select only "Fran." The filter returns all records that have a company name starting with "Fran," such as Franchi S.p.A. and Frankenversand.
Part of a value starting after the first character in a field | All or any part of the value in that field contains the same characters you selected. | In the CompanyName field that contains the value "Old World Delicatessen," you select the letters "Del." The filter returns all records that have "del" anywhere in the CompanyName field, such as Ernst Handel, Galería del gastrónomo, and Que Delícia.

Note You can't find records based on the end of the value in a field; however, if you select a word or part of a word that isn't the last characters of that field, records that contain that word or part of a word will be returned. For example, say the Pub_Name field contains the values "Five Lakes Publishing" and "Publishing Times." If you select "Publishing," of the two records only "Publishing Times" will be returned. However, if you select "Pub" or "Publish," the filter will return both records.


I applied a local sort order and now it looks like some records are missing.

If you don't need to work with all the records in the database, create a server filter to limit records to the subset you need. If you do need to work with all the records, raise the limit for the maximum number of records. This limit determines how many records can be retrieved from the database. If the limit is too low, you aren't sorting on a complete set of records.


The local filter didn't return all the records that meet the criteria I specified.

If you don't need to filter on all the records in the database, create a server filter to limit records to the subset that you need. If you do need to filter on all the records, raise the maximum record limit raise. This limit determines how many records can be retrieved from the database. If the limit is too low, you aren't filtering on a complete set of records. For example, if you specify >M in the Last Name field to find all last names that start with M or letters after M in the alphabet, Microsoft Access may have only retrieved records containing last names that start with A through F.


 Why can't I use some of the fields in the Filter By Form or Server Filter By Form window?

Why can't I use some of the fields in the Filter By Form or Server Filter By Form window?

You can't use the following types of fields in the Filter By Form window or Server Filter By Form window because they don't apply to filtering records:

  • A calculated control in a form.

  • A field created with an unbound control or unbound object frame.


 Multi-User Environments and Database Diagrams

Multi-User Environments and Database Diagrams

A multi-user environment is one in which other users can connect and make changes to the same database that you’re working with. As a result, several users might be working with the same database objects at the same time. Thus, a multi-user environment introduces the possibility of your database diagrams being affected by changes made by other users, and vice versa. Such changes could include changes to copies of your diagrams, other users’ diagrams that share database objects with your diagrams, or the underlying database.

A key issue when working with databases in a multi-user environment is access permissions. The permissions you have for the database determine the extent of the work you can do with the database. For example, to make changes to objects in a database, you must have the appropriate write permissions for the database. For more information about permissions in your database, see your database documentation.

Note In addition to assigning permissions and otherwise securing your database objects, you may also want to secure the Microsoft Access project.

As one of multiple users, you may need to address any of the following issues when working with the Database Diagram Designer:

  • Ownership of Database Objects

  • Diagrams Affected by Another User’s Changes

  • Database Objects Deleted by Another User


 Reconciling a Database Diagram with a Modified Database

Reconciling a Database Diagram with a Modified Database

You save your database diagram when you’re ready to update the database to match your diagram. However, if other users have updated the database since you opened your diagram, their changes might affect your diagram and vice versa. In such cases, saving your diagram will automatically:

  • Recreate database objects that are referenced in your diagram but that another user deleted.

  • Preserve triggers that were added to a table; triggers that were deleted from a table are not preserved.

  • Delete an object that another user edited because you deleted it from your diagram.

Saving your diagram will reconcile the database with your diagram by overwriting other users’ changes so that the database will match your diagram.

To reconcile your diagram with a modified database

  1. Save your database diagram.

    If you have not previously saved your diagram, type a name for the diagram in the Save As dialog box and choose OK.

  2. The Save dialog box lists the tables that will be affected when you save your diagram. Choose Yes to continue.

  3. The Database Changes Detected dialog box lists the objects that were modified and will be changed to match your diagram. Choose Yes to save the diagram and accept the list of changes.

Note If your diagram contains tables and columns that were deleted in the database, only their definitions are recreated in the database when you save your diagram. This process does not restore any data that was stored in these objects prior to their deletion.


A blank constraint expression is not allowed

You must enter a constraint in the Constraints Expression dialog box before continuing to define properties for your table.

For more information, see Creating a Unique Constraint.


SQL Verification

The SQL verified successfully.

For more information, see Creating Queries and Specifying Search Criteria.


Are you sure you want to delete the selected relationship from your database?

Answering YES will delete the selected relationship.

For more information about relationships, see Table Relationships and Deleting a Relationship.


Database Diagram Designer Error

No specific help is available for this error. If the text in the error message does not provide enough information for you to solve the problem, please consider the following options:

  • Verify that your settings are correct and try the action again.

  • Use the index to search for keywords related to the error message.

  • If the problem is due to external applications or software, consult the documentation for that area. For example, errors may be caused by your database software, your server setup, or even the network you are using.

  • For database modification errors, such as invalid parameters in a database table, consult your database software for details.


Deleting the selected columns will also delete relationships

The columns you have chosen to delete have existing relationships. Deleting these columns will delete the relationships associated with them.

For more information about relationships, see Table Relationships and Deleting a Relationship.


Error in values list in INSERT INTO clause: '<Os>' not recognized

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

Make sure the number of items in the column list matches the number of items in the values list.

For more information, see Specifying Search Criteria and Creating Queries.


Invalid name. You must provide a name for this object.

An object name is required to continue. Valid names begin with an underscore (_) or a character and contain a combination of characters, numbers, and underscores.

The maximum length for a name based on the server is 32 for Microsoft® SQL Server™ 7.0 and earlier.

In general, avoid names that contain periods.

For more information, see Uniquely Naming Database Objects.


An index can't exist on a blank column.

An index must contain at least one column, and that column must contain unique data values if you are creating a unique index. The column names selected must be entered under Column name in the Selected index box.

For more information, see Indexes and Creating an Index.


 The columns in table '<0s>' do not match an existing enabled primary key or UNIQUE constraint.

The columns in table '<0s>' do not match an existing enabled primary key or UNIQUE constraint.

At least one table participating in a relationship must have either a Primary Key or a Unique Constraint. After setting up a Primary Key or a Unique constraint for one of the tables you’ve selected, you can then define other relationships for that table.

For more information, see Creating a Unique Constraint and Defining a Primary Key.


Query Designer Error

No specific help is available for this error. If the text in the error message does not provide enough information for you to solve the problem, please consider the following options:

  • Verify that your settings are correct and try the action again.

  • Use the index to search for keywords related to the error message.

  • If the problem is due to external applications or software, consult the documentation for that area. For example, errors may be caused by your database software, your server setup, or even the network you are using.

  • For SQL statement errors, consult your database software to ensure you are using the appropriate syntax for your database.


Function argument count error

A function in your query has the wrong number of arguments. Review you query syntax to locate the function.

For more information, see Functions for Expressions and Specifying Search Criteria.


Invalid prefix or suffix characters

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


Invalid escape character

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

Your escape character must be a single character.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


Row limit value should be between <xxx> and <xxx>.

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Entering Search Values.


Bad top value

The top value in your query is invalid or out of range. The value for the top clause must be an integer value if the PERCENT clause is not used. To use the PERCENT clause, just type in the word PERCENT after the numeric value in the cell.

For more information, see Entering Search Values.


Invalid entries must be resolved before you can exit this pane.

Exiting a pane causes other panes to be updated. If there is an invalid entry in the pane you are editing, you need to change or delete it.


Appropriate SQL cannot be generated.

The Query Designer requires that you follow specific rules when designing queries. This error may appear if you have used the Diagram or Grid pane to create a query that cannot be expressed in an SQL statement. Verify the query options you have selected.

For more information, see Creating Queries and Specifying Search Criteria.


SQL statement could not be parsed.

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Creating Queries.


Error in column list

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error in column list: '<Os>' not recognized

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Unable to locate data source.

The specified data source cannot be found. Check the data source location and the entered location.


Too many characters for field width.

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Creating Queries.


This cell contains the text string "<NULL>" which may not be processed correctly.

Use NULL or NOT NULL for comparing null data. Review your query syntax and correct the error before running your query.

For more information, see Creating Queries.


Missing FROM keyword

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


Missing FROM keyword near '<Os>'

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


Error in table name or view name in DELETE clause

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query. Be sure to use Quoted Identifiers as needed.

For more information, see Specifying Search Criteria and Creating Queries.


Error in table name or view name in DELETE clause: <Os>' not recognized.

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query. Be sure to use Quoted Identifiers as needed.

For more information, see Specifying Search Criteria and Creating Queries.


This ALIAS name is already being used.

Alias names must be unique. Enter a different alias name.

For more information, see Creating Table Aliases and Creating Column Aliases.


The specified OR group number is already in use.

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria.


Error before EXISTS clause

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error before EXISTS clause: '<Os>" not recognized

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Missing escape character in LIKE predicate.

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


The NOT keyword may not be used in a column cell.

When entering a NOT EXIST subquery into the Column cell, enter just the EXIST clause. Then go to the Criteria cell and enter False for it.

For more information, see Specifying Search Criteria.


Invalid or missing expression

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


Invalid or missing expression near '<Os>'

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


Data type error in expression

Expressions with different data types can generate errors. To work with different data types in a single expression, you need to convert to the same data type.

For more information, see Creating an Expression.


Error in text following query statement: '<Os>'

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error in FROM clause near '<Os>'

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error before FROM clause

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Missing FROM clause

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


Missing FROM clause near '<Os>'

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


Error in list of function arguments: '<Os>' not recognized

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error after function '<Os>'

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error in GROUP BY clause

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Summarizing and Grouping.


Error in GROUP BY clause near '<Os>'

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Summarizing and Grouping.


Error in HAVING clause

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Querying on Groups of Rows.


Error in HAVING clause near '<Os>'

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Querying on Groups of Rows.


Invalid identifier: '<Os>'

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


Error in list of values in IN clause

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error in list of values in IN clause: '<Os>' not recognized

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Missing INTO keyword

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


Missing INTO keyword near '<Os>'

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


Error in table name or view name in INSERT clause

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query. Be sure to use Quoted Identifiers as needed.

For more information, see Specifying Search Criteria and Creating Queries.


Error in table name or view name in INSERT clause: '<Os>' not recognized

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query. Be sure to use Quoted Identifiers as needed.

For more information, see Specifying Search Criteria and Creating Queries.


Error in values list in INSERT INTO clause

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error in INSERT statement

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error in INSERT statement: '<Os>' not recognized

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Incomplete values list

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


Invalid view name

The View name you’ve specified is not valid. Valid names begin with an underscore (_) or a character and contain a combination of characters, numbers and underscores.

The maximum length for View names is 32 for Microsoft® SQL Server™ 6.5 and 128 for SQL Server 7.0. Do not use names with a period.


Invalid text or symbol

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


Error in join expression

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Querying Using Multiple Tables.


Error in join expression: '<Os>' not recognized

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Querying Using Multiple Tables.


Object <Os> does not exist in the database.

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria.


This table is not in the query definition.

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Creating Queries.


There are not enough columns to match the value list.

An UPDATE or INSERT statement contains more values than the table being updated. Verify your SQL statement to make sure the number of columns matches the table.


There are not enough columns to match the subquery select list.

The SELECT statement needs to include the same number of columns that the embedded subquery returns.

For more information, see Creating Subqueries.


This IS operator can only be used with NULL or NOT NULL.

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria.


The Query Designer supports no more than one data source for this type of query.

Only one data source can be used with this query type.

For more information, see Supported Query Types.


Cannot open encrypted <Os> <1s>.

After a view has been encrypted and closed it can’t be opened again.

For more information, see Creating Views.


There is no unique table in this query.

The query needs to unambiguously identify which table to return values from.


Error in ON clause near '<Os>'

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error in optional FROM clause

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Cannot use LONG data type in this context.

The Query Designer requires that you follow specific rules when designing queries.

For more information, see Creating Queries and Specifying Search Criteria.


Outer join column may not be used with an IN predicate or subquery.

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Creating Outer Joins.


Error in ORDER BY clause

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error in ORDER BY clause near '<Os>'

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Missing pattern in LIKE predicate

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


Error after predicate near '<Os>'

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


<Os> may not be used in this query type.

The action you are attempting is not permitted with the type of query you have selected. Verify the syntax in your query or change the query type.

For more information, see Supported Query Types.


<Os> in expression is not part of the query.

An expression within your query is not properly formed. This often occurs when the criteria expression that you entered doesn't match the available columns for the input sources. Clear the value out and then type in a column reference that matches your input sources.

For more information, see Using Expressions in Queries.


Cannot assign an alias to this field.

An alias can only be created for a suitable column or table. The field you have chosen is not valid. Verify that the settings for the field are correct.

For more information, see Creating Column Aliases or Creating Table Aliases.


Cannot filter this expression.

The expression you’ve entered cannot be filtered. This typically occurs when the user types in a criteria against the * or a criteria against a field that is blank in the QBE. The user should only enter criteria against fields that are already in the QBE.

For more information, see Specifying Search Criteria.


Cannot add this expression to the select list.

There are limitations to what expressions are allowed in the select list. The expression you are trying to add may be invalid. Verify that the syntax in the expression is correct. It is possible that the type of expression is invalid.

For more information, see Using Expressions in Queries.


Cannot update this expression.

The selected expression cannot be updated.

For more information, see Using Expressions in Queries.


You must enter an expression in the Column cell before continuing.

Enter an expression in the column cell.

For more information, see Using Expressions in Queries.


Error in SELECT clause: alias not recognized

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error in SELECT clause: alias '<Os>' not recognized

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error in SELECT clause: expression near '<Os>'

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Missing or incomplete SELECT clause

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


Missing subquery correlation name

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Creating SubQueries.


Unsupported SQL

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria.


<Os> is not supported.

The syntax you entered is valid but is not supported visually by the Query Designer. Be sure to verify your syntax before saving.

For more information, see Supported Query Types.


You may not use a link server object as a destination with this query type.

The selected query type does not support using link server objects as destinations.

For more information, see Creating Queries.


You may not use ALL with CUBE or ROLLUP.

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria.


Data type mismatch - use the CONVERT function

To work with different data types in a single expression, you need to convert to the same data type. One of the data types must be converted before you can continue.

For more information, see Using Expressions in Queries.


Unknown conversion specification

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria.


Unnecessary use of CONVERT function

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria.


Data type mismatch - no conversion possible

To work with different data types in a single expression, you need to convert to the same data type. The selected data types cannot be converted.

For more information, see Using Expressions in Queries.


Illegal use of outer join operator

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Creating Outer Joins.


You may not use an openrowset as a destination with this query type.

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria.


Cannot use column with IMAGE or TEXT data type in this context.

The Query Designer requires that you follow specific rules when designing queries.

For more information, see Creating Queries and Specifying Search Criteria.


<Os> support is not available in this server version.

You have attempted to use a feature that isn’t supported by your server software.


Unable to parse statement.

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria.


Missing subquery

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Creating SubQueries.


Error in destination table specification

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For best results, do not include periods in the destination table specification.

For more information, see Specifying Search Criteria and Creating Queries.


Syntax error in table reference

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Creating Queries and Specifying Search Criteria.


Syntax error in table reference: '<Os>' not recognized.

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria.


Must enter either TRUE or FALSE.

When specifying a criteria for the EXISTS statement, you must use either True for EXISTS or False for NOT EXISTS.

For more information, see Specifying Search Criteria.


Unable to parse expression.

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria.


Unable to parse query text.

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria.


Error following UNION operator

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Unknown column

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria.


Error in table name or view name in UPDATE clause

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query. Be sure to use Quoted Identifiers as needed.

For more information, see Specifying Search Criteria and Creating Queries.


Missing SET keyword

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


Incomplete SET clause

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Specifying Search Conditions.


Error in set list in UPDATE clause

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error in list of values

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Error in list of values: '<Os>' not recognized

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Creating Queries.


Missing subquery or the operator you entered requires parenthesis.

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Creating SubQueries.


View already exists in the database.

Views must have unique names within the database. Enter a different name for the view.

For more information, see Creating Views.


Error in WHERE clause near '<Os>'

There is an error in the syntax of your query. The Query Designer has attempted to locate the source of the error. Review your query syntax and correct the error before running your query.

For more information, see Specifying Search Criteria and Querying on Groups of Rows.


The primary key or UNIQUE constraint cannot be changed until its existing relationships are deleted.

You cannot change a table’s primary key or unique constraint while other foreign key relationships are still in place. To change a table’s primary key or unique constraint, first delete all existing relationships for the table.

For more information, see Deleting a Relationship.


Table '<0s>' is marked for deletion and was not added to the diagram.

A table that has been removed from the diagram will be deleted from the diagram when the changes are saved. The table will not, however, be deleted from the database.

For more information, see Removing a Table from a Database Diagram.

-or-

The table has been deleted from the database by another user and cannot be added to your diagram.

For more information, see Deleting a Table from a Database Diagram and the Database.


One or more selected tables are already on the diagram.

You can only have one copy of any table on a diagram. If you want to create a new table that has some of the same columns as an existing table, you can duplicate an existing table as the first step in creating a new table.

For more information, see Duplicating Tables.


The primary key or Unique constraint cannot be changed while relationships to the existing primary key or Unique constraint are enforced.

You cannot change a table’s primary key or unique constraint while other foreign key relationships are still in place. To change a table’s primary key or unique constraint, first delete all existing relationships for the table.

For more information, see Deleting a Relationship.


Only one clustered index can be created on table '<0s>'.

A clustered index is a special type of index that reorders the way records in the table are physically stored. Therefore only one clustered index can be created on each table.

To create a second index on the same table, change the Clustered property setting before creating the second index.

For more information, see Indexes and Creating a Clustered Index.


Are you sure you want to delete the current selection from your database?

This will permanently delete the table and all its data from your database.

For more information, see Deleting a Table from a Database Diagram and the Database.


Are you sure you want to permanently delete table '<0s>' from your database?

This will permanently delete the table and all its data from the database.

For more information, see Deleting a Table from a Database Diagram and the Database.


Are you sure you want to permanently delete the selected tables from your database?

The table and all its data will be deleted from the database.

For more information, see Deleting a Table from a Database Diagram and the Database.


Are you sure you want to remove the selected table from the diagram?

This will remove the table from the diagram but leave the table in the database.

For more information, see Removing a Table from a Database Diagram.


Are you sure you want to remove the selected tables from the diagram?

This will remove the table from the diagram, but not from your database.

For more information, see Removing a Table from a Database Diagram.


Column '<1s>' in table '<0s>' participates in index '<2s>'. Columns with a datatype of '<3s>' cannot participate in indexes or primary keys.

You have attempted to change the datatype of a column that is part of an index or a primary key. Indexes and primary keys cannot be created for columns with datatypes such as TEXT or IMAGE. To change the datatype, first remove the index or primary key.

For more information see Indexes, Creating a Unique Index, and Defining a Primary Key.


Relationship '<0s>' was modified or deleted since the diagram was loaded.

A modified relationship is about to be saved. It is possible that a table involved in the relationship has been deleted from the database by another user.

Verify whether this relationship is meant to be modified. Changing or deleting a relationship for a table may affect other tables.

For more information about relationships, see Table Relationships and Deleting a Relationship.


The datatype or size property of '<0s>.<1s>' doesn't match '<2s>.<3s>'.

When creating a foreign key relationship, the datatypes of selected columns must match. Select a column with the same datatype and size as the related column.

For more information, see Checking Existing Data when Creating a Relationship.


A relationship cannot contain more than '<0d>' columns.

Select fewer than 16 columns when defining the foreign key relationship.

For more information, see Creating a Relationship Between Tables.


The number of selected columns exceeds the number of columns in the target table.

You cannot create a compound foreign key relationship using more columns than exist in the target table. Make sure the number of columns you’ve selected matches the number in the target table.

For more information, see Creating a Relationship Between Tables.


 A pair of matching columns is required to create a relationship.

A pair of matching columns is required to create a relationship.

You must select matching columns from both tables participating in a foreign key relationship. The columns you have selected don’t match, so they cannot be related.

Choose two columns that match, then attempt to establish the relationship. In order to match, there must be the same number of columns and each partner in a pair of columns must have a comparable data type.

For more information, see Foreign Key and Creating a Relationship Between Tables.


Both sides of a relationship must have the same number of columns.

When creating a composite foreign key relationship, both sides of the relationship must have the same number of columns. Make sure the number of columns you’ve selected matches the number of columns in the target table.

For more information, see Creating a Relationship Between Tables.


Table '<0s>' no longer exists in the database.

The table has been deleted from the database and cannot be used in your diagram.

For more information, see Deleting a Table from a Database Diagram and the Database.


A primary key or index cannot have more than <0d> columns.

Microsoft® SQL Server™ does not allow more than 16 columns in an index. Because a primary key has an associated index, there can be no more than 16 columns in a primary key.

For more information, see Indexes and Defining a Primary Key.


Editing this default will permanently unbind the named default.

Changing from a named default to a default constraint is not allowed on Microsoft® SQL Server™. Refer to the Microsoft SQL Server online documentation for more information.


Only one ROWGUID column is allowed per table.

You have attempted to assign more than one ROWGUID. The ROWGUID is a special property similar to IDENTITY and only one ROWGUID is allowed per table.

For more information, see Setting Column Properties.


A primary key or index cannot be created on columns with a datatype of <0s>.

A column’s datatype defines what kind of information can be stored in a column. Some datatypes such as TEXT or Image cannot be used in an index because servers will not allow indexes on these types of data.

For more information, see Indexes, Creating a Unique Index, and Defining a Primary Key.


The Allow Nulls property can't be set on column '<0s>' because it is an identity column.

All identity columns must contain unique values other than NULL. To make the column an identity column, first clear the Allow Nulls check box on the Column Property dialog box.

For more information, see Changing the Null Option Assigned to a Column.


The Allow Nulls property can't be set on a column that is part of the primary key.

All columns that are part of a table’s primary key must contain unique values other than NULL. To add the column to a primary key, first clear the Allow Nulls check box on the Column Property dialog box.

For more information, see Changing the Null Option Assigned to a Column.


The Default Value property can't be set on column '<0s>' because it is an identity column.

Identity columns contain system-generated sequential values that uniquely identify each row within the table. Therefore, identity columns cannot have default values.

For more information, see Changing a Column’s Identity Properties and Assigning a Default Value to a Column.


The datatype of column '<1s>' in the '<0s>' table can't be changed because it participates in index '<2s>'.

The sum of the lengths of all columns in an index can not exceed 256 bytes. Changing to the specified datatype would exceed the maximum index size of <3d> bytes.

For more information, see Changing the Data Type Assigned to a Column and Creating an Index.


Identity column '<0s>' in table '<1s>' must have a datatype of int, smallint, tinyint, decimal or numeric with scale of 0.

Only certain datatypes can be used for Identity columns. Columns that are Identity columns contain system-generated, sequential values that uniquely identify each row within a table.

For more information, see Changing a Column’s Identity Properties.


The Identity property can't be set on column '<0s>' because it allows null values.

Identity columns contain system-generated sequential values that uniquely identify each row within the table. Therefore, identity columns cannot have null values.

For more information, see Changing a Column’s Identity Properties and Changing the Null Option Assigned to a Column.


The Identity property can't be set on column '<0s>' because it has a default value.

Identity columns contain system-generated sequential values that uniquely identify each row within the table. Therefore, identity columns cannot have default values.

For more information, see Changing a Column’s Identity Properties and Assigning a Default Value to a Column.


The total size of an index or primary key cannot exceed 256 bytes.

The sum of the lengths of all columns in an index can not exceed 256 bytes. Changing to the specified datatype would exceed the maximum index size of <3d> bytes.

For more information, see Indexes, Changing the Data Type Assigned to a Column, and Creating an Index.


The existing relationship must have at least one pair of related columns.

There must be matching columns on both sides of a foreign key relationship. Deleting a column that is part of a relationship will disable the relationship.

For more information, see Creating a Relationship.


 A primary key can't be created on column '<0s>' because it allows null values.

A primary key can't be created on column '<0s>' because it allows null values.

The primary key is used to relate the table to foreign keys in other tables. All columns participating in a primary key must contain defined values other than NULL.

To create a primary key on the selected column, first clear the Allow Nulls check box for the column.

For more information, see Primary Key and Changing the Null Option Assigned to a Column.


A primary key or unique constraint must be defined for table '<0s>' before it can participate in a relationship.

In order to create a foreign key relationship, at least one of the two tables must have a primary key or unique constraint defined. To create the relationship you are attempting to create, first create a primary key for one of the tables.

For more information, see Defining a Primary Key and Creating a Relationship Between Tables.


 The columns in table '<0s>' do not match an existing primary key or UNIQUE constraint.

The columns in table '<0s>' do not match an existing primary key or UNIQUE constraint.

The columns on the primary key side of a foreign key relationship must participate in either a Primary Key or a Unique Constraint. After setting up a Primary Key or a Unique constraint for one of the tables you’ve selected, you can then define other relationships for that table.

For more information, see Creating a Unique Constraint and Defining a Primary Key.


You are not logged in as the database owner or system administrator. You will not be able to save changes to tables that you do not own.

In Microsoft® SQL Server™, each database has a database owner (dbo). The dbo is the creator of the database and has system administrator privileges inside the database. It is the dbo who determines the access and capabilities provided to other users.

If you are not the dbo, you will still be able to create diagrams showing any tables that you have permissions to see, however you won’t be able to perform all edits. Certain edits require SQL Server CREATE TABLE permission.

For more information, see Working in a Multi-User Environment.


Query Designer Window

The Query Designer provides a series of panes in which you can design, edit, and test your query. The panes are synchronized so that changes you make in one are reflected in the others, providing you with both a graphical and textual version of your query at all times.

Each pane provides different features for creating your query. For details about how each pane is used, see the topics listed in the following table

To | See
Add tables or views to your query, select columns to work with, and join tables | Diagram Pane
Specify options for displaying columns, sorting the results, searching, and grouping results | Grid Pane
Enter SQL commands directly | SQL Pane


Query Designer Properties Pages

The Query Designer provides property pages to set options that affect how queries will be executed against your database.

To | See
Control the behavior of a SQL statement stored in the RecordSource property of a form or report by setting its properties using the Query Designer | Query Tab, Properties Window (SQL statements)
Control the behavior of your view by setting its properties in the Query Designer | Query Tab, Properties Window (Views)
Specify options for the joining of tables in a multitable query | Join Line Tab, Properties Window


Database Diagram Designer Properties Pages

The Database Diagram Designer provides property pages where you can set options that affect the database objects in your database diagram.

To | See
Set properties for database tables, including attaching constraints to the table or table columns | Tables Property Page
Set properties for relationships between tables, including choosing primary and foreign keys for the relationship | Relationships Property Page
Set properties for indexes, primary keys, and unique constraints attached to a table | Indexes/Keys Property Page


Querying on Groups of Rows

In addition to creating result sets comprised of individual rows, you can create a result set that includes summary information out of information in groups of rows.

To | See
Learn about creating aggregate queries to summarize and group data. | Summarizing and Grouping
Learn about logical principles for creating aggregate queries. | Summary and Grouping Behavior in the Query Designer
Create an average, sum, or other summary from information in all rows in a table. | Summarizing Values for All Rows in a Table
Count the number of rows that meet specific conditions. | Counting Rows in a Table
Create subsets of summary information by organizing data into groups. | Grouping Rows in Query Results
Create search conditions that apply to groups of rows. | Specifying Conditions for Groups
Use search conditions on both individual rows and on groups of rows. | Using HAVING and WHERE Clauses in the Same Query
Use calculations to create summary information. | Summarizing Values Using Custom Expressions


Choose Name Dialog Box

Enables you to change the system-assigned name of a new table that has not yet been created in the database. This dialog box appears when you:

  • Right-click the database diagram background and choose New Table from the shortcut menu.

    –or–

  • Click the New Table button [image] on the toolbar.

    –or–

  • Click Tables [image] under Objects in the Database window, and then click the New button on the Database window toolbar.

Options

Enter a name for the table

Displays the system-assigned name of the table. Type a new name for the table in the text box.

OK

Creates the table in your database diagram with the name you specified. The table is created in the database when you save the table or diagram.

Cancel

Cancels the creation of the new table.

For more information about creating tables, see Adding a Table to a Database Diagram.


Create Relationship Dialog Box

Enables you to confirm the related columns and to set properties for a new relationship. This dialog box appears when you draw a relationship line between two tables in your database diagram.

Options

Relationship name

Displays the system-assigned name of the relationship. To rename the relationship, type a new name in the text box.

Primary key table

Shows the name of the primary key table in the relationship, followed by the columns that make up the primary key. You can select different columns to match the columns shown under Foreign key table.

Foreign key table

Shows the name of the foreign key table in the relationship, followed by the columns that make up the foreign key. You can select different columns to match the columns shown under Primary key table.

Check existing data on creation

Applies the constraint to existing data in the foreign key table when the relationship is created. An error message will notify you of any data that violates the constraint if this box is selected.

Enable relationship for INSERT and UPDATE

Applies the constraint when data is added to or updated in the foreign key table using these statements.

Enable relationship for replication

Copies the constraint whenever the foreign key table is copied to a different database.

OK

Creates the relationship in your database diagram and sets the properties you selected.

Cancel

Erases the relationship line from your database diagram. The relationship is not created.

For more information about creating relationships between tables, see Creating a Relationship Between Tables.


Column Selection Dialog Box

Enables you to change the Custom view for tables in the database diagram. Custom view shows only the column properties identified by the user. This dialog box appears when you click Modify Custom View from the Diagram menu.

Options

Available columns

Lists all columns existing in the selected database table. The columns listed here depend on the properties of the database table and the type of database. Highlight the desired column and use the arrow buttons to move the columns to the Selected columns box.

Selected columns

Displays the column properties currently defined for the Custom view. Add column properties you want to display and remove those that you do not want to display. Sort the column in this list to determine the order they will be displayed in the table.

Sort

Use the arrows to move highlighted columns up or down in the Selected columns list. The columns will be displayed in the table in the order shown in the Selected columns list.

Save as default

Replaces the current Custom view with the columns selected in this dialog box. If not selected, the column selection specified in the dialog box will be applied to the selected table in the database diagram.

OK

Creates the new Custom view. The selected table is redrawn to display those columns listed in the Selected columns box.

Cancel

Cancels the modification of Custom view.

For more information about Custom views, see Changing a Table View.


Database Changes Detected Dialog Box

Appears if you attempt to save a database diagram but some of the database objects that will be affected by the save action are out of date with the database. Accepting the changes shown in this dialog box updates the database to match your diagram and overwrites other users' changes.

Options

Yes

Updates the database with all the changes shown in the list.

No

Cancels the save action.

Save Text File

Saves the list of database changes in a text file in the default directory for your system and displays a message box with the fully qualified file name of the text file. This file provides a record of the changes you made.

Note Although you cannot undo changes made to a table or database diagram, the changes are not saved to the database until you save the diagram. You can discard any unsaved changes by closing all open diagrams without saving them.

For more information about saving database objects that have changed since you began working in the Database Diagram Designer, see Reconciling a Database Diagram with a Modified Database.


Datatype Change Required Dialog Box

Appears when you change the data type, length, scale, or precision of a column that participates in a relationship.

Options

Yes

Changes the data type property of the related columns shown in the list so that existing relationships are preserved.

No

Cancels the data type change and restores the previous data type to the column you just changed.

Note Although you cannot undo changes made to a database diagram, the changes are not saved to the database until you save the diagram. You can discard any unsaved changes by closing all open diagrams without saving them.


Diagram Pane

The Diagram pane presents a graphic display of the input sources (tables or views) you have selected from the data connection. It also shows any join relationships among them.

In the Diagram pane you can:

  • Add or remove input sources and specify data columns for output.

  • Specify columns for ordering the query (except in views).

  • Specify that you want to group rows in the result set.

  • Create or modify joins between input sources.

When you make a change in the Diagram pane, the Grid pane and SQL pane are updated to reflect your change. For example, if you select a column for output in an input source window in the Diagram pane, the Query Designer adds the data column to the Grid pane and to the SQL statement in the SQL pane.

In this topic, you can find information about:

  • Resizing Input Source Windows

  • Working with Joined Tables

About the Diagram Pane

Each input source appears as a separate window in the Diagram pane. The icon in the title bar of each window indicates what type of input source the window represents, as illustrated in the following table.

Icon | Input source type
 | Table
 | View
 | Subquery (in FROM clause)

The input source’s data columns are listed in its window. Check boxes and symbols appear next to the names of columns to indicate how the columns are being used in the query. ToolTips display information such as data type and size for columns.

Input source window

The following table lists the check boxes and symbols used in input source windows.

Check box or symbol | Description
 | Specifies whether a data column appears in the query result set. Select the column to add it to the results. If (All Columns) is selected, all data columns appear in the output.
 | Indicates that the data column is being used to order the query results (is part of an ORDER BY clause). The icon appears as A-Z if the sort order is ascending or Z-A if sort order is descending. Note ORDER BY is not supported in the Query Designer for views. However you can sort a view's results in Datasheet view.
 | Indicates that the data column is being used to create a grouped result set (is part of a GROUP BY clause) in an aggregate query.
 | Indicates that the data column is included in a search condition for the query (is part of a WHERE or HAVING clause).
 | Indicates that the contents of the data column are being summarized for output (are included in a SUM, AVG, or other aggregate function).

Note The Query Designer will not display data columns for an input source if you do not have sufficient access rights to it or if the database provider cannot return information about it. In such cases, the Query Designer displays only a title bar for the input source.

Resizing Input Source Windows

If you need more room in the Diagram pane, you can resize individual input source windows as you would any window. In addition, you can collapse them so that only the input source names are visible. When you want to work with columns in an input source whose window has been collapsed, you can expand that input source again.

To collapse an input source window

  1. Select the input source.

  2. From the View menu, choose Table, and then choose Name Only.

    –or–

    Click the Minimize button in the window’s title bar.

To expand a collapsed input source window

  1. Select the input source.

  2. From the View menu, choose Table, and then choose Column Names.

    –or–

    Click the Restore button in the window’s title bar.

Working with Joined Tables

If the query involves a join, a join line appears between the data columns involved in the join. If the joined data columns are not displayed (for example, the input source window is minimized or the join involves an expression), the Query Designer places the join line in the title bar of the input source window. The Query Designer displays one join line for each join condition.

Input source windows with join line between them

The shape of the icon in the middle of the join line indicates how the input sources are joined. If the join clause uses an operator other than equal (=), the operator is displayed in the join line icon. The following table lists the icons that can be displayed in a join line.

Join line icon | Description
 | Inner join (created using equal sign).
 | Inner join based on the "greater than" operator. (The operator displayed in the join line icon reflects the operator used in the join.)
 | Outer join in which all rows from the table represented on the left will be included, even if they do not have matches in the related table.
 | Outer join in which all rows from the table represented on the right will be included, even if they do not have matches in the related table.
 | A full outer join in which all rows from both tables will be included, even if they do not have matches in the related table.

Icons on the ends of the join line indicate the type of join. The following table lists the types of joins and the icons that can be displayed on the ends of the join line.

Icon on ends of join line | Description
 | One-to-one join
 | One-to-many join
 | Query Designer cannot determine join type


Grid Pane

The Grid pane allows you to specify query options — such as which data columns to display, how to order the results, and what rows to select — by entering your choices into a spreadsheet-like grid. In the Grid pane you can specify:

  • Columns to display and column name aliases

  • The table that a column belongs to

  • Expressions for calculated columns

  • The sort order for the query (This does not apply to views. However you can sort a view's results in Datasheet view).

  • Search conditions

  • Grouping criteria, including aggregate functions to use for summary reports

Changes you make in the Grid pane are automatically reflected in the Diagram pane and SQL pane. Similarly, the Grid pane is updated automatically to reflect changes made in the other panes.

In this topic, you can find information about:

  • Navigating in the Grid Pane

  • Resizing Grid Columns

  • Editing Values in Cells

  • Adding and Removing Data Columns in the Grid Pane

  • Reordering Grid Rows

About the Grid Pane

The rows in the Grid pane display the data columns used in your query; columns in the Grid pane display query options.

The following table lists the grid columns that can appear in the Grid pane.

Column | Description
Column | Displays either the name of a data column used for the query or the expression for a computed column. This column is locked so that it is always visible as you scroll horizontally.
Alias | Specifies either an alternate name for a column or the name you can use for a computed column.
Table | Specifies the name of the input source for the associated data column. This column is blank for computed columns.
Output Specifies whether a data column appears in the query output.

Note If the database allows, you can use a data column for sort or search clauses without displaying it in the result set.
Sort Type | Specifies that the associated data column is used to sort the query results and whether the sort is ascending or descending. (Not available for views.)
Sort Order | Specifies the sort priority for data columns used to sort the result set. When you change the sort order for a data column, the sort order for all other columns is updated accordingly. (Not available for views.)
Group By Specifies that the associated data column is being used to create an aggregate query. This grid column appears only if you have chosen Group By from the Query menu or have added a GROUP BY clause to the SQL pane.

By default, the value of this column is set to Group By, and the column becomes part of the GROUP BY clause.

When you move to a cell in this column and select an aggregate function to apply to the associated data column, by default the resulting expression is added as an output column for the result set.
Criteria Specifies a search condition (filter) for the associated data column. Enter an operator (the default is "=") and the value to search for. Enclose text values in single quotation marks.

If the associated data column is part of a GROUP BY clause, the expression you enter is used for a HAVING clause.

If you enter values for more than one cell in the Criteria grid column, the resulting search conditions are automatically linked with a logical AND.

To specify multiple search condition expressions for a single database column (for example, (fname > 'A') AND (fname < 'M'), add the data column to the Grid pane twice and enter separate values in the Criteria grid column for each instance of the data column.
Or … | Specifies an additional search condition expression for the data column, linked to previous expressions with a logical OR. You can add more Or … grid columns by pressing the TAB key in the rightmost Or … column.

Navigating in the Grid Pane

You can move from cell to cell in the Grid pane using the mouse or by pressing the TAB or arrow keys. As you scroll, the leftmost grid column (Column) is locked so that you can always see the data column name you are working with.

Resizing Grid Columns

You can resize grid columns to make more room for entries.

To resize a grid column

  • Move the mouse over the divider between grid column headers until it changes to a double-headed arrow, and then either drag the grid column header until the column is the size you want or double-click to auto-size the column.

Editing Values in Cells

You can specify query options by entering values in the appropriate cell of the Grid pane. Certain grid columns — for example, Column or Sort Type — display drop-down lists when you navigate to them.

The check box in the Output grid column indicates whether a data column appears in the result set of the query. If this check box is selected, the data column will appear in the output. If it is not selected, the data column will be used for ordering or searching, but will not appear in the result set.

To remove a query option

  • Move to the appropriate cell, select the value, and then press DELETE.

You can also remove all values in the Grid column at once.

To remove all the values in a Grid column

  • Select the column by clicking its header, and then press DELETE.

Adding and Removing Data Columns in the Grid Pane

You can add and remove data columns to the grid to make them part of the query. The order in which you add them to the query determines the order they appear in the query's results. Adding a data column to the query puts it rightmost in the result set.

To control more precisely where a data column appears in the output or is used in queries, you can insert a data column between existing grid columns.

To add a data column to the grid

  • Drag the column name from the Diagram pane onto the Column column.

    –or–

  • Navigate to a blank cell at the bottom of the Columns column, and then choose the name of a column to add from the drop-down list.

To insert a data column in the grid

  1. Select the row by clicking the box to the left of the Column column.

  2. Press INSERT to insert a blank row.

  3. In the Column column, select the data column to use in the grid.

To remove a data column from the grid

  • Select the row containing the column by clicking the box to the left of the Column column, and then press DELETE. You can select and delete multiple rows at one time.

    The Query Designer removes the selected data column as an output column, sort column, and search condition for the query.

Reordering Grid Rows

The order in which columns appear in the Grid pane determines their order in the result set. The data column that is topmost in the grid appears leftmost in the result set. The bottom row in the grid contains the data column that appears rightmost in the result set.

To control where a data column appears or is used, you can move the corresponding row in the Grid pane.

To reorder grid rows

  1. Select the row by clicking the button to the left of the row.

  2. Drag the row to the new location.

Tip You can also insert a data column into the grid at a specific location by inserting a blank row, and then specifying the data column to insert. For details, see "Adding and Removing Data Columns in the Grid Pane" earlier in this topic.


Indexes/Keys Property Page

This property page contains a set of properties for the indexes, primary keys, and unique constraints attached to the tables in your database diagram. Indexes and constraints are not graphically represented in database diagrams.

Options

Selected index

Shows the name of the first index for the selected table in your diagram. If more than one table is selected in your diagram, only the name of the first index for the first table is visible. To choose a different index to show properties for, expand the Selected index drop-down list.

Type

Shows the index/key object type for the selected table: index, primary key, or unique.

New

Choose this button to create a new index for the selected database table. Enter properties for the index. For more information, see Creating an Index.

Delete

Choose this button to remove the selected index from the table. For more information, see Deleting an Index.

Note You cannot delete a primary key without removing any relationships between tables dependent upon the primary key.

Column name

Shows the list of columns in the index, primary key, or unique constraint. You can add, change, or remove column names in this list.

Index name

Shows the name of the selected index. You can rename the index by entering a new name in this box. For more information, see Renaming an Index.

Index file group

Select the name of the filegroup in which you want to store the selected index. You must have at least one user-defined filegroup for this setting to be enabled. This setting is only available for Microsoft® SQL Server™ 7.0 databases. If you create a database object and do not specify its filegroup, SQL Server will assign it to the default filegroup. Initially, the default filegroup is the Primary filegroup.

For more information on creating and using filegroups, see your SQL Server documentation.

Create UNIQUE

Select this option to create a unique constraint or index for the selected database table. Specify whether you are creating a constraint or index by selecting either the Constraint or Index button.

  • Ignore duplicate key If you create a unique index, you can set this option to ensure each value in an indexed column is unique.

Fill factor

Shows the fill factor that specifies how full each index page can be. If a fill factor is not specified, the database’s default fill factor is used. For more information, see Specifying a Fill Factor for an Index.

  • Pad Index If you specified a Fill Factor of more than zero percent, and you selected the option to create a unique index, you can tell SQL Server to use the same percentage you specified in Fill Factor as the space to leave open on each interior node. By default, SQL Server sets a two-row index size.

Create as CLUSTERED

Select this option to create a clustered index for the selected database table. For more information, see Creating a Clustered Index.

For SQL Server 6.5, the following options are exposed.

Sort Data Options

Identify how the data is ordered in the index as records are added to the index.

  • Sort data (the default) Organizes data in ascending order.

  • Data already sorted Accepts the order of existing data.

  • Reorganize sorted data Reorganizes the data in ascending order. Select this option, for example, when the table becomes fragmented or to rebuild nonclustered indexes.

Duplicate Row Options

Identify how the index should handle duplicate rows.

  • Disallow duplicate rows (the default) Prevents the index from being saved if duplicate rows exist. If duplicate rows exist, an error message will appear.

  • Ignore duplicate rows Deletes duplicate rows from the index as it is being created.

  • Allow duplicate rows Creates the index, even though duplicate rows exist.

Don't automatically recompute statistics

Select this option to tell SQL Server to use previously created statistics. This choice, available only for Microsoft® SQL Server™ 7.0 databases, may not produce optimal results and is not recommended.

For more information, see your SQL Server documentation.


Join Line Tab, Properties Window

Specifies options for the joining of tables in a multitable query.

By default, related tables are joined using an inner join that creates a result set based on rows containing matching information in the join columns. By setting options in the Join Line tab, you can specify a join based on a different operator, and you can specify an outer join.

For more information about joining tables, see Querying Using Multiple Tables.

Options

Table

The names of the tables involved in the join. You cannot change the names of the tables here — this information is displayed for information only.

Column

The names of the columns used for joining the tables. The operator in the Operator list specifies the relationship between the data in the columns. You cannot change the names of the tables here — this information is displayed for information only.

Operator

Specifies the operator used to relate the join columns. To specify an operator other than equal (=), select it from the list. When you close the dialog box, the operator you selected will appear in the diamond graphic of the join line, as in the following diagram:

Symbol for an inner join based on the "greater than" operator

Include rows

Specifies whether unmatched rows appear in the result set.

All rows from <table1>

Specifies that all the rows from the left table appear in the output, even if there are no corresponding matches in the right table. Columns with no matching data in the right table appear as null. Choosing this option is equivalent to specifying LEFT OUTER JOIN in the SQL statement.

All rows from <table2>

Specifies that all the rows from the right table appear in the output, even if there are no corresponding matches in the left table. Columns with no matching data in the left table appear as null. Choosing this option is equivalent to specifying RIGHT OUTER JOIN in the SQL statement.

Selecting both options is equivalent to specifying FULL OUTER JOIN in the SQL statement.

When you select an option to create an outer join, the diamond graphic in the join line changes to indicate that the join is a left outer, right outer, or full outer join.

Note The words "left" and "right" do not necessarily correspond to the position of tables in the Diagram pane. "Left" refers to the table whose name appears to the left of the keyword JOIN in the SQL statement, and "right" refers to the table whose name appears to the right of the JOIN keyword. If you move tables in the Diagram pane, you do not change which table is considered left or right.


Page Setup Dialog Box

Use this dialog box to specify printer settings, such as orientation, scale, and paper size, for a diagram. The print setup options you set for a diagram are saved with the diagram file. When you set the Print scale and Orientation options for the diagram, the page breaks for the diagram are automatically updated.

Options

Name

Specifies the name of the default printer and lists the printers that are set up on your computer.

Properties

Sets the options for the selected printer. The options available depend on the features of the printer.

Status

Shows information about the selected printer.

Type

Displays the model and make information for the selected printer.

Where

Displays the network path or serial port information for the selected printer.

Comment

Displays additional information about the selected printer.

Paper

Size

Specifies the size of the paper or envelope you want to use.

Source

Specifies where the paper you want to use is located in the printer. Different printer models support different paper sources, such as the upper tray, envelope feed, and manual feed.

Orientation

Portrait

Sets a taller-than-wide layout for the document on the page.

Landscape

Sets a wider-than-tall layout for the document on the page.

Print Scale

Percent

Sets the size of the diagram based on the settings as applied to a 100-percent diagram. Choose a percentage between 10 and 400.


Query Definitions Differ Dialog Box

Notifies you that your query cannot be represented graphically in the Diagram and Grid panes and that you will be able to edit your query only in the SQL pane. This dialog box appears when you enter or edit an SQL statement in the SQL pane; and then switch to another pane, verify the query, or attempt to execute the query; and one of the following conditions applies:

  • The SQL command is incomplete or contains one or more syntax errors.

  • The SQL command is valid but is not supported in the graphical panes (for example, a Union query).

  • The SQL command is valid but contains syntax specific to the data connection you are using.

    Tip You can check whether a statement is valid using the Verify SQL Statement button on the Query toolbar.

The dialog box displays a message with the reason that the SQL statement cannot be represented, and then asks how you want to proceed.

Note The Query Definitions Differ dialog box does not appear if you have hidden the Diagram and Grid panes, because the Query Designer assumes that you are editing only in the SQL pane.

Options

Yes

Choose this button to specify that you want to accept the SQL statement, either to edit it further or to execute it. If you accept the statement, the Query Designer dims the Diagram and Grid panes to indicate that they do not represent the statement in the SQL pane.

Note If the statement is correct but not supported graphically by the Query Designer, you can execute it even though it cannot be represented in the Diagram and Grid panes. For example, if you enter a Union query, the statement can be executed but not represented in the other panes.

No

Choose this button to discard the changes in the SQL pane and revert to the most recent SQL statement that can be represented in the Diagram and SQL panes.


 Query Tab, Properties Window

Query Tab, Properties Window

Contains options for controlling the behavior of the query (view, or SQL statement in the RecordSource property of a form or report) you are building or modifying.

Options

Query/View name

Displays the name for the current query. You cannot change the query name in this box. To assign a new name, use the Save As command from the File menu.

Top

(Microsoft SQL Server 7.0 only) Specifies that the query will include a TOP clause, which returns only the first n rows or first n percentage of rows in the result set. The default is that the query returns the first 10 rows in the result set. To specify that the query return the first n percent, you must type "n percent."

Use this box to specify a different number of rows to return or to specify a percentage.

Output all columns

Specifies that all columns from all tables in the current query will be in the result set. Choosing this option is equivalent to specifying an asterisk (*) in place of individual column names.

DISTINCT values

Specifies that the query will filter out duplicates in the result set. This option is useful when you are using only some of the columns from a table and those columns might contain duplicate values, or when the process of joining two or more tables produces duplicate rows in the result set. Choosing this option is equivalent to inserting the word DISTINCT into the statement in the SQL pane.

Encrypt view

Encrypts the view when you save it. You will continue to be able to work with the view until you close the Query Designer.

Important After you close an encrypted view, you will no longer be able to open it in the Query Designer.

GROUP BY extension

Specifies that additional options (WITH CUBE, WITH ROLLUP, ALL) for views based on aggregate queries are available.

WITH CUBE

Specifies that the aggregate query should produce summary values for groups specified in the GROUP BY clause. The groups are created by cross-referencing columns included in the GROUP BY clause, and then applying the query's aggregate function to produce summary values for the additional super-aggregate rows. The With CUBE option is multi-dimensional, creating summaries from all combinations of aggregate functions and columns in the query.

WITH ROLLUP

Specifies that the aggregate query should produce summary values for the groups specified in the GROUP BY clause. The With ROLLUP option is similar to the With CUBE option, but creates only one type of summary for each combination of column and aggregate function.

ALL

Specifies that the aggregate query will include any duplicate rows in the summary.


Relationships Property Page

This property page contains a set of properties for the relationships between the tables in your database diagram.

Options

Selected relationship

Shows the name of the selected relationship in your diagram. If more than one relationship is selected in your diagram, only the name of the first relationship in your selection is visible. Expand the list to choose a different relationship to show properties for.

Relationship name

Shows the name of the selected relationship. You can rename the relationship by entering a new name in this box. For more information, see Renaming a Relationship.

Primary key table

Shows the name of the primary key table in the relationship, followed by the columns that make up the primary key. For information about changing the primary key, see Modifying a Primary Key.

Foreign key table

Shows the name of the foreign key table in the relationship, followed by the columns that make up the foreign key. For information about changing the foreign key, see Modifying a Foreign Key.

Check existing data on creation

Applies the constraint to data that already exists in the database when the relationship is added to the foreign key table.

Enable relationship for INSERT and UPDATE

Applies the constraint to data that is inserted into or updated in the foreign key table. Also prevents a row in the primary key table from being deleted when a matching row exists in the foreign key table.

Enable relationship for replication

Applies the constraint when the foreign key table is copied to a different database.


 Save Dialog Box

Save Dialog Box

Appears when you attempt to save a database diagram, enabling you to confirm the tables that will be saved. This dialog box does not appear when your diagram contains only one modified table.

Options

Yes

Saves all the tables shown in the list.

No

Cancels the save action.

Save Text File

Saves the list of tables in a text file in the default folder for your Microsoft Access project and displays a message box with the fully qualified file name of the text file. This file provides a record of the tables that were affected by the changes you made.

Note Although you cannot undo changes made to a database diagram, the changes are not saved to the database until you save the diagram. You can discard any unsaved changes by closing all open diagrams without saving them.

For more information about the effects of saving tables and diagrams, see Controlling Database Changes.


 Save Incomplete Dialog Box

Save Incomplete Dialog Box

Appears when errors have been encountered while you were trying to save a database diagram or selected tables. This dialog box lists the following: the objects that were successfully saved in the database, the objects that were not saved, and the errors that were encountered.

Options

OK

Returns to the diagram.

Save Text File

Saves the information shown in a text file in the default folder for your Microsoft Access project and displays a message box with the fully qualified file name of the text file. This file provides a record of the database changes that were successfully saved as well as the changes that could not be saved due to errors.

For more information about the errors that can occur, see:

  • Error modifying column properties

  • Invalid cursor state

  • Unable to add constraint

  • Unable to create index

  • Unable to create relationship

  • Unable to modify table

  • Unable to preserve trigger

If the error you want to troubleshoot does not appear in this list, see System errors for additional messages returned by Microsoft® SQL Server™.

Error modifying column properties

Appears when your constraint expression contains an error.

Error text

The name '[column value]' is illegal in this context. Only constants, constant expressions, or variables allowed here. Column names are illegal.

Cause

A default value defined for a character column is not enclosed in single quotation marks (').

Recommended solution

Enclose the value in single quotation marks in the database column's Default Value cell. and then save the table.

Invalid cursor state

Appears when Microsoft® SQL Server™ runs out of resources while attempting to save selected tables or a database diagram.

Error text

Invalid cursor state.

Cause

There is insufficient space in your database or transaction log to complete the save process.

Recommended solution

Check to see if the database or the transaction log is full. If so, increase the size of the database to accommodate the change. Check other system resources or contact your System Administrator.

For more information about increasing the size of your database, see "Controlling Database Growth" in SQL Server Books Online.

Unable to add constraint

Appears when a new constraint has failed on existing data or your constraint expression contains an error. Compare the error text that appears in the Save Incomplete dialog box with the error text shown below to determine the appropriate solution.

Error text

Data exists in table '[table name]', database '[database name]', that violates CHECK constraint '[constraint name]' being added. ALTER command has been aborted.

Unable to create constraint. See previous errors.

Cause

Existing data does not match the check constraint.

Recommended solution

Change the data to match the constraint.

-or-

Clear the Check existing data on creation check box in the Tables property page for the check constraint in question. For more information about disabling this property, see Checking Existing Data when Creating a Relationship.

-or-

Change the constraint expression in the Tables property page for the check constraint in question.

Error text

Invalid column '[column name]' specified in constraint definition. Unable to create constraint. See previous errors.

Cause

The text value in the check constraint expression on the Tables property page is not enclosed in single quotation marks (').

-or-

A column that participates in the check constraint has been renamed. For example, if the original constraint had the expression (cityname = 'Paris') and you renamed the column to city, you would see the same error except that 'cityname' would be the invalid column shown in the error message.

Recommended solution

Correct the expression and save the table.

Error text

Incorrect syntax near '[operator]'.Cause

The expression defined for the check constraint (in the Tables property page) or the default constraint (in the Default Value cell) is not valid SQL syntax. For example, the check constraint expression 'city equals Paris' was typed instead of 'city = Paris'.

Recommended solution

Correct the expression and save the table.

For more information about constraints, see Constraints.

Unable to create index

Appears when a new index has failed on existing data.

Error text

Create unique index aborted on duplicate key. Primary key is '[primary key data]'

Unable to create constraint. See previous errors.

Cause

A unique index was created in the Indexes/Keys property page but duplicate data exists in the database. The value after the phrase "Primary key is" is the first duplicate value that Microsoft® SQL Server™ found as it created the index.

Recommended solution

Remove duplicate data from the database.

-or-

Change the option in the Indexes/Keys property page to allow duplicate rows in the index.

For more information about creating unique indexes, see Creating a Unique Index.

Unable to create relationship

Appears when a new constraint has failed on existing data.

Error text

Data exists in table '[table name]', database '[database name]', that violates FOREIGN KEY constraint '[constraint name]' being added. ALTER command has been aborted.

Unable to create constraint. See previous errors

Cause

Existing data fails the foreign key constraint.

Recommended solution

Change the data that fails the foreign key constraint by running a query to show all the foreign key values that do not match primary key values. For example, to find foreign key values in the job_id column of the employee table that do not match primary key values in the jobs table, run a query with this SQL syntax:

SELECT  employee.emp_id, employee.job_id
FROM  employee LEFT OUTER JOIN jobs ON employee.job_id = jobs.job_id
WHERE (jobs.job_id IS NULL)

For more information, see Creating Queries.

-or-

Clear the Check existing data on creation check box in the Relationships property page. For more information, see Checking Existing Data when Creating a Relationship.

Unable to modify table

Appears when a new constraint has failed on existing data. Compare the error text that appears in the Save Incomplete dialog box with the two errors shown below to determine the appropriate solution.

Error text

The column [column name] in table Tmp_ [table name] may not be null.

Cause

A new database column has been added that doesn't allow null values and doesn't provide a default value. The table name in question appears after "Tmp_".

Recommended solution

Change the column properties. Either select the Allow Nulls property or type a Default Value setting. For more information about setting properties for database columns, see Column Properties.

Error text

Cannot insert the value NULL into column '[column name]', table '[database name] TMP_ [table name]'; column does not allow nulls. INSERT fails.

Command has been aborted.

Cause

The Allow Nulls property on an existing database column has been cleared, but the column has existing null values in it. The table name in question appears after "TMP_".

Recommended solution

Go to the column and select the Allow Nulls property.

For more information about setting properties for database columns, see Column Properties.

Unable to preserve trigger

Appears when your trigger text references a column that has been renamed, deleted, or assigned a different data type.

Error text

Invalid column name '[column name]'.
- Unable to preserve trigger '[trigger name]'.

Cause

A change to the table required the table to be recreated. When a table is recreated, the triggers attached to that table are automatically recreated as well.

Recommended solution

The recommended solution depends on the type of change made to the column referenced by the trigger.

To preserve a trigger that references a renamed column

  • Rename the column to its original name and then save the table. This action will allow the table to be recreated. You can now rename the column, save the table again, and then edit the trigger to fix the renamed columns.

To preserve a trigger that references a deleted column

  1. In the Database window, right-click the name of the table that was changed, then click Triggers.

  2. Select the trigger name from the list, then click Edit to edit the trigger text and save the trigger.

For more information about triggers, see Triggers and your database documentation.

System errors

Two system errors can appear in the Save Incomplete dialog box when you exceed Microsoft® SQL Server™ limitations that are not controlled by the Database Diagram Designer.

Error text

Can't allocate space for object 'Syslogs' in database 'Guest' because the 'logsegment' segment is full. If you ran out of space in Syslogs, dump the transaction log. Otherwise, use ALTER DATABASE or sp_extendsegment to increase the size of the segment.

Cause

This error occurs because there is insufficient log space to complete the transaction.

Recommended solution

Follow the recommendation in the message and delete the transaction log. (Typically this action will not entirely solve the problem.)

-or-

Increase the size of the database to accommodate the change. With large databases, changes that require the recreation of tables (for example, changing a column data type or size) may not be possible using the Database Diagram Designer. You may need to use methods of transferring data that don't require transactions, such as BCP.

Error text

Timeout expired.

Cause

The timeout can occur when you're updating the database with any Transact-SQL changes.

Recommended solution

Try again later to save the diagram.

-or-

Increase the SQL Query Time-out value and try to save the diagram.

To increase the SQL Query Time-out value

  1. From the Tools menu, choose Options.

  2. Click the Advanced tab.

  3. Type a new value in the OLE/DDE timeout (sec) box.

For additional information about Microsoft SQL Server errors, see your database documentation.


SQL Pane

The SQL pane displays the SQL statement for the current query. It is updated automatically as you build your query and reformatted to be easy to read. This pane is not displayed by default. To display the SQL pane, point to Show Panes on the View menu, and then choose SQL.

In the SQL pane you can:

  • Create new SELECT queries by entering SQL statements.

  • Modify the SQL statement created by the Query Designer based on settings you make in the Diagram and Grid panes.

  • Enter statements that take advantage of features specific to the database you are using.

    Note Be sure you know the rules for identifying database objects. For details about SQL Server, see Query Designer Considerations for SQL Server Databases.

Entering Statements in the SQL Pane

You can edit the current query directly in the SQL pane. When you move to another pane, the Query Designer automatically formats your statement, and then changes the Diagram and Grid panes to match your statement.

Note You can enter optimizer hints for SQL statements, but the Query Designer might reformat them. For details about SQL Server, see Query Designer Considerations for SQL Server Databases.

If your statement cannot be represented in the Diagram and Grid panes, and if those panes are visible, the Query Designer displays an error and then offers you two choices:

  • Return to the SQL pane and edit the statement.

  • Discard your changes and revert to the most recent version of the SQL statement.

If you return to the SQL pane and continue editing the statement, the Query Designer dims the other panes to indicate that they no longer reflect the contents of the SQL pane.

You can also use the SQL pane to enter SQL statements that cannot be represented graphically in the Query Designer. In such cases, the Query Designer displays the same behavior as it does when it detects an error — it dims the Diagram and Grid panes to indicate that they do not represent the current statement. You can continue to edit the statement and execute it as you would any SQL statement.

Note If you enter an SQL statement, but then make further changes to the query by changing the Diagram and Grid panes, the Query Designer rebuilds and redisplays the SQL statement. In some cases, this action results in an SQL statement that is constructed differently from the one you originally entered (though it will always yield the same results). This difference is particularly likely when you are working with search conditions that involve several clauses linked with AND and OR.


SQL Syntax Errors Encountered Dialog Box

Notifies you that the Query Designer cannot parse the SQL statement in the SQL pane. This dialog box appears when you enter or edit an SQL statement in the SQL pane; and then switch to another pane, verify the query, or attempt to execute the query; and one of the following conditions applies:

  • The SQL command is incomplete or contains one or more syntax errors.

  • The SQL command is valid but is not supported in the graphical panes (for example, a Union query).

  • The SQL command is valid but contains syntax specific to the data connection you are using.

    Tip You can check whether a statement is valid using the Verify SQL Statement button on the Query toolbar.

The dialog box displays a message with the reason that the SQL statement cannot be parsed. Choose OK to proceed.

Tip If you suspect that your SQL statement contains errors, choose the Verify SQL Syntax button on the Query toolbar to check the statement.


Tables Property Page

This property page contains a set of properties for the tables in your database diagram and their check constraints.

Selected table

Shows the name of the selected table in your diagram. If more than one table is selected in your diagram, only the name of the first table in your selection is visible. Expand the list to choose a different table to show properties for.

Table name

Shows the name of the selected table. To rename the table, enter a new name in this box. For more information, see Renaming a Table.

Table File Group

Select the name of the filegroup in which you want to store the selected table data. You must have at least one user-defined filegroup for this setting to be enabled. This setting is only available for SQL Server 7.0 databases. If you create a database object and do not specify its filegroup, SQL Server will assign it to the default filegroup. Initially, the default filegroup is the Primary filegroup.

For more information on creating and using filegroups, see your SQL Server documentation.

Text File Group

Select the name of the filegroup you want to store the text and images from the selected table in. You must have at least one user-defined filegroup for this setting to be enabled. This setting is only available for SQL Server 7.0 databases. If you create a database object and do not specify its filegroup, SQL Server will assign it to the default filegroup. Initially, the default filegroup is Primary filegroup.

For more information on creating and using filegroups, see your SQL Server documentation.

Check constraints for table and columns

You can add or edit a check constraint in this dialog box. For more information about adding check constraints, see Attaching a New Check Constraint to a Table or Column.

  • Selected constraint Shows a list of the check constraints attached to the selected table.

  • New Creates a new check constraint for the selected table.

  • Delete Deletes the selected check constraint from the database.

  • Constraint expression Shows the SQL syntax of the selected check constraint. For new constraints, you must enter the SQL syntax before exiting this box. You can also edit existing check constraints. For more information, see Defining a Check Constraint Expression.

  • Constraint name Shows the name of the selected constraint. You can rename the constraint by entering a new name in this box.

  • Check existing data on creation When selected, this option ensures that all data that exists in the table before the constraint was created is verified against the constraint.

  • Enable constraint for INSERT and UPDATE Applies the constraint when data is inserted into or updated in the table.

  • Enable constraint for replication Applies the constraint when the table is copied in a different database.


 Unsaved Changes Exist Dialog Box

Unsaved Changes Exist Dialog Box

Appears if you attempt to close the last table of a database diagram or the diagram itself in the Database Diagram Designer when there are unsaved tables in memory.

Options

Yes

Saves all the tables shown in the list.

No

Closes the diagram without saving the changes.

Save Text File

Saves the list of unsaved tables in a text file in the default folder for your Microsoft Access project and displays a message box with the fully qualified file name of the text file. This file provides a record of the tables that were affected by the changes you made.

Note Although you cannot undo changes made to a table or database diagram, the changes are not saved to the database until you save the table or diagram. You can discard any unsaved changes by closing all open diagrams without saving them.

For more information about canceling unsaved changes that exist in memory, see Rolling Back Unsaved Database Changes.