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.

For information about how Transact-SQL interacts with APIs and application components such as transaction control, cursors, and locking, see Overview of Accessing and Changing Data.


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 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. For more information, see Deferred Name Resolution and Compilation.

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. For information about distributed queries, see Distributed Queries. 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. For more information, see Implementing Jobs. 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. For more information, see Parallel Query Processing.

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_helpreplicationdboption
sp_add_agent_profile	sp_helpsubscription
sp_adddistpublisher	sp_helpsubscription_properties
sp_adddistributiondb	sp_link_publication
sp_addmergearticle	sp_mergedummyupdate
sp_addmergefilter	sp_mergesubscription_cleanup
sp_addmergepublication	sp_refreshsubscriptions
sp_addmergepullsubscription	sp_reinitmergepullsubscription
sp_addmergepullsubscription_agent	sp_reinitmergesubscription
sp_addmergesubscription	sp_reinitpullsubscription
sp_addpublication_snapshot	sp_reinitsubscription
sp_addpublisher70	sp_replicationdboption
sp_addpullsubscription	sp_replication_agent_checkup
sp_addpullsubscription_agent	sp_replshowcmds
sp_addsubscriber_schedule	sp_removedbreplication
sp_addsynctriggers	sp_revoke_publication_access
sp_articlesynctranprocs	sp_script_synctran_commands
sp_browsereplcmds	sp_scriptdelproc
sp_change_agent_parameter	sp_scriptinsproc
sp_change_agent_profile	sp_scriptmappedupdproc
sp_change_subscription_properties	sp_scriptupdproc
sp_changedistpublisher	sp_subscription_cleanup
sp_changedistributiondb	MSagent_parameters
sp_changedistributor_property	MSagent_profiles
sp_changedistributor_password	MSarticles
sp_changemergearticle	MSdistpublishers
sp_changemergefilter	MSdistributiondbs
sp_changemergepublication	MSdistribution_agents
sp_changemergepullsubscription	MSdistribution_history
sp_changemergesubscription	MSdistributor
sp_changesubscriber_schedule	MSlogreader_agents
sp_check_for_sync_trigger	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_expired_subscription_cleanup	MSrepl_commands
sp_get_distributor	MSrepl_errors
sp_grant_publication_access	MSrepl_originators
sp_help_agent_default	MSrepl_transactions
sp_help_agent_parameter	MSrepl_version
sp_help_agent_profile	MSsnapshot_agents
sp_helpdistpublisher	MSsnapshot_history
sp_helpdistributiondb	MSsubscriber_info
sp_helpmergearticle	MSsubscriber_schedule
sp_helpmergearticleconflicts	MSsubscriptions
sp_helpmergeconflictrows	MSsubscription_properties
sp_helpmergedeleteconflictrows	sysarticleupdates
sp_helpmergefilter	sysmergearticles
sp_helpmergepublication	sysmergepublications
sp_helpmergepullsubscription	sysmergeschemachange
sp_helpmergesubscription	sysmergesubscriptions
sp_help_publication_access	sysmergesubsetfilters
sp_helppullsubscription	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. For more information, see Monitoring with SQL Server Profiler. 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
For more information, see Setting Configuration Options.

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
For more information, see Setting Configuration Options.

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_check_for_sync_trigger determines if a user-defined trigger or stored procedure is being called in the context of an immediate-updating trigger.

•	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_expired_subscription_cleanup periodically checks the status of all the subscriptions of every publication and identifies those that have expired.

•	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.

•	syscacheobjects contains information on how the cache is being used.

•	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.


Changes to Columns in System Tables

Some of the system tables in Microsoft® SQL Server™ version 7.0 were present in version 6.5. Some of these tables have changed. This section lists the columns that have been dropped or have been assigned different data types. Columns that have been added for the current version are not shown.

The SQL Server system tables are described in detail in System Tables. This list of column changes is provided for informational purposes only. Applications should not be written to query the system tables directly.

Note  The lengths for nchar and nvarchar columns are expressed in characters. sysname is defined as varchar(30) in SQL Server 6.5 and as nvarchar(128) in SQL Server 7.0.

MSsubscriber_info

These columns have been dropped:

commit_batch_size	frequency_relative_interval	active_start_date
status_batch_size	frequency_recurrence_factor	active_end_date
flush_frequency	frequency_subday	retryattempts
frequency_type	frequency_subday_interval	retrydelay
frequency_interval	active_start_time_of_day
These columns have different data types.

Column name	Previous data type	Current data type
publisher	varchar(30)	sysname
subscriber	varchar(30)	sysname
sysalerts

These columns have been dropped:

task_id	has_email_notification	has_pager_notification
These columns have different data types.

Column name	Previous data type	Current data type
name	varchar(60)	sysname
event_source	varchar(100)	sysname
event_id	varchar(20)	int
notification_message	varchar(255)	nvarchar(512)
database_name	varchar(30)	sysname
event_description	varchar(100)	nvarchar(100)
sysarticles

These columns have different data types.

Column name	Previous data type	Current data type
creation_script	varchar(127)	nvarchar(255)
del_cmd	varchar(255)	nvarchar(255)
description	varchar(255)	nvarchar(255)
filter_clause	text	ntext
ins_cmd	varchar(255)	nvarchar(255)
name	varchar(30)	sysname
upd_cmd	varchar(255)	nvarchar(255)
syscharsets

These columns have different data types.

Column name	Previous data type	Current data type
name	varchar(30)	sysname
description	varchar(255)	nvarchar(255)
syscolumns

These columns have different data types.

Column name	Previous data type	Current data type
name	varchar(30)	sysname
colid	tinyint	smallint
prec	tinyint	smalint
scale	tinyint	int
syscomments

These columns have different data types.

Column name	Previous data type	Current data type
colid	tinyint	smallint
text	varchar(255)	nvarchar(4000)
sysconfigures

These columns have different data types.

Column name	Previous data type	Current data type
comment	varchar(255)	nvarchar(255)
sysconstraints

These columns have different data types.

Column name	Previous data type	Current data type
colid	tinyint	smallint
syscurconfigs

These columns have different data types.

Column name	Previous data type	Current data type
comment	varchar(255)	nvarchar(255)
sysdatabases

These columns have been dropped:

logptr	dumptrdate
These columns have different data types.

Column name	Previous data type	Current data type
name	varchar(30)	sysname
status	smallint	int
sysdevices

These columns have been dropped:

mirrorname	stripeset
These columns have different data types.

Column name	Previous data type	Current data type
name	varchar(30)	sysname
sysindexes

These columns have been dropped:

distribution	segment	rowpage
keys1	keys2
These columns have different data types:

Column name	Previous data type	Current data type
first	int	binary(6)
root	int	binary(6)
name	varchar(30)	sysname
maxlen	int	smallint
syslanguages

These columns have different data types.

Column name	Previous data type	Current data type
name	varchar(30)	sysname
alias	varchar(30)	sysname
months	varchar(251)	nvarchar(372)
shortmonths	varchar(119)	varchar(132)
days	varchar(216)	nvarchar(217)
syslogins

These columns have different data types.

Column name	Previous data type	Current data type
name	varchar(30)	nvarchar(128)
dbname	varchar(30)	nvarchar(128)
password	varchar(30)	nvarchar(128)
language	varchar(30)	nvarchar(128)
table

This column has been dropped: langid

These columns have different data types.

Column name	Previous data type	Current data type
description	varchar(255)	nvarchar(255)
sysobjects

This column has been dropped: schema

sysoperators

These columns have different data types.

Column name	Previous data type	Current data type
name	varchar(50)	sysname
email_address	varchar(100)	nvarchar(100)
pager_address	varchar(100)	nvarchar(100)
sysprocesses

This column has been dropped: gid

These columns have different data types.

Column name	Previous data type	Current data type
status	char(10)	nchar(128)
hostname	char(16)	nchar(128)
hostprocess	char(8)	nchar(8)
cmd	char(16)	nchar(16)
table

This column has been dropped: restricted

These columns have different data types.

Column name	Previous data type	Current data type
description	varchar(255)	nvarchar(255)
name	varchar(30)	sysname
sysremotelogins

These columns have different data types.

Column name	Previous data type	Current data type
remoteusername	varchar(30)	nvarchar(128)
sysservers

These columns have different data types.

Column name	Previous data type	Current data type
srvname	varchar(30)	sysname
syssubscriptions

These columns have different data types.

Column name	Previous data type	Current data type
dest_db	varchar(30)	sysname
systypes

These columns have different data types.

Column name	Previous data type	Current data type
name	varchar(30)	sysname
length	tinyint	smallint
prec	tinyint	smallint


+ (Add) (T-SQL)

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
Data Type Conversion	Operators
Expressions


+ (Positive) (T-SQL)

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) (T-SQL)

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
Data Type Conversion	Setting Database Options
Expressions	sp_dboption
Functions	Operators


- (Negative) (T-SQL)

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) (T-SQL)

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) (T-SQL)

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) (T-SQL)

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) (T-SQL)

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) (T-SQL)

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) (T-SQL)

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) (T-SQL)

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) (T-SQL)

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) (T-SQL)

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) (T-SQL)

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) (T-SQL)

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) (T-SQL)

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) (T-SQL)

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) (T-SQL)

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) (T-SQL)

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) (T-SQL)

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) (T-SQL)

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) (T-SQL)

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) (T-SQL)

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
Using Comments


/*…*/ (Comment) (T-SQL)
/*...*/ (Comment) (T-SQL)

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
Using Comments


[ ] (Wildcard - Character(s) to Match) (T-SQL)

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) (T-SQL)

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) (T-SQL)

Matches any single character, and can be used as either a prefix or a suffix.

See Also

LIKE


@@CONNECTIONS (T-SQL)

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 (T-SQL)

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 (T-SQL)

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

Asynchronous Population	Cursor Functions
OPEN


@@DATEFIRST (T-SQL)

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 (T-SQL)

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

Cursor Concurrency	Configuration Functions
Data Types


@@ERROR (T-SQL)

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

Error Handling	sysmessages
@@ROWCOUNT	System Functions
SET @local_variable


@@FETCH_STATUS (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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

Customizing the Lock Time-out	Configuration Functions
SET LOCK_TIMEOUT


@@MAX_CONNECTIONS (T-SQL)

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
user connections Option


@@MAX_PRECISION (T-SQL)

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 (T-SQL)

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

Creating a Stored Procedure	Configuration Functions
@@TRANCOUNT


@@OPTIONS (T-SQL)

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
user options Option


@@PACK_RECEIVED (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 SEATTLE1...check_server

Here is the result set:

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

LONDON2

See Also

Configuring Remote Servers	Configuration Functions


@@ROWCOUNT (T-SQL)

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 (T-SQL)

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 (T-SQL)

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

MSSQLServer Service	Configuration Functions


@@SPID (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 Microsoft® SQL 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. For more information, see Using Identifiers.

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. For more information, see Transaction Log Backups.

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 transferable.

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 (T-SQL)

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	Using Identifiers
DROP PROCEDURE	Programming Stored Procedures
EXECUTE	System Tables


ALTER TABLE (T-SQL)

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, except that changing the length, precision, or scale of a column is allowed if the data type is not changed.

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 (T-SQL)

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, UPDATE} 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
Using Identifiers	Transactions
Programming Stored Procedures


ALTER VIEW (T-SQL)

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	Using Identifiers
CREATE VIEW	Programming Stored Procedures
DROP VIEW	SELECT


AND (T-SQL)

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 (T-SQL)

Compares a scalar value with a single-column set of values. For more information, see SOME | ANY.


APP_NAME (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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	Mathematical Functions
float and real


AVG (T-SQL)

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 (T-SQL)

Backs up an entire database, transaction log, or one or more files or filegroups. For more information about database back up and restore operations, see Backing Up and Restoring Databases.

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. For more information, see Differential Database Backups.

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. For more information about file backups, see Creating File or Filegroup Backups.

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. NO_LOG and TRUNCATE_ONLY are synonyms.

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). For more information, see Character Set.

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

A.    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

Backup Format	sp_addumpdevice
Using Identifiers	sp_configure
DBCC SQLPERF	sp_dboption
RESTORE FILELISTONLY	sp_helpfile
RESTORE HEADERONLY	sp_helpfilegroup
RESTORE LABELONLY	Using Media Sets and Families
RESTORE VERIFYONLY


BEGIN…END (T-SQL)
BEGIN...END (T-SQL)

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). For more information, see Batches and the individual statements being used.

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 (T-SQL)

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	COMMIT WORK
COMMIT TRANSACTION	ROLLBACK WORK
ROLLBACK TRANSACTION	Distributed Transactions
SAVE TRANSACTION


BEGIN TRANSACTION (T-SQL)

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	Transactions
COMMIT TRANSACTION	COMMIT WORK
ROLLBACK TRANSACTION	ROLLBACK WORK
SAVE TRANSACTION


BETWEEN (T-SQL)

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 (T-SQL)

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	DECLARE @local_variable
CAST and CONVERT	DELETE
CREATE TABLE	INSERT
Data Type Conversion	SET @local_variable
Data Types	UPDATE


bit (T-SQL)

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 Type Conversion	UPDATE
Data Types	syscolumns
DECLARE @local_variable


BREAK (T-SQL)

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 (T-SQL)

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. For more information, see bcp Utility.

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

bcp Utility	Parallel Data Load Using bcp
Copying Data Using bcp or BULK INSERT	sp_tableoption
Code Pages and Sort Orders	Using Delimited Identifiers with bcp
Copying Data Between Different Code Pages	Using the bcp Format File


CASE (T-SQL)

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
Data Type Conversion	WHERE
Expressions	System Functions
SELECT


CAST and CONVERT (T-SQL)

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.
Important  By default, SQL Server interprets two-digit years based on a cutoff year of 2049. That is, the two-digit year 49 is interpreted as 2049 and the two-digit year 50 is interpreted as 1950. Many client applications, such as those based on OLE Automation objects, use a cutoff year of 2030. SQL Server provides a configuration option (two digit year cutoff) that changes the cutoff year used by SQL Server and allows the consistent treatment of dates. The safest course, however, is to specify four-digit years.

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

Data Type Conversion	System Functions
SELECT


CEILING (T-SQL)

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 (T-SQL)

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	Data Types
Character Set	sp_dbcmptlevel
Code Pages and Sort Orders	Using char and varchar Data
Data Type Conversion	Using Unicode Data


CHAR (T-SQL)

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 (T-SQL)

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 (T-SQL)

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, 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

Checkpoints and the Active Portion of the Log	SHUTDOWN
recovery interval Option	sp_dboption
Setting Database Options


CLOSE (T-SQL)

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	Cursors


COALESCE (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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	SAVE TRANSACTION
BEGIN DISTRIBUTED TRANSACTION	ROLLBACK TRANSACTION
COMMIT WORK	ROLLBACK WORK
Transactions	@@TRANCOUNT


COMMIT WORK (T-SQL)

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 (T-SQL)

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. For more information, see Using Unicode 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. For more information about the formats for datetime constants, see Using Date and Time Data. 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	Using Constants


CONTAINS (T-SQL)

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.

Remarks

CONTAINS is not recognized as a keyword if the compatibility level is less than 70. For more information, see sp_dbcmptlevel.

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 choc in the ProductName column.

USE Northwind

GO

SELECT ProductName

FROM Products

WHERE CONTAINS(ProductName, ' "choc*" ')

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	WHERE
FREETEXT	Using the CONTAINS Predicate
FREETEXTTABLE


CONTAINSTABLE (T-SQL)

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.

CONTAINSTABLE is not recognized as a keyword if the compatibility level is less than 70. For more information, see sp_dbcmptlevel.

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), beers 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 2 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 > 2

AND FT_TBL.CategoryName <> 'Seafood'

ORDER BY KEY_TBL.RANK DESC

See Also

CONTAINS	WHERE
Full-text Querying SQL Server Data	Rowset Functions
SELECT


CONTINUE (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 nonnull values.

COUNT(DISTINCT expression) evaluates expression for each row in a group and returns the number of unique, nonnull 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 (T-SQL)

Creates a new database and the files used to store the database, or attaches a database from the files of a previously created database.

Note  For more information about backward compatibility with DISK INIT, see Devices (Level 3) in SQL Server Backward Compatibility Details.

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.5 MB (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. For more information, see SQL Server Backward Compatibility Details.

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	Using Raw Partitions


CREATE DEFAULT (T-SQL)

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	Using Identifiers
Batches	INSERT
CREATE RULE	sp_bindefault
CREATE TABLE	sp_help
DROP DEFAULT	sp_helptext
DROP RULE	sp_rename
Expressions	sp_unbindefault


CREATE INDEX (T-SQL)

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. For more information, see 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	SET
CREATE DATABASE	sp_autostats
CREATE STATISTICS	sp_createstats
CREATE TABLE	sp_dbcmptlevel
Data Types	sp_dboption
DBCC SHOW_STATISTICS	sp_helpindex
Designing an Index	sp_spaceused
DROP INDEX	sysindexes
DROP STATISTICS	Transactions
Indexes	UPDATE
INSERT	UPDATE STATISTICS
RECONFIGURE	Using Identifiers


CREATE PROCEDURE (T-SQL)

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. For more information, see Using Identifiers.

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_name 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 be used only on OUTPUT parameters. When you specify a data type of cursor, the VARYING and OUTPUT keywords must also be specified. For more information about 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 OUTPUT 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.

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, add programming logic to the procedure or use a default value (with the DEFAULT keyword of CREATE or ALTER TABLE) for the column.

It is recommended that you explicitly specify NULL or NOT NULL for each column in any CREATE TABLE or ALTER TABLE statement in a stored procedure, such as when creating a temporary table. The ANSI_DFLT_ON and ANSI_DFLT_OFF options control the way SQL Server assigns the NULL or NOT NULL attributes to columns if they are not specified in a CREATE TABLE or ALTER TABLE statement. If a connection executes a stored procedure with different settings for these options than the connection that created the procedure, the columns of the table created for the second connection can have different nullability and exhibit different behaviors. If NULL or NOT NULL is explicitly stated for each column, the temporary tables will be created with the same nullability for all connections that execute the stored procedure.

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 used when the stored procedure is executed. Therefore, any client session settings for SET QUOTED_IDENTIFIER and SET ANSI_NULLS are ignored during stored procedure execution. SET QUOTED_IDENTIFIER and SET ANSI_NULLS statements that occur within the stored procedure do not affect the functionality of the stored procedure.

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. For more information, see Deferred Name Resolution and Compilation.

Deferred Name Resolution and Compatibility Level

SQL Server allows Transact-SQL stored procedures to refer to tables that do not exist at creation time. This ability is called deferred name resolution. If, however, the Transact-SQL stored procedure refers to a table defined within the stored procedure, a warning is issued at creation time if the compatibility level setting (set by executing sp_dbcmptlevel) is 65. An error message is returned at execution time if the table referenced does not exist. For more information, see sp_dbcmptlevel and Deferred Name Resolution and Compilation.

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, 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 returned by 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	Cache Size (pages)
SQLServer: Cache Manager	Cache Hit Ratio
	Cache Pages
	Cache Object Counts*
* These counters are available for various categories of cache objects including adhoc sql, prepared sql, procedures, triggers, and so on.

For more information, see SQL Server: Buffer Manager Object and SQL Server: Cache Manager Object.

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 must be qualified with the name of the object owner if other users are to use the stored procedure. The 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	SELECT
Batches	sp_addextendedproc
Control-of-Flow Language	sp_depends
Cursors	sp_helptext
DBCC	sp_procoption
DECLARE @local_variable	sp_recompile
DROP PROCEDURE	sp_rename
Functions	System Tables
GRANT	Using Comments
Programming Stored Procedures	Using Variables and Parameters


CREATE RULE (T-SQL)

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	Using Identifiers
Batches	sp_bindrule
CREATE DEFAULT	sp_help
CREATE TABLE	sp_helptext
DROP DEFAULT	sp_rename
DROP RULE	sp_unbindrule
Expressions	WHERE


CREATE SCHEMA (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 keyword is not valid if the database compatibility level is 65 or lower. For more information, see sp_dbcmptlevel.

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,060. If you create tables with varchar, nvarchar, or varbinary columns in which the total defined width exceeds 8,060 bytes, the table is created but a warning message appears. Trying to insert more than 8,060 bytes into such a row or to update a row so that its total row size exceeds 8,060 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 (T-SQL)

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. For more information, see Deferred Name Resolution and Compilation.

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_depends
ALTER TRIGGER	sp_help
CREATE TABLE	sp_helptext
DROP TRIGGER	sp_rename
Using Identifiers	sp_spaceused
Programming Stored Procedures


CREATE VIEW (T-SQL)

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. For more information, see Scenarios for Using Views.

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_depends
ALTER VIEW	sp_help
DELETE	sp_helptext
DROP VIEW	sp_rename
Using Identifiers	System Tables
INSERT	UPDATE
Programming Stored Procedures	Using Views with Partitioned Data


CURRENT_TIMESTAMP (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 Type Conversion	SET @local_variable
Data Types


CURSOR_STATUS (T-SQL)

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
Using Identifiers


Cursors (T-SQL)

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
See Also

Cursors


DATABASEPROPERTY (T-SQL)

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	Internal version number of the Microsoft® SQL Server™ code with which the database was created. For internal use only by SQL Server tools and in upgrade processing.	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 (T-SQL)

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 and Creating User-defined Data Types.

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	SET
CREATE TABLE	sp_bindefault
Data Type Conversion	sp_droptype
DECLARE @local_variable	sp_bindrule
EXECUTE	sp_help
expression	sp_rename
Expressions	sp_unbindefault
Functions	sp_unbindrule
LIKE	Using Unicode Data


Data Type Precedence (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 you specify only the last two digits of the year, values that are less than or equal to the last two digits of the value of the two digit year cutoff configuration option are in the same century as the cutoff year. Values that are greater than the last two digits of the value of this option are in the century that precedes the cutoff year. For example, if two digit year cutoff is 2049 (default), 49 is interpreted as 2049 and 2050 is interpreted as 1950. To avoid ambiguity, use four-digit years.

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	Time Formats
Data Types	Date and Time Functions


DATEDIFF (T-SQL)

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 you specify only the last two digits of the year, values that are less than or equal to the last two digits of the value of the two digit year cutoff configuration option are in the same century as the cutoff year. Values that are greater than the last two digits of the value of this option are in the century that precedes the cutoff year. For example, if two digit year cutoff is 2049 (default), 49 is interpreted as 2049 and 2050 is interpreted as 1950. To avoid ambiguity, use four-digit years.

For information about specifying time values, see Time Formats. 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 (T-SQL)

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. For information about specifying time values, see Time Formats.

If you specify only the last two digits of the year, values that are less than or equal to the last two digits of the value of the two digit year cutoff configuration option are in the same century as the cutoff year. Values that are greater than the last two digits of the value of this option are in the century that precedes the cutoff year. For example, if two digit year cutoff is 2049 (default), 49 is interpreted as 2049 and 2050 is interpreted as 1950. To avoid ambiguity, use four-digit years.

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 (T-SQL)

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 you specify only the last two digits of the year, values that are less than or equal to the last two digits of the value of the two digit year cutoff configuration option are in the same century as the cutoff year. Values that are greater than the last two digits of the value of this option are in the century that precedes the cutoff year. For example, if two digit year cutoff is 2049 (default), 49 is interpreted as 2049 and 2050 is interpreted as 1950. To avoid ambiguity, use four-digit years.

For information about specifying time values, see Time Formats. 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 (T-SQL)

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	DECLARE @local_variable
CAST and CONVERT	DELETE
CREATE TABLE	INSERT
Data Type Conversion	SET @local_variable
Data Types	UPDATE


DAY (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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. For more information, see Using 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 roll back 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	Space Allocation and Reuse
sp_dboption	DBCC


DBCC CHECKCATALOG (T-SQL)

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. For more information, see Using 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 (T-SQL)

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. For more information, see Using Identifiers.

NOINDEX

Specifies that nonclustered indexes for nonsystem tables should not be checked. NOINDEX 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 roll back 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

Physical Database Architecture	System Tables
sp_helpdb	DBCC


DBCC CHECKFILEGROUP (T-SQL)

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. For more information, see Using 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	sp_helpfilegroup
Physical Database Architecture	sysfilegroups
sp_helpfile	DBCC


DBCC CHECKIDENT (T-SQL)

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. For more information, see Using 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 (T-SQL)

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. For more information, see Using 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 roll back 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

Table and Index Architecture	DBCC


DBCC DBREPAIR (T-SQL)

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 (T-SQL)

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. For more information, see Using 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	Table and Index Architecture
CREATE TABLE	DBCC


DBCC dllname (FREE) (T-SQL)

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

Execution Characteristics of Extended Stored Procedures	sp_helpextendedproc
sp_addextendedproc	Unloading an Extended Stored Procedure DLL
sp_dropextendedproc	DBCC


DBCC HELP (T-SQL)

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 (T-SQL)

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 (T-SQL)

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	sqlmaint Utility
DBCC CHECKDB	DBCC


DBCC OPENTRAN (T-SQL)

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. For more information, see Using 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 (T-SQL)

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 (T-SQL)

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	sp_tableoption
Memory Architecture	DBCC


DBCC PROCCACHE (T-SQL)

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

Memory Architecture	DBCC


DBCC ROWLOCK (T-SQL)

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

Architecture Enhancements	DBCC


DBCC SHOWCONTIG (T-SQL)

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	Space Allocation and Reuse
DBCC DBREINDEX	sysindexes
DROP INDEX	Table and Index Architecture
OBJECT_ID	DBCC


DBCC SHOW_STATISTICS (T-SQL)

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. For more information, see Using 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
Distribution Statistics	UPDATE STATISTICS
DROP STATISTICS	USE
sp_autostats	DBCC
sp_createstats


DBCC SHRINKDATABASE (T-SQL)

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. For more information, see Using 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. For more information about when truncation occurs, see Truncating the Transaction Log. For more information about determining virtual log file sizes, see Virtual Log Files.

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
Physical Database Files and Filegroups


DBCC SHRINKFILE (T-SQL)

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. For more information, see Using 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 EMPTYFILE 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. For more information on when truncation occurs, see Truncating the Transaction Log. For more information about determining virtual log file sizes, see Virtual Log Files.

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
Physical Database Files and Filegroups


DBCC SQLPERF (T-SQL)

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 (T-SQL)

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

Space Allocation and Reuse	DBCC
Table and Index Architecture


DBCC TEXTALLOC (T-SQL)

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

Space Allocation and Reuse	DBCC
Table and Index Architecture


DBCC TRACEOFF (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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	OBJECT_ID
DBCC PINTABLE	sp_tableoption
Memory Architecture	DBCC


DBCC UPDATEUSAGE (T-SQL)

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. For more information see Using 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	Table and Index Architecture
sysindexes	DBCC


DBCC USEROPTIONS (T-SQL)

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

Customizing Transaction Isolation Level	SET TRANSACTION ISOLATION LEVEL
SET	DBCC


DEALLOCATE (T-SQL)

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
Cursors	OPEN
DECLARE @local_variable


decimal and numeric (T-SQL)

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 Type Conversion	SQL Server Startup Options
Data Types	UPDATE
DECLARE @local_variable


DECLARE @local_variable (T-SQL)

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. For more information, see Using 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. For more information, see Using 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. For more information about using local variables in statement blocks, see Using BEGIN...END.

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. For more information about cursor variables, see Transact-SQL Cursors.

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
Functions


DECLARE CURSOR (T-SQL)

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. For more information, see Using 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. For more information, see Implicit Cursor Conversions.

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. For more information, see Using 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. For more information, see Setting Database Options.

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. For more information, see Implicit Cursor Conversions.

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	FETCH
CLOSE	OPEN
Cursors	SELECT
DEALLOCATE	sp_configure


DEGREES (T-SQL)

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 (T-SQL)

Removes rows from a table.

Syntax

DELETE
[FROM ]
{
  table_name WITH ( <table_hint_limited> [...n])
 | view_name
 | 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
| MAXDOP
| 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

Is the name 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

Is the name 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 capabilities needed by the provider, see UPDATE and DELETE Requirements for OLE DB Providers. 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.

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. For more information, see max degree of parallelism Option.

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	INSERT
CREATE TRIGGER	SELECT
Cursors	TRUNCATE TABLE
DROP TABLE	UPDATE


DENY (T-SQL)

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	Backward Compatibility
Preventing Access by Denying Permissions


DIFFERENCE (T-SQL)

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 (T-SQL)

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 (T-SQL)

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. For more information, see Using 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 (T-SQL)

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. For more information, see Using 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 and dll_admin 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 (T-SQL)

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. For more information, see Using 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 (T-SQL)

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. For more information, see Using 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 (T-SQL)

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. For more information, see Using 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 (T-SQL)

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 (T-SQL)

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. For more information, see Using 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 and ddl_admin 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 (T-SQL)

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. For more information, see Using 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 (T-SQL)

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) (T-SQL)
ELSE (IF...ELSE) (T-SQL)

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
Batches	IF...ELSE
Control-of-Flow Language


END (BEGIN…END) (T-SQL)
END (BEGIN...END) (T-SQL)

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	Control-of-Flow Language
Batches	ELSE (IF...ELSE)
BEGIN...END	IF...ELSE
CREATE TRIGGER	WHILE


EXECUTE (T-SQL)

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 nonfully qualified name of the stored procedure to call. Procedure names must conform to the rules for identifiers. For more information, see Using Identifiers. The names of extended stored procedures are always case-sensitive, regardless of the code page or sort order of the server.

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 the 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; therefore, 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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 Conversion	WHERE
Data Type Precedence


FETCH (T-SQL)

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
Cursors	OPEN
DEALLOCATE


FILE_ID (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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	DECLARE @local_variable
CAST and CONVERT	DELETE
CREATE TABLE	INSERT
Data Type Conversion	SET @local_variable
Data Types	UPDATE


FLOOR (T-SQL)

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 (T-SQL)

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 (T-SQL)

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.

FREETEXT is not recognized as a keyword if the compatibility level is less than 70. For more information, see sp_dbcmptlevel.

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 (T-SQL)

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.

FREETEXTTABLE is not recognized as a keyword if the compatibility level is less than 70. For more information, see sp_dbcmptlevel.

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
Full-text Querying SQL Server Data


FROM (T-SQL)

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.

[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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

These scalar functions return information about cursors.

@@CURSOR_ROWS	@@FETCH_STATUS
CURSOR_STATUS
See Also

Functions


Date and Time Functions (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 used 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 (T-SQL)

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. For more information, see osql Utility, isql Utility, and SQL Server Query Analyzer.

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

See Also

Batches	Writing Readable Code
Batch Processing


GOTO (T-SQL)

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	Using Identifiers


GRANT (T-SQL)

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 role can grant any permissions in any database. Object owners can grant permissions for the objects they own. Members of the db_owner or db_securityadmin roles can grant any permissions on any statement or object in their database.

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_datareader	db_datawriter	db_ddladmin	db_backupoperator	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

Allowing Access by Granting Permissions	DENY
REVOKE	sp_dropgroup
sp_addgroup	sp_dropuser
sp_addlogin	sp_helpgroup
sp_adduser	sp_helprotect
sp_changedbowner	sp_helpuser
sp_changegroup


GROUP BY (T-SQL)

Divides a table into groups. Groups can consist of column names or results or computed columns. For more information, see SELECT.


GROUPING (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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) (T-SQL)

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) (T-SQL)

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	SELECT @local_variable
@@IDENTITY	Using System Functions
IDENTITY (Property)


IF…ELSE (T-SQL)
IF...ELSE (T-SQL)

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 (T-SQL)

For information about the image data type, see ntext, text, and image.

See Also

Data Type Conversion	Data Types


IN (T-SQL)

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 (T-SQL)

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)
CREATE INDEX	UPDATE
DELETE	WHERE
INSERT	Metadata Functions


INDEX_COL (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

Adds a new row to a table or a view.

Syntax

INSERT [INTO]
{
  table_name WITH ( <table_hint_limited> [...n])
 | view_name
 | 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

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

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 multitable 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.

Note  For SQL Server version 7.0, execute_statement cannot contain an extended stored procedure that returns text or image columns. This behavior is a change from earlier versions of SQL Server.

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. For more information about inserting text and image data, see Using text, ntext, and image Functions.

•	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 (T-SQL)

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	DECLARE @local_variable
CAST and CONVERT	DELETE
CREATE TABLE	INSERT
Data Type Conversion	SET @local_variable
Data Types	UPDATE


IS_MEMBER (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

Returns the part of a character string starting at a specified number of characters from the left.

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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	Monetary Data
Data Type Conversion	SET @local_variable
Data Types	UPDATE
DECLARE @local_variable	Using Monetary Data


MONTH (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 Type Conversion	sp_dbcmptlevel
Data Types	UPDATE
DECLARE @local_variable	Using Unicode Data
DELETE	WHERE
INSERT


NEWID (T-SQL)

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:

Value of @myid is: 6F9619FF-8B86-D011-B42D-00C04FC964FF

Note  The value returned by NEWID is different for each computer. This number is shown only for illustration.

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	Overview of Replication
CAST and CONVERT	uniqueidentifier
CREATE TABLE	System Functions
Data Types


Northwind Sample Database (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

Column_name	Data type	Nullable	Default	Check	Key/index
CustomerID	nchar(5)	no			Composite PK nonclust1, FK  Customers(CustomerID)
CustomerTypeID	nchar(10)	no			Composite PK nonclust1,  FK  CustomerDemographics (CustomerTypeID)

1The composite primary key is defined on CustomerID, CustomerTypeID.


CustomerDemographics (T-SQL)

Column_name	Data type	Nullable	Default	Check	Key/index
CustomerTypeID	nchar(10)	no			PK nonclust.
CustomerDesc	ntext	yes


Employees (T-SQL)

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		yes1
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
1The 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 (T-SQL)

Column_name	Data type	Nullable	Default	Check	Key/index
EmployeeID	int	no			Composite PK nonclust.
TerritoryID	nvarchar(20)	no			Composite PK nonclust.


Order Details (T-SQL)

Column_name	Data type	Nullable	Default	Check	Key/index
OrderID	int	no			Composite PK, clust1, FK  Orders(OrderID)2
ProductID	int	no			Composite PK, clust1, FK  Products(ProductID)3
UnitPrice	money	no	0	yes4
Quantity	smallint	no	1	yes5
Discount	real	no	0
1The composite, primary key, clustered index is defined on OrderID and ProductID. 2There are also two nonclustered indexes on OrderID. 3There are also two nonclustered indexes on ProductID. 4The UnitPrice CHECK constraint is defined as (UnitPrice >= 0). 5The Quantity CHECK constraint is defined as (Quantity > 0). The table-level CHECK constraint is defined as (Discount >= 0 and Discount < = 1).


Orders (T-SQL)

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
1There are also two nonclustered indexes on CustomerID. 2There are also two nonclustered indexes on EmployeeID. 3There is also a nonclustered index on ShipVia.


Products (T-SQL)

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	yes3
UnitsInStock	smallint	yes	0	yes4
UnitsOnOrder	smallint	yes	0	yes5
ReorderLevel	smallint	yes	0	yes6
Discontinued	bit	no	0

1There are two nonclustered indexes on SupplierID.

2There are two nonclustered indexes on CategoryID.

3The UnitPrice CHECK constraint is defined as (UnitPrice >=).

4The UnitsInStock CHECK constraint is defined as (UnitsInStock >=).

5The UnitsOnOrder CHECK constraint is defined as (UnitsOnOrder >=).

6The ReorderLevel CHECK constraint is defined as (ReorderLevel >=).


Region (T-SQL)

Column_name	Data type	Nullable	Default	Check	Key/index
RegionID	int	no			PK nonclust.
RegionDescription	nchar(50)	no


Shippers (T-SQL)

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 (T-SQL)

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
Territories (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 Type Conversion	SET @local_variable
Data Types	UPDATE
DECLARE @local_variable	Using Unicode Data


NULLIF (T-SQL)

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 (T-SQL)

For information about the numeric data type, see decimal and numeric.

See Also

Data Type Conversion	Data Types


OBJECT_ID (T-SQL)

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 (T-SQL)

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.

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 (T-SQL)

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.
TableDeleteTriggerCount	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.
TableHasActiveFulltextIndex	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.
TableInsertTriggerCount	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.
TableUpdateTriggerCount	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 (T-SQL)

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. For more information, see Asynchronous Population.

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 (T-SQL)

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
Distributed Queries	sp_serveroption
FROM	UPDATE
INSERT	WHERE
OPENROWSET	Rowset Functions
SELECT


OPENROWSET (T-SQL)

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. For more information, see SQL Server OLE DB Programmer’s Reference.

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
Distributed Queries	sp_serveroption
FROM	UPDATE
INSERT	WHERE
OPENQUERY	Rowset Functions
SELECT


Operators (T-SQL)

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 (T-SQL)

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 (T-SQL)

Specifies the sort order used on columns returned in a SELECT statement. For more information, see SELECT.


PARSENAME (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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( )
1The 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]'). 2The 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 (T-SQL)

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 (T-SQL)

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.
1The information shown here is not the actual data. It is the file name from which the bitmap (image data) was loaded. 2The 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 (T-SQL)

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'
1The 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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

For information about the real data type, see float and real.

See Also

Data Type Conversion	Data Types


RECONFIGURE (T-SQL)

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

Setting Configuration Options	sp_configure


REPLACE (T-SQL)

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 (T-SQL)

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 (T-SQL)

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	EXIT	PRIMARY
ALL	FETCH	PRINT
ALTER	FILE	PRIVILEGES
AND	FILLFACTOR	PROC
ANY	FLOPPY	PROCEDURE
AS	FOR	PROCESSEXIT
ASC	FOREIGN	PUBLIC
AUTHORIZATION	FREETEXT	RAISERROR
AVG	FREETEXTTABLE	READ
BACKUP	FROM	READTEXT
BEGIN	FULL	RECONFIGURE
BETWEEN	GOTO	REFERENCES
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	STATISTICS
CONVERT	LIKE	SUM
COUNT	LINENO	SYSTEM_USER
CREATE	LOAD	TABLE
CROSS	MAX	TAPE
CURRENT	MIN	TEMP
CURRENT_DATE	MIRROREXIT	TEMPORARY
CURRENT_TIME	NATIONAL	TEXTSIZE
CURRENT_TIMESTAMP	NOCHECK	THEN
CURRENT_USER	NONCLUSTERED	TO
CURSOR	NOT	TOP
DATABASE	NULL	TRAN
DBCC	NULLIF	TRANSACTION
DEALLOCATE	OF	TRIGGER
DECLARE	OFF	TRUNCATE
DEFAULT	OFFSETS	TSEQUAL
DELETE	ON	UNCOMMITTED
DENY	ONCE	UNION
DESC	ONLY	UNIQUE
DISK	OPEN	UPDATE
DISTINCT	OPENDATASOURCE	UPDATETEXT
DISTRIBUTED	OPENQUERY	USE
DOUBLE	OPENROWSET	USER
DROP	OPTION	VALUES
DUMMY	OR	VARYING
DUMP	ORDER	VIEW
ELSE	OUTER	WAITFOR
END	OVER	WHEN
ERRLVL	PERCENT	WHERE
ERROREXIT	PERM	WHILE
ESCAPE	PERMANENT	WITH
EXCEPT	PIPE	WORK
EXEC	PLAN	WRITETEXT
EXECUTE	PRECISION
EXISTS	PREPARE
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. For more information, see Using Identifiers.

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

Using Reserved Keywords	SET QUOTED_IDENTIFIER


RESTORE (T-SQL)

Restores an entire database and transaction log, database file(s), or a transaction log. For more information about database back up and restore operations, see Backing Up and Restoring Databases.

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. For more information, see Copying Databases.

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. For more information, see Creating and Applying Transaction Log Backups.

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. For more information, see Using Standby Servers.

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. For more information, see Transaction Log Backups.

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). For more information, see Character Set.

For more information about database recovery, see Backing Up and Restoring Databases.

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. For more information, see Restoring File or Filegroup Backups.

•	Create and maintain a warm backup server or standby server. For more information about standby servers, see Using Standby Servers.

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. For more information, see Restoring the master Database.

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 HEADERONLY
bcp Utility	RESTORE LABELONLY
Data Types	RESTORE VERIFYONLY
Using Identifiers	sp_addumpdevice
RESTORE FILELISTONLY	Understanding Media Sets and Families


RESTORE FILELISTONLY (T-SQL)

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

Backing Up and Restoring Databases	RESTORE HEADERONLY
BACKUP	RESTORE LABELONLY
Data Types	RESTORE VERIFYONLY
Using Identifiers	Understanding Media Sets and Families
RESTORE


RESTORE HEADERONLY (T-SQL)

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.
BackupDescription	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
DatabaseVersion	int	Version of the database from which the backup was created.	NULL
DatabaseCreationDate	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
CheckpointLSN	numeric(25,0)	Log sequence number of the most recent checkpoint at the time the backup was created.	NULL
DatabaseBackupLSN	numeric(25,0)	Log sequence number of the most recent full database backup.	NULL
BackupStartDate	datetime	Date and time that the backup operation began.	Media Write Date.
BackupFinishDate	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
CompatibilityLevel	tinyint	Compatibility level setting of the database from which the backup was created.	NULL
SoftwareVendorId	int	Software vendor identification number. For SQL Server, this number is 4608 (or hexadecimal 0x1200).	Software vendor identification number.
SoftwareVersionMajor	int	Major version number of the server that created the backup set.	Major version number of the software that created the backup set.
SoftwareVersionMinor	int	Minor version number of the server that created the backup set.	Minor version number of the software that created the backup set.
SoftwareVersionBuild	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	RESTORE
RESTORE FILELISTONLY	RESTORE VERIFYONLY
RESTORE LABELONLY	Backing Up and Restoring Databases
Understanding Media Sets and Families	Using Identifiers
Data Types


RESTORE LABELONLY (T-SQL)

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.
FamilySequenceNumber	int	Sequence number of this family.
MediaFamilyId	uniqueidentifier	Unique identification number for the media family.
MediaSequenceNumber	int	Sequence number of this media in the media family.
MediaLabelPresent	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

Backing Up and Restoring Databases	RESTORE FILELISTONLY
BACKUP	RESTORE VERIFYONLY
Data Types	Understanding Media Sets and Families
RESTORE	Using Identifiers


RESTORE VERIFYONLY (T-SQL)

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

Backing Up and Restoring Databases	RESTORE HEADERONLY
BACKUP	RESTORE LABELONLY
Data Types	System Tables
RESTORE	Understanding Media Sets and Families
RESTORE FILELISTONLY	Using Identifiers


RETURN (T-SQL)

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 (T-SQL)

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 (T-SQL)

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

Backward Compatibility	GRANT
Deactivating Established Access by Revoking Permissions	sp_helprotect
DENY


RIGHT (T-SQL)

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 (T-SQL)

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 synchronous STATIC or INSENSITIVE cursors or asynchronous STATIC cursors that have been fully populated. 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
Cursor Locking	SAVE TRANSACTION
COMMIT TRANSACTION	Transactions


ROLLBACK WORK (T-SQL)

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	ROLLBACK TRANSACTION
BEGIN TRANSACTION	SAVE TRANSACTION
COMMIT TRANSACTION	Transactions
COMMIT WORK


ROUND (T-SQL)

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 (T-SQL)

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 (T-SQL)

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

Batches	INSERT
BEGIN TRANSACTION	ROLLBACK TRANSACTION
COMMIT TRANSACTION	ROLLBACK WORK
COMMIT WORK	SELECT
CREATE PROCEDURE	Transaction Savepoints
CREATE TRIGGER	UPDATE
DELETE


Search Condition (T-SQL)

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 statement, 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	FREETEXTTABLE
CASE	Full-text Querying SQL Server Data
CONTAINSTABLE	FROM
Cursors	Operators (Logical)
DELETE	UPDATE
Expressions


SELECT @local_variable (T-SQL)

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 (T-SQL)

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. For more information, see Transactions and Explicit Transactions.

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. For more information, see Using 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 Condition.

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. For more information, see max degree of parallelism Option.

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	INSERT
CONTAINSTABLE	SET TRANSACTION ISOLATION LEVEL
CREATE TRIGGER	Subquery Fundamentals
CREATE VIEW	sp_dboption
DELETE	Join Fundamentals
EXECUTE	UNION
Expressions	UPDATE
FREETEXT	Using Variables and Parameters
FREETEXTTABLE	WHERE
Full-text Querying SQL Server Data


SELECT Examples (T-SQL)

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	Subquery Fundamentals
Expressions	UNION
CREATE TRIGGER	UPDATE
CREATE VIEW	Using Variables and Parameters
INSERT	LIKE
Distributed Queries	WHERE


SESSION_USER (T-SQL)

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 (T-SQL)

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. For more information, see Using 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 select_statement contains an ORDER BY in which 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 the SET @cursor_variable = CURSOR... syntax is used, 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.

For more information, see DECLARE CURSOR.

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
Expressions	Using Variables and Parameters


SET (T-SQL)

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 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 affect the statements that follow 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, 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 QUOTED_IDENTIFIER and 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 batches are used, 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 that contains the stored procedure. For example, when stored procedure db1.dbo.sp1 calls stored procedure db2.dbo.sp2, 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, 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 that 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 (T-SQL)

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 Microsoft 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 IMPLICIT_TRANSACTIONS to 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 that 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 (T-SQL)

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 and Setting Database Options.

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, the other option is set OFF. Therefore, either 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, that setting (SET ANSI_NULL_DFLT_OFF or SET ANSI_NULL_DFLT_ON) takes effect. If both options are set OFF, Microsoft® SQL Server™ uses the value of the ANSI null default option of sp_dboption.

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 (T-SQL)

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 and Setting Database Options.

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, the other option is set OFF. Therefore, either ANSI_NULL_DFLT_OFF or ANSI_NULL_DFLT_ON can be set ON, or both can be set OFF. If either option is ON, that setting (SET ANSI_NULL_DFLT_OFF or SET ANSI_NULL_DFLT_ON) takes effect. If both options are set OFF, Microsoft® SQL Server™ uses the value of the ANSI null default option of sp_dboption.

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 Microsoft 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 (T-SQL)

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 and Setting Database Options.

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 uses 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 Microsoft 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 (T-SQL)

Controls the way the column stores values shorter than the defined size of the column, and the way 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, Microsoft® SQL Server™ 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 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 Microsoft 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 (T-SQL)

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 in which 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 or Setting Configuration Options.

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, SQL Server uses the ANSI warnings setting of sp_dboption. For more information, see sp_dboption or Setting Database Options.

ANSI_WARNINGS should be set to ON for executing distributed queries.

The SQL Server ODBC driver and Microsoft 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 (T-SQL)

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 (T-SQL)

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
SET CONCAT_NULL_YIELDS_NULL (T-SQL)

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

Setting Database Options	SET
sp_dboption


SET CURSOR_CLOSE_ON_COMMIT (T-SQL)

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; however, an asynchronous STATIC cursor that has not been fully populated is closed. 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, Microsoft® 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 SQL Server ODBC driver both set CURSOR_CLOSE_ON_COMMIT to 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	Setting Database Options
COMMIT TRANSACTION	sp_dboption
ROLLBACK TRANSACTION	SET


SET DATEFIRST (T-SQL)

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 (T-SQL)

Sets the order of the dateparts (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 (T-SQL)

Controls the way the 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 (T-SQL)

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 is set to 60 or 65, executing this statement does nothing. However, if the compatibility level is set to 70, executing this statement does nothing, and SQL Server returns a warning message. For information about setting compatibility levels, see sp_dbcmptlevel.

See Also

CREATE TABLE	UPDATE
DELETE	SET
INSERT


SET FIPS_FLAGGER (T-SQL)

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, Microsoft® 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 (T-SQL)

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 (T-SQL)

Makes the Microsoft® SQL Server™ query optimizer process a 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 query 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 the way SQL Server processes the tables to satisfy the query.

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 (T-SQL)

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 (T-SQL)

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, it 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 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 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	Transactions
GRANT	TRUNCATE TABLE
Implicit Transactions	UPDATE
INSERT	SET


SET LANGUAGE (T-SQL)

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)
sp_helplanguage	SET


SET LOCK_TIMEOUT (T-SQL)

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
Locking Hints


SET NOCOUNT (T-SQL)

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 Microsoft® 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 the osql utility 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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 nonzero 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 and Setting Configuration Options.

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 (T-SQL)

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. For more information, see Using 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 Microsoft 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, SQL Server uses the quoted identifier setting of sp_dboption. For more information about database settings, see sp_dboption and Setting Database Options.

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.    Use the 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.    Use the quoted identifier setting with single and double quotes

This example shows the way 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 (T-SQL)

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. For more information on remote store procedures, see Remote Stored Procedure Architecture. The option does not apply to distributed queries that execute a stored procedure on a linked server defined using sp_addlinkedserver. For more information on distributed queries, see Distributed Query Architecture.

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	Transactions
Distributed Transactions	SET


SET ROWCOUNT (T-SQL)

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

SET


SET SHOWPLAN_ALL (T-SQL)

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, 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 table shows the columns that the output contains.

Column name	Description
StmtText	For rows that 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 that is determined by the physical operator. For more information about logical and physical operators, see Logical and Physical Operators.
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 the way 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 (T-SQL)

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 table shows the column that the output contains.

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.
For more information about the physical and logical operators that can be seen in showplan output, see Logical and Physical Operators.

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.

This 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 (T-SQL)

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 (T-SQL)

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 SHOWPLAN_ALL	SET STATISTICS TIME
SET STATISTICS IO	SET


SET STATISTICS TIME (T-SQL)

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 (T-SQL)

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 gigabytes (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 SQL Server ODBC driver and Microsoft 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 (T-SQL)

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

Specifies that 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

Places a range lock 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 the 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

Adjusting Transaction Isolation Levels	SELECT
DBCC USEROPTIONS	SET
Isolation Levels


SET XACT_ABORT (T-SQL)

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. For more information, see Distributed Queries and Distributed Transactions.

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 (T-SQL)

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 (T-SQL)

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	sqlservr Application
sp_lock	Stopping SQL Server
sp_who


SIGN (T-SQL)

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 (T-SQL)

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 (T-SQL)

For information about the smalldatetime data type, see datetime and smalldatetime.

See Also

Data Type Conversion	Data Types


smallint (T-SQL)

For information about the smallint data type, see int, smallint, and tinyint.

See Also

Data Type Conversion	Data Types


smallmoney (T-SQL)

For information about the smallmoney data type, see money and smallmoney.

See Also

Data Type Conversion	Data Types


SOME | ANY (T-SQL)

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)
Expressions	SELECT
Functions	WHERE


SOUNDEX (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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

Managing Security	System Functions


SUSER_NAME (T-SQL)

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

Managing Security	System Functions


SUSER_SID (T-SQL)

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
Managing Security


SUSER_SNAME (T-SQL)

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
Managing Security


System Stored Procedures (T-SQL)

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.
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_expired_subscription_cleanup
sp_addmergearticle	sp_generatefilters
sp_addmergefilter	sp_getmergedeletetype
sp_addmergepublication	sp_get_distributor
sp_addmergepullsubscription	sp_grant_publication_access
sp_addmergepullsubscription_agent	sp_help_agent_default
sp_addmergesubscription	sp_help_agent_parameter
sp_addpublication	sp_help_agent_profile
sp_addpublication_snapshot	sp_help_publication_access
sp_addpublisher70	sp_helparticle
sp_addpullsubscription	sp_helparticlecolumns
sp_addpullsubscription_agent	sp_helpdistpublisher
sp_addsubscriber	sp_helpdistributiondb
sp_addsubscriber_schedule	sp_helpdistributor
sp_addsubscription	sp_helpmergearticle
sp_addsynctriggers	sp_helpmergearticleconflicts
sp_addtabletocontents	sp_helpmergeconflictrows
sp_article_validation	sp_helpmergedeleteconflictrows
sp_articlecolumn	sp_helpmergefilter
sp_articlefilter	sp_helpmergepublication
sp_articlesynctranprocs	sp_helpmergepullsubscription
sp_articleview	sp_helpmergesubscription
sp_browsereplcmds	sp_helppublication
sp_change_agent_parameter	sp_helppullsubscription
sp_change_agent_profile	sp_helpreplicationdboption
sp_changearticle	sp_helpsubscriberinfo
sp_changedistpublisher	sp_helpsubscription
sp_changedistributiondb	sp_helpsubscription_properties
sp_changedistributor_password	sp_link_publication
sp_changedistributor_property	sp_mergedummyupdate
sp_changemergearticle	sp_mergesubscription_cleanup
sp_changemergefilter	sp_publication_validation
sp_changemergepublication	sp_refreshsubscriptions
sp_changemergepullsubscription	sp_reinitmergepullsubscription
sp_changemergesubscription	sp_reinitmergesubscription
sp_changepublication	sp_reinitpullsubscription
sp_changesubscriber	sp_reinitsubscription
sp_changesubscriber_schedule	sp_removedbreplication
sp_changesubstatus	sp_replcmds
sp_change_subscription_properties	sp_replcounters
sp_check_for_sync_trigger	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 (T-SQL)

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

Data Type Conversions Using OLE Automation Stored Procedures	OLE Automation Sample Script
How to create an OLE Automation object (Transact-SQL)	System Stored Procedures (OLE Automation Extended Stored Procedures)
How to debug a custom OLE Automation server (Transact-SQL)


sp_add_agent_parameter (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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

Application Security and Application Roles	sp_setapprole
Rules for SQL Server Logins, Users, Roles, and Passwords	System Stored Procedures
sp_dropapprole


sp_addarticle (T-SQL)

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.
XCALL sp_MSdel_article	Calls a stored procedure taking XCALL style parameters. For more information, see Using Custom Stored Procedures in Articles.
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. For an example, see sp_scriptmappedupdproc.
XCALL sp_MSupd_article	Calls a stored procedure taking XCALL style parameters. For more information, see Using Custom Stored Procedures in Articles.
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 table or stored procedure from which the article was created. source_object is sysname, with a default of NULL. If source_table is NULL, source_object cannot be NULL. source_object should be used instead of source_table in SQL Server 7.0. source_table is provided for backward compatibility with SQL Server 6.x Publishers.

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

Enhancing Transactional Replication Performance	sp_droparticle
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_add_data_file_recover_suspect_db (T-SQL)

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 filegroup 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

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

ALTER DATABASE	System Stored Procedures
sp_add_log_file_recover_suspect_db


sp_adddistpublisher (T-SQL)

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 (T-SQL)

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 (T-SQL)

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. If NULL or N, password is reset to a random value. The password must be configured when the first remote distributor that is not trusted is added. 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 (T-SQL)

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. For more information, see Creating Extended Stored Procedures.

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_hello, 'xp_hello.dll'

See Also

EXECUTE	sp_dropextendedproc
GRANT	sp_helpextendedproc
REVOKE	System Stored Procedures


sp_addgroup (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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

Modifying and Viewing Jobs	sp_update_jobschedule
sp_delete_jobschedule	System Stored Procedures
sp_help_jobschedule


sp_add_jobserver (T-SQL)

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 (T-SQL)

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

Modifying and Viewing Jobs	sp_help_job
sp_add_job	sp_help_jobstep
sp_add_jobschedule	sp_update_jobstep
sp_delete_jobstep	System Stored Procedures


sp_addlinkedserver (T-SQL)

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	Microsoft OLE DB Provider for SQL Server	SQL Server	SQLOLEDB	Network name of SQL Server	-	-	Database name (optional)
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. Use server to specify the 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.

Note  For more information about ODBC connect strings, see SQLDriverConnect and How to allocate handles and connect to SQL Server (ODBC).

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

Configuring Linked Servers	sp_serveroption
sp_addlinkedsrvlogin	System Tables
sp_addserver	System Stored Procedures
sp_dropserver


sp_addlinkedsrvlogin (T-SQL)

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

Security for Linked Servers	sp_droplinkedsrvlogin
Configuring Linked Servers	System Stored Procedures
sp_addlinkedserver


sp_add_log_file_recover_suspect_db (T-SQL)

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

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

ALTER DATABASE	System Stored Procedures
sp_add_data_file_recover_suspect_db


sp_addlogin (T-SQL)

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, language is set to the server’s current default language (defined by the sp_configure configuration variable default language). Changing the server’s default language does not change the default language for existing logins. language remains the same as the default language used when the login was added.

[@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 (T-SQL)

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

Reporting and Resolving Conflicts	sp_helpmergearticle
sp_changemergearticle	Using a Custom Resolver
sp_dropmergearticle	System Stored Procedures


sp_addmergefilter (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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

Error Message Severity Levels	sp_dropmessage
RAISERROR	System Stored Procedures
sp_altermessage


sp_add_notification (T-SQL)

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. For more information, see Configuring the SQLServerAgent Service.

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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

Security for Remote Servers	sp_helpremotelogin
sp_addlogin	sp_helpserver
sp_addlinkedsrvlogin	sp_remoteoption
sp_addserver	sp_revokelogin
sp_dropremotelogin	System Stored Procedures
sp_grantlogin


sp_addrole (T-SQL)

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 Microsoft 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

Creating User-Defined SQL Server Database Roles	sp_helprole
sp_addrolemember	System Stored Procedures
sp_droprole


sp_addrolemember (T-SQL)

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

Adding a Member to a SQL Server Database Role	sp_grantdbaccess
sp_addsrvrolemember	System Stored Procedures
sp_droprolemember


sp_addserver (T-SQL)

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 Microsoft 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 (T-SQL)

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 role 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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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.

See Also

Adding Rows Using Bulk Copy Operations	System Stored Procedures


sp_addtask (T-SQL)

sp_addtask is provided for backward compatibility only. For information about the replacement procedures for Microsoft® SQL Server™ version 7.0, see SQL Server Backward Compatibility Details.

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 dbo 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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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

Application Security and Application Roles	sp_setapprole
sp_addapprole	System Stored Procedures


sp_article_validation (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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	sp_removedbreplication
sp_detach_db	System Stored Procedures


sp_attach_single_file_db (T-SQL)

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 (T-SQL)

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 (T-SQL)

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. For more information, see Delimited Identifiers.

[@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 when set to futureonly 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 (T-SQL)

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. For more information, see Delimited Identifiers.

[@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 when set to futureonly 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 futureonly_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 (T-SQL)

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.

For more information about bound connections, see Using Bound Connections.

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
srv_getbindtoken


sp_browsereplcmds (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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_check_for_sync_trigger (T-SQL)

Determines if a user-defined trigger or stored procedure is being called in the context of an immediate-updating trigger.

Syntax

sp_check_for_sync_trigger [@tabid =] 'tabid'
[,[@trigger_op =] 'trigger_op'] [OUTPUT]

Arguments

[@tabid =] 'tabid'

Is the object ID of the table being checked for immediate-updating triggers. tabid is int, with no default.

[@trigger_op =] 'trigger_op' [OUTPUT]

Is whether the output parameter returns the type of trigger it is being called from. trigger_op is char(10), and can be one of these values.

Value	Description
ins	INSERT trigger
upd	UPDATE trigger
del	DELETE trigger
NULL (default)
Return Code Values

0 indicates that the stored procedure is not being called within the context of an immediate-updating trigger. 1 indicates that it is being called within the context of an immediate-updating trigger and is the type of trigger being returned in @trigger_op.

Remarks

sp_check_for_sync_trigger is used in snapshot and transactional replication.

Permissions

Members of the public role can execute sp_check_for_sync_trigger.

See Also

Option: Immediate-updating Subscribers (Snapshot)	System Stored Procedures


sp_column_privileges (T-SQL)

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

Distributed Queries	REVOKE
GRANT	System Stored Procedures


sp_column_privileges_ex (T-SQL)

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 ordered 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 = 'Northwind'

See Also

sp_table_privileges_ex	System Stored Procedures


sp_columns (T-SQL)

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, see Data Types.
* 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 (T-SQL)

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 no 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 see Data Types.
* 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 (T-SQL)

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. For more information about the available configuration options and their settings, see Setting Configuration Options.

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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

Viewing the SQL Server Error Log	System Stored Procedures


sp_databases (T-SQL)

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 (T-SQL)

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 (T-SQL)

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. For more information about backward compatible behaviors, see SQL Server Backward Compatibility Details.

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. For information about deferred name resolution, see CREATE PROCEDURE (Level 4).
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, CONTAINS, CONTAINSTABLE, DENY, FREETEXT, FREETEXTTABLE, PERCENT, RESTORE, ROWGUIDCOL, 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	SQL Server Backward Compatibility Details
Reserved Keywords	Using Identifiers
Setting Database Options	System Stored Procedures
sp_dboption


sp_dbfixedrolepermission (T-SQL)

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 (T-SQL)

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. For more information about each option, see Setting Database Options.

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

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 (T-SQL)

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	sp_detach_db
CREATE DATABASE	System Stored Procedures
DBCC


sp_defaultdb (T-SQL)

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 without 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 (T-SQL)

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, language is set to the server’s default language (defined by the sp_configure configuration variable default language). Changing the server’s default language does not change the default language for existing logins. language remains the same as the default language used when sp_defaultlanguage was executed.

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 (T-SQL)

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	System Stored Procedures
sp_help_alert


sp_delete_backuphistory (T-SQL)

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.

USE msdb

EXEC sp_delete_backuphistory '08/20/98'

See Also

BACKUP	LOAD
backupfile	RESTORE
backupmediafamily	restorefile
backupmediaset	restorehistory
backupset	SQL Server: Buffer Manager Object
DUMP	SQL Server: Cache Manager Object


sp_delete_category (T-SQL)

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 (T-SQL)

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 (T-SQL)

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

Modifying and Viewing Jobs	sp_update_jobschedule
sp_add_jobschedule	System Stored Procedures
sp_help_jobschedule


sp_delete_jobserver (T-SQL)

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 (T-SQL)

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

Modifying and Viewing Jobs	sp_update_jobstep
sp_add_jobstep	System Stored Procedures
sp_help_jobstep


sp_delete_notification (T-SQL)

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 (T-SQL)

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 (T-SQL)

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	Troubleshooting Multiserver Jobs
sp_msx_defect	System Stored Procedures


sp_delete_targetservergroup (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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

Denying Login Access to Windows NT Accounts	sp_revokelogin
sp_grantlogin	System Stored Procedures


sp_depends (T-SQL)

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 (T-SQL)

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

Cursors	sp_cursor_list
CURSOR_STATUS	sp_describe_cursor_columns
DECLARE CURSOR	sp_describe_cursor_tables


sp_describe_cursor_columns (T-SQL)

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

Cursors	sp_describe_cursor
CURSOR_STATUS	sp_describe_cursor_tables
DECLARE CURSOR	System Stored Procedures
sp_cursor_list


sp_describe_cursor_tables (T-SQL)

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

Cursors	sp_describe_cursor
CURSOR_STATUS	sp_describe_cursor_columns
DECLARE CURSOR	System Stored Procedures
sp_cursor_list


sp_detach_db (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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_hello'

See Also

sp_addextendedproc	System Stored Procedures
sp_helpextendedproc


sp_dropgroup (T-SQL)

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 (T-SQL)

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

Security for Linked Servers	sp_addlinkedsrvlogin
sp_addlinkedserver	System Stored Procedures


sp_droplogin (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

sp_droptask is provided for backward compatibility only. For information about the Microsoft SQL® Server™ version 7.0 replacement procedures, see SQL Server Backward Compatibility Details.

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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. For more information, see Defining Jobs.

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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)

    )

For more information about retrieving data from these partitioned tables, see Using Views with Partitioned Data.

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

Batches	EXECUTE
Building Statements at Run Time	System Stored Procedures


sp_expired_subscription_cleanup (T-SQL)

Periodically checks the status of all the subscriptions of every publication and identifies those that have expired.

Syntax

sp_expired_subscription_cleanup

Return Code Values

0 (success) or 1 (failure)

Remarks

sp_expired_subscription_cleanup is used in all types of replication.

sp_expired_subscription_cleanup checks the status of all subscriptions every 24 hours. If any of the subscriptions are out-of-date, that is, have 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 db_owner fixed database role can execute sp_expired_subscription_cleanup.

See Also

sp_subscription_cleanup	System Stored Procedures
sp_mergesubscription_cleanup


sp_fkeys (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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	System Stored Procedures
FULLTEXTSERVICEPROPERTY


sp_fulltext_service (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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
srv_getbindtoken


sp_getmergedeletetype (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 must access the database(s) on the server to determine the information to be displayed about the database. Therefore, for each database on the server, one of these must apply:

•	The user executing sp_helpdb must have permissions to access the database.

•	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™.

exec sp_helpdb

See Also

ALTER DATABASE	sp_dboption
CREATE DATABASE	sp_renamedb
sp_configure	System Stored Procedures


sp_helpdbfixedrole (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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	Description
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 redownloads 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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

sp_helphistory is provided for backward compatibility. For information about the replacement procedures for Microsoft® SQL Server™ version 7.0, see SQL Server SQL Server Backward Compatibility Details.

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 (T-SQL)

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	Schedule information
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 job 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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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.

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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

Security for Linked Servers	sp_droplinkedsrvlogin
sp_addlinkedserver	System Stored Procedures


sp_helplogins (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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	Affects 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 (T-SQL)

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

See Also

Sort Order


sp_helpsrvrole (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

sp_helptask is provided for backward compatibility only. For information about the procedures used in Microsoft® SQL Server™ version 7.0, see SQL Server Backward Compatibility Details.

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 DBCC.

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

Functions	sp_who
KILL	System Stored Procedures
Locking


sp_makewebtask (T-SQL)

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. For more information, see Defining Jobs.

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 Using the Web Assistant Wizard.

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 retrieves five book titles and prices, 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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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

sp_expired_subscription_cleanup	System Stored Procedures
sp_subscription_cleanup


sp_monitor (T-SQL)

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
Using Variables and Parameters


sp_msx_defect (T-SQL)

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 (T-SQL)

Adds the current server to the list of target servers available for multiserver operations. Only a Microsoft SQL Server version 7.0 database server running on Windows NT can be enlisted.

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 (T-SQL)

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.

For more information about HRESULT Return Codes, see OLE Automation Return Codes and Error Information.

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

Data Type Conversions Using OLE Automation Stored Procedures	How to debug a custom OLE Automation server (Transact-SQL)
How to create an OLE Automation object (Transact-SQL)	OLE Automation Sample Script


sp_OADestroy (T-SQL)

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.

For more information about HRESULT Return Codes, see OLE Automation Return Codes and Error Information.

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

Data Type Conversions Using OLE Automation Stored Procedures	How to debug a custom OLE Automation server (Transact-SQL)
How to create an OLE Automation object (Transact-SQL)	OLE Automation Sample Script


sp_OAGetErrorInfo (T-SQL)

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.

For more information about HRESULT Return Codes, see OLE Automation Return Codes and Error Information.

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.
For more information about processing HRESULT Return Codes, see OLE Automation Return Codes and Error Information.

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

Data Type Conversions Using OLE Automation Stored Procedures	How to debug a custom OLE Automation server (Transact-SQL)
How to create an OLE Automation object (Transact-SQL)	OLE Automation Sample Script


sp_OAGetProperty (T-SQL)

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.

For more information about HRESULT Return Codes, see OLE Automation Return Codes and Error Information.

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

Data Type Conversions Using OLE Automation Stored Procedures	How to debug a custom OLE Automation server (Transact-SQL)
How to create an OLE Automation object (Transact-SQL)	OLE Automation Sample Script


sp_OAMethod (T-SQL)

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.

For more information about HRESULT Return Codes, OLE Automation Return Codes and Error Information.

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

Data Type Conversions Using OLE Automation Stored Procedures	How to debug a custom OLE Automation server (Transact-SQL)
How to create an OLE Automation object (Transact-SQL)	OLE Automation Sample Script


sp_OASetProperty (T-SQL)

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.

For more information about HRESULT Return Codes, see OLE Automation Return Codes and Error Information.

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

Data Type Conversions Using OLE Automation Stored Procedures	How to debug a custom OLE Automation server (Transact-SQL)
How to create an OLE Automation object (Transact-SQL)	OLE Automation Sample Script


sp_OAStop (T-SQL)

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.

For more information about HRESULT Return Codes, see OLE Automation Return Codes and Error Information.

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

Data Type Conversions Using OLE Automation Stored Procedures	How to debug a custom OLE Automation server (Transact-SQL)
How to create an OLE Automation object (Transact-SQL)	OLE Automation Sample Script


sp_password (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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. For more information, see Modifying and Viewing Jobs.

Permissions

Anyone can execute this procedure, but the procedure will only have an effect if it is executed by a member of the sysadmin fixed server role.

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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.

If your application has immediate-updating Subscribers, sp_publication_validation may detect spurious errors. sp_publication_validation first calculates the rowcount or checksum at the Publisher and then at the Subscriber. Because the immediate-updating trigger could propogate an update from the Subscriber to the Publisher after the rowcount or checksum is completed at the Publisher but before the rowcount or checksum is completed at the Subscriber, the values could not change. To ensure that the values at the Subscriber and Publisher do not change while validating a publication, stop the MSDTC service at the Publisher during validation.

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 (T-SQL)

sp_purgehistory is provided for backward compatibility only. For information about the replacement procedures for Microsoft® SQL Server™ version 7.0, see SQL Server Backward Compatibility Details.

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 (T-SQL)

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 (T-SQL)

This procedure is provided for backward compatibility only. For information about the replacement procedures for Microsoft® SQL Server™ version 7.0, see SQL Server Backward Compatibility Details.

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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

Configuring Remote Servers	sp_helpremotelogin
sp_addremotelogin	System Stored Procedures


sp_remove_job_from_targets (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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

Error Messages	sp_repltrans
sp_repldone	System Stored Procedures
sp_replflush


sp_replcounters (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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.

See Also

Implementing Nonpartitioned, Bidirectional Transaction Replication	System Stored Procedures
Immediate-updating Subscribers Components


sp_replshowcmds (T-SQL)

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

Error Messages	sp_replflush
sp_replcmds	sp_repltrans
sp_repldone	System Stored Procedures


sp_repltrans (T-SQL)

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 (T-SQL)

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. For more information about situations that may require using this stored procedure, see Troubleshooting Multiserver Jobs.

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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. For more information, see Defining Jobs.

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 (T-SQL)

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 (T-SQL)

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 sp_del_authors'

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_scriptdelproc @artid = 1

The statement returns:

CREATE PROCEDURE [sp_del_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 (T-SQL)

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 sp_ins_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_scriptinsproc @artid = 1

This statement returns:

CREATE PROCEDURE [sp_ins_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 (T-SQL)

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

UPDATE [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 (T-SQL)

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 sp_upd_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_scriptupdproc @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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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

Application Security and Application Roles	sp_dropapprole
sp_addapprole	System Stored Procedures


sp_setnetname (T-SQL)

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 (T-SQL)

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). Values can be true or false. 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

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.

When updateusage is specified, Microsoft® 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 (T-SQL)

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 (T-SQL)

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. For more information, see Data Types.
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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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.

See Also

System Stored Procedures


sp_stop_job (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 immediate-updating 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

sp_expired_subscription_cleanup	System Stored Procedures
sp_mergesubscription_cleanup


sp_table_privileges (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 =] table_name]

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

Checksum computes a 32-bit cyclic redundancy check (CRC) on the entire row image on the page. It does not selectively check columns and cannot operate on a view or vertical partition of the table. Also, the checksum skips the contents of text and image columns (by design).

When doing a checksum, the structure of the table must be identical between the two servers; that is, the tables must have the same columns created and existing in the same order, same data types and lengths, and same NULL/NOT NULL conditions. For example, if the Publisher did a CREATE TABLE, then an ALTER TABLE to add columns, but the script applied at the Publisher is a simple CREATE table, the structure is NOT the same. If you are not certain that the structure of the two tables is identical, look at syscolumns and confirm that the offset in each table is the same.

Floating point values are likely to generate checksum differences if character-mode bcp was used, which is the case if the publication has heterogeneous subscribers. These are due to minor and unavoidable differences in precision when doing conversion to and from character mode.

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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.

Note  object_name can contain the [ and ] characters as delimited identifier characters. For more information, see Delimited Identifiers.

[@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 (T-SQL)

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.

Note  object_name can contain the [ and ] characters as delimited identifier characters. For more information, see Delimited Identifiers.

[@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 futureonly_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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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

Modifying and Viewing Jobs	sp_help_jobschedule
sp_add_jobschedule	System Stored Procedures
sp_delete_jobschedule


sp_update_jobstep (T-SQL)

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

Modifying and Viewing Jobs	sp_help_jobstep
sp_delete_jobstep	System Stored Procedures


sp_update_notification (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

sp_updatetask is provided for backward compatibility only. For information about the replacement procedures for Microsoft® SQL Server™ version 7.0, see SQL Server Backward Compatibility Details.

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 (T-SQL)

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	ntext, text, and image
Using Identifiers	nchar and nvarchar
NCHAR	System Stored Procedures


sp_validatelogins (T-SQL)

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 (T-SQL)

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 (T-SQL)

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™ has the needed privileges to execute.

By default, only members of the sysadmin fixed server role can execute this extended stored procedure. You may, however, grant other users permission to execute this stored procedure. Users who are not members of the sysadmin fixed server role will always run their Windows NT commands in the context of the SQLAgentCmdExec user account, which is the same account used by SQL Server Agent for scheduled tasks entered by users who are not members of sysadmin. When members of the sysadmin fixed server role execute xp_cmdshell, their Windows NT commands execute in the MSSQLServer service's security context, which by default is a user account with local administrator authority.

Note  In previous versions, a user who was granted execute permissions for xp_cmdshell ran the command in the context of the MSSQLServer service's user account. SQL Server could be configured (through a configuration option) so that users who did not have sa access to SQL Server could run xp_cmdshell in the context of the SQLExecutiveCmdExec Windows NT account. In SQL Server 7.0, the account is called SQLAgentCmdExec. Users who are not members of the sysadmin fixed server role now run commands in the context of this account without specifying a configuration change.

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 to use a Windows NT account that is not a member of the local administrator's group 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	Setting Up Security Accounts
EXECUTE	System Stored Procedures (General Extended Procedures)


xp_deletemail (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 body or 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 (T-SQL)

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 (T-SQL)

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 7,990 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. For more information about setting up a SQLMail session automatically, see Setting Up SQLAgentMail. 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.

For more information about using a stored procedure for calling xp_sendmail, see How to use SQLMail (Transact-SQL).

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 7,990 characters

This example shows how to send a message longer than 7,990 characters. Because  message is limited to the length of a varchar (less row overhead, 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 (T-SQL)

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 (T-SQL)

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). For more information, see set working set size Option.
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.
ServerAvailableMemory	Available amount of physical memory in megabytes on SQL Server.
OperatingSystem	Operating system for SQL Server; for example, Microsoft Windows NT.
OperatingSystemBuild	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.
AvailablePhysicalDisk	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 (T-SQL)

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

sqlmaint Utility	System Stored Procedures


xp_sqltrace (T-SQL)

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

Monitoring with SQL Server Profiler	System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_sscanf (T-SQL)

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 (T-SQL)

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	Setting Up SQLAgentMail
xp_readmail	System Stored Procedures (SQL Mail Extended Procedures)


xp_stopmail (T-SQL)

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_addnewqueueile Title:

File(s): Xp_trace.csf	File: xp_trace.csf

Date In	Date Out	e-mail	Stage	Comments
07/24/98	07/24/98	a-annera	dtp	TSQL: created file from xp_aa-zz,everything past xp_sz.
07/27/98	07/27/98	t-jamilj	DTP	Incorporated  edits
07/28/98	07/28/98	dianemar	writing	inserted query history to xp_trace_setqueryhistory, per email from bob vogt.
08/08/98	08/08/98	dianemar	writing	updating per bob vogt's tech review comments.
08/18/98	08/18/98	a-toddry	dtp	incorporate edits
08/18/98	08/18/98	dianemar	writing	added new event names in xp_trace_eventclassrequired, per bob vogt.
08/19/98	08/19/98	a-raymwh	dtp	Incorporated edits
08/19/98	08/19/98	a-raymwh	dtp	Incorporated edits from Ken
08/20/98	08/19/98	a-raymwh	dtp	Enabled jumps and put in numbered order
8/24/98	8/24/98	a-kensa	editing	Checked and reordered SAs. Added global change to the wording for Permissions, and made additional edits
08/25/98	08/25/98	a-donada	writer	Modified last sentence in first para of xp_trace_setqueryhistory as per Rob Vogt.
08/25/98	08/25/98	a-donada	writer	checked for inconsistent examples under xp_trace_geteventnames
08/26/98	08/25/98	a-raymwh	dtp	Incorporated edits from Ken’s 8/24/98 edit
08/28/98	08/28/98	t-jamilj	DTP	Making Examples for print
8/28/98	8/28/98	v-juliha		keyword pass for RTM
08/31/98	08/31/98	a-donada	writer	fixed last code example under topic xp_trace_geteventnames
9/3/98	9/3/98	a-kensa	editing	Marked x-refs for print and other edits
09/07/98	09/07/98	dianemar	writing	began incorporating Bob Vogt's tech review comments
09/08/98	09/08/98	dianemar	writing	added include/exclude filter procs, per bob vogt tech review comments and result set info for xp_setqueryhistory.
09/10/98	09/10/98	a-raymwh	dtp	Incorporated edits from Ken
09/14/98	09/14/98	a-raymwh	dtp	Incorporated edits from Jennifer into xp_trace_setappfilter
09/17/98	09/17/98	a-toddry	DTP	Inserted index tags for print
09/23/98	09/23/98	a-donada	writer	Modified xp_trace_setquertyhistory as per Ken S.
09/23/98	09/23/98	a-raymwh	DTP	Incorporated edits from Jennifer (globals)
10/01/98	10/01/98	a-raymwh	dtp	Fixed bugs and moved index tags out of FMIs
10/03/98	10/03/98	a-raymwh	dtp	Incorporated edits from Kathy
10/04/98	10/04/98	dianemar	writing	inc Bob Vogt's tech review comments printed on hardcopy (Printed footer shows Printed 9/25/98, Revision #12, Last Saved by Don Adams)
10/05/98	10/05/98	dianemar	writing	made minor corrections from bob vogt's answers to questions.
10/06/98	10/06/98	a-raymwh	dtp	Incorporated edits from Ken and Diane
10/07/98	10/07/98	a-raymwh	dtp	Incorporated edits from Diane and Ken into xp_trace_generate_event topic
10/15/98	10/15/98	a-annera	dtp	incorporated edits on xp_trace_generate_event
10/15/98	10/15/98	a-raymwh	dtp	Incorporated edits from Ken
10/20/98	10/20/98	a-raymwh	dtp	Incorporated edits from Don and Ann
10/21/98	10/21/98	a-raymwh	dtp	Incorporated edits from Don, Ken, and Ann
10/23/98	10/23/98	a-raymwh	dtp	Fixing bugs 50834 from Diane and Ann
10/26/98	10/26/98	a-raymwh	dtp	Fixing bugs 2016
10/26/98	10/26/98	a-raymwh	dtp	Incorporated edits from Ken
10/26/98	10/26/98	a-bryanf	DTP	Printisms.
›


xp_trace_addnewqueue (T-SQL)

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. For more information about stopping or destroying a trace queue, see Deleting Traces.

There are some special considerations when using the Replay feature of SQL Server Profiler which pertain to passwords, permissions, and authentication. For more information, see Replaying Traces.

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
Monitoring with SQL Server Profiler	xp_trace_restartqueue
xp_trace_destroyqueue	xp_trace_savequeuedefinition
xp_trace_enumqueuehandles	System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_loadqueuedefinition


xp_trace_deletequeuedefinition (T-SQL)

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

Monitoring with SQL Server Profiler	xp_trace_savequeuedefinition
xp_trace_destroyqueue	System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_destroyqueue (T-SQL)

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

Monitoring with SQL Server Profiler	xp_trace_restartqueue
xp_trace_addnewqueue	xp_trace_savequeuedefinition
xp_trace_deletequeuedefinition	System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_pausequeue


xp_trace_enumqueuedefname (T-SQL)

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

Monitoring with SQL Server Profiler	xp_trace_loadqueuedefinition
xp_trace_addnewqueue	System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_enumqueuehandles (T-SQL)

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

Monitoring with SQL Server Profiler	xp_trace_loadqueuedefinition
xp_trace_addnewqueue	System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_enumqueuedefname


xp_trace_eventclassrequired (T-SQL)

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. For more information, see How to use Microsoft Distributed Transaction Coordinator (ODBC).
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

Monitoring with SQL Server Profiler	xp_trace_seteventclassrequired
xp_trace_addnewqueue	System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_geteventnames


xp_trace_flushqueryhistory (T-SQL)

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

Monitoring with SQL Server Profiler	System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_setqueryhistory


xp_trace_generate_event (T-SQL)

Adds a user-defined event to all queues. Returns no result set.

Syntax

xp_trace_generate_event {event_class} [, event_subclass]
[, integer_data] [, 'server_name'] [, 'event_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'] [, 'sql_user_name'] [, spid]
[, duration] [, start_time] [, end_time] [, read]
[, write] [, 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.

'server_name'

Is a character value representing the name of the server that generated the event.

'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'

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.

read

Is an integer value representing the number of reads for the user-defined event.

write

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,

@event_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

Monitoring with SQL Server Profiler	System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_setqueuedestination


xp_trace_getappfilter (T-SQL)

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

Monitoring with SQL Server Profiler	System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_setappfilter


xp_trace_getconnectionidfilter (T-SQL)

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

Monitoring with SQL Server Profiler	System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_setconnectionidfilter


xp_trace_getcpufilter (T-SQL)

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

Monitoring with SQL Server Profiler	System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_setcpufilter


xp_trace_getdbidfilter (T-SQL)

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

Monitoring with SQL Server Profiler	System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_setdbidfilter


xp_trace_getdurationfilter (T-SQL)

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

Monitoring with SQL Server Profiler	System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_setdurationfilter


xp_trace_geteventfilter (T-SQL)

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

Monitoring with SQL Server Profiler	System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_seteventfilter


xp_trace_geteventnames (T-SQL)

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

Monitoring with SQL Server Profiler	xp_trace_seteventclassrequired
xp_trace_eventclassrequired	System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_getevents (T-SQL)

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

Monitoring with SQL Server Profiler	xp_trace_geteventnames
xp_trace_addnewqueue	System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_eventclassrequired


xp_trace_gethostfilter (T-SQL)

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

Monitoring with SQL Server Profiler	System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_sethostfilter


xp_trace_gethpidfilter (T-SQL)

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

Monitoring with SQL Server Profiler	System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_sethpidfilter


xp_trace_getindidfilter (T-SQL)

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

Monitoring with SQL Server Profiler	System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_setindidfilter


xp_trace_getntdmfilter (T-SQL)

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

Monitoring with SQL Server Profiler	System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_setntdmfilter


xp_trace_getntnmfilter (T-SQL)

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

Monitoring with SQL Server Profiler	System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_setntnmfilter


xp_trace_getobjidfilter (T-SQL)

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

Monitoring with SQL Server Profiler	System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_setobjidfilter


xp_trace_getqueueautostart (T-SQL)

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

Monitoring with SQL Server Profiler	xp_trace_loadqueuedefinition
xp_trace_addnewqueue	xp_trace_pausequeue
xp_trace_deletequeuedefinition	xp_trace_restartqueue
xp_trace_destroyqueue	xp_trace_savequeuedefinition
xp_trace_enumqueuedefname	System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_enumqueuehandles


xp_trace_getqueuedestination (T-SQL)

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

Monitoring with SQL Server Profiler	System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_setqueuedestination


xp_trace_getqueueproperties (T-SQL)

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

Monitoring with SQL Server Profiler	System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_addnewqueue


xp_trace_getreadfilter (T-SQL)

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

Monitoring with SQL Server Profiler	System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_setreadfilter


xp_trace_getserverfilter (T-SQL)

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

Monitoring with SQL Server Profiler	System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_setserverfilter


xp_trace_getseverityfilter (T-SQL)

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

Monitoring with SQL Server Profiler	System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_setseverityfilter


xp_trace_getspidfilter (T-SQL)

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

Monitoring with SQL Server Profiler	System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_setspidfilter


xp_trace_getsysobjectsfilter (T-SQL)

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

Monitoring with SQL Server Profiler	System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_setsysobjectsfilter


xp_trace_gettextfilter (T-SQL)

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

Monitoring with SQL Server Profiler	System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_settextfilter


xp_trace_getuserfilter (T-SQL)

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

Monitoring with SQL Server Profiler	System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_setuserfilter


xp_trace_getwritefilter (T-SQL)

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

Monitoring with SQL Server Profiler	System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_setwritefilter


xp_trace_loadqueuedefinition (T-SQL)

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

Monitoring with SQL Server Profiler	xp_trace_getqueueautostart
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_pausequeue (T-SQL)

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

Monitoring with SQL Server Profiler	xp_trace_setqueueautostart
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_restartqueue (T-SQL)

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

Monitoring with SQL Server Profiler	xp_trace_getqueueautostart
xp_trace_addnewqueue	xp_trace_loadqueuedefinition
xp_trace_deletequeuedefinition	xp_trace_pausequeue
xp_trace_destroyqueue	xp_trace_savequeuedefinition
xp_trace_enumqueuedefname	System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_enumqueuehandles


xp_trace_savequeuedefinition (T-SQL)

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

Monitoring with SQL Server Profiler	xp_trace_getqueueautostart
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_setappfilter (T-SQL)

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

Monitoring with SQL Server Profiler	xp_trace_getappfilter
xp_trace_addnewqueue	xp_trace_getqueueproperties
xp_trace_enumqueuehandles	System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_setconnectionidfilter (T-SQL)

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

Monitoring with SQL Server Profiler	xp_trace_enumqueuehandles
xp_trace_addnewqueue	xp_trace_getqueueproperties
xp_trace_getconnectionidfilter	System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_setcpufilter (T-SQL)

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

Monitoring with SQL Server Profiler	xp_trace_getcpufilter
xp_trace_addnewqueue	xp_trace_getqueueproperties
xp_trace_enumqueuehandles	System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_setdbidfilter (T-SQL)

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

Monitoring with SQL Server Profiler	xp_trace_getdbidfilter
sp_helpdb	xp_trace_getqueueproperties
xp_trace_addnewqueue	System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_enumqueuehandles


xp_trace_setdurationfilter (T-SQL)

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

Monitoring with SQL Server Profiler	xp_trace_enumqueuehandles
xp_trace_addnewqueue	xp_trace_getqueueproperties
xp_trace_getdurationfilter	System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_seteventclassrequired (T-SQL)

Specifies the event classes to trace or not to 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

Monitoring with SQL Server Profiler	xp_trace_geteventnames
xp_trace_addnewqueue	System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_eventclassrequired


xp_trace_seteventfilter (T-SQL)

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

Monitoring with SQL Server Profiler	xp_trace_enumqueuehandles
xp_trace_addnewqueue	xp_trace_getqueueproperties
xp_trace_geteventfilter	System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_sethostfilter (T-SQL)

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

Monitoring with SQL Server Profiler	xp_trace_gethostfilter
xp_trace_addnewqueue	xp_trace_getqueueproperties
xp_trace_enumqueuehandles	System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_sethpidfilter (T-SQL)

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

Monitoring with SQL Server Profiler	xp_trace_gethpidfilter
xp_trace_addnewqueue	xp_trace_getqueueproperties
xp_trace_enumqueuehandles	System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_setindidfilter (T-SQL)

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

Monitoring with SQL Server Profiler	xp_trace_getindidfilter
xp_trace_addnewqueue	xp_trace_getqueueproperties
xp_trace_enumqueuehandles	System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_setntdmfilter (T-SQL)

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

Monitoring with SQL Server Profiler	xp_trace_getqueueproperties
xp_trace_enumqueuehandles	System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_getntdmfilter


xp_trace_setntnmfilter (T-SQL)

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

Monitoring with SQL Server Profiler	xp_trace_getqueueproperties
xp_trace_enumqueuehandles	System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_getntnmfilter


xp_trace_setobjidfilter (T-SQL)

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

Monitoring with SQL Server Profiler	xp_trace_getqueueproperties
xp_trace_enumqueuehandles	System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_getobjidfilter


xp_trace_setqueryhistory (T-SQL)

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
Monitoring with SQL Server Profiler	System Stored Procedures (SQL Server Profiler Extended Procedures)
SET @local_variable


xp_trace_setqueueautostart (T-SQL)

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

Monitoring with SQL Server Profiler	xp_trace_getqueueautostart
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_setqueuecreateinfo (T-SQL)

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

Monitoring with SQL Server Profiler	xp_trace_getqueueproperties
xp_trace_addnewqueue	System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_setqueuedestination (T-SQL)

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 maximum 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

Monitoring with SQL Server Profiler	xp_trace_getqueueproperties
xp_trace_addnewqueue	xp_trace_startconsumer
xp_trace_enumqueuehandles	System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_getqueuedestination


xp_trace_setreadfilter (T-SQL)

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

Monitoring with SQL Server Profiler	xp_trace_getqueueproperties
xp_trace_addnewqueue	xp_trace_getreadfilter
xp_trace_enumqueuehandles	System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_setserverfilter (T-SQL)

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

Monitoring with SQL Server Profiler	xp_trace_getqueueproperties
xp_trace_addnewqueue	xp_trace_getserverfilter
xp_trace_enumqueuehandles	System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_setseverityfilter (T-SQL)

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

Monitoring with SQL Server Profiler	xp_trace_getqueueproperties
xp_trace_addnewqueue	xp_trace_getseverityfilter
xp_trace_enumqueuehandles	System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_setspidfilter (T-SQL)

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

Monitoring with SQL Server Profiler	xp_trace_getqueueproperties
sp_who	xp_trace_getspidfilter
xp_trace_addnewqueue	System Stored Procedures (SQL Server Profiler Extended Procedures)
xp_trace_enumqueuehandles


xp_trace_setsysobjectsfilter (T-SQL)

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

Monitoring with SQL Server Profiler	xp_trace_getqueueproperties
xp_trace_addnewqueue	xp_trace_getsysobjectsfilter
xp_trace_enumqueuehandles	System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_settextfilter (T-SQL)

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

Monitoring with SQL Server Profiler	xp_trace_getqueueproperties
xp_trace_addnewqueue	xp_trace_gettextfilter
xp_trace_enumqueuehandles	System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_setuserfilter (T-SQL)

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

Monitoring with SQL Server Profiler	xp_trace_getuserfilter
xp_trace_addnewqueue	xp_trace_getqueueproperties
xp_trace_enumqueuehandles	System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_setwritefilter (T-SQL)

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

Monitoring with SQL Server Profiler	xp_trace_getqueueproperties
xp_trace_addnewqueue	xp_trace_getwritefilter
xp_trace_enumqueuehandles	System Stored Procedures (SQL Server Profiler Extended Procedures)


xp_trace_startconsumer (T-SQL)

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

Monitoring with SQL Server Profiler	xp_trace_setqueuedestination
xp_trace_addnewqueue	System Stored Procedures (SQL Server Profiler Extended Procedures)


System Tables (T-SQL)

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
syscacheobjects	syslanguages	sysperfinfo
syscharsets	syslockinfo	sysprocesses
sysconfigures	syslogins	sysremotelogins
syscurconfigs	sysmessages	sysservers
sysdatabases
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_tombstone	sysmergeschemachange
MSmerge_delete_conflicts	sysarticleupdates	sysmergesubscriptions
MSmerge_genhistory	sysmergearticles	sysmergesubsetfilters
MSmerge_replinfo	sysmergepublications


backupfile (T-SQL)

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 (T-SQL)

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: 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 (T-SQL)

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 (T-SQL)

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. For more information about sort orders, see Sort Order.
code_page	smallint NULL	Code page of the server performing the backup operation. For more information about code pages, see Sort Order.
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 (T-SQL)

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 msdb database.

Column name	Data type	Description
profile_id	int	Profile ID from the MSagent_profiles table
parameter_name	sysname	Name of the parameter
value	nvarchar(255)	Value of the parameter


MSagent_profiles (T-SQL)

Contains one row for each defined replication agent profile. This table is stored in the msdb database.

Column name	Data type	Description
profile_id	int	Profile ID from the MSagent_profiles table.
profile_name	sysname	Unique profile name 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 profile.
def_profile	bit	Specifies whether this profile is the default for this agent type.


MSarticles (T-SQL)

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
destination_object	sysname	Name of the table created at the Subscriber
source_owner	sysname	Name of the owner of the source table at the Publisher
source_object	sysname	Name of the source object from which to add the article
description	nvarchar(255)	Description of the article


MSdistpublishers (T-SQL)

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.
trusted	bit	Whether the remote Publisher uses the same password as the local Distributor: 0 = A password is needed at the remote Publisher to connect to the Distributor. 1 = No password is needed.
third_party	bit	Whether the Publisher is an installation of Microsoft® SQL Server™: 0 = SQL Server installation. 1 = Heterogeneous data source.


MSdistributiondbs (T-SQL)

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 (T-SQL)

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, used by well-known agents only. For anonymous agents, this column is reserved.
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, used by anonymous agents only.
virtual_agent_id	int	For internal use only.
anonymous_agent_id	int	For internal use only.
creation_date	datetime	Datetime when the Distribution or Merge Agent was created.


MSdistribution_history (T-SQL)

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.
current_delivery_rate	float	Average number of commands delivered per second since the last history entry.
current_delivery_latency	int	Latency between the command entering the distribution database and being applied to the Subscriber since the last history entry.
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.
updateable_row	bit	Set if the history row can be overwritten.
timestamp	timestamp	Timestamp column of this table.


MSdistributor (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 published database and being entered into the distribution database.
error_id	int	ID of the error in the MSrepl_error system table.
timestamp	timestamp	Timestamp column of this table.


MSmerge_agents (T-SQL)

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.
creation_date	datetime	Date and time the Distribution or Merge Agent was created.


MSmerge_contents (T-SQL)

Contains one row for each row modified in the current database since it was published. This table is used by the merge process to determine the rows that have changed. This table is stored in the user database.

Column name	Data type	Description
tablenick	int	Nickname of the published table.
rowguid	uniqueidentifier	Row identifier for the given row.
generation	int	Generation of the row identified by the tablenick and rowguid.
partchangegen	int	The generation associated with the last data change that could have changed whether the row belongs in a filtered publication.
joinchangegen	int	The generation associated with the last data change to this row that would have changed whether related rows belong in a filtered publication.
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 (T-SQL)

Contains information for rows that were deleted because either they conflicted with an update and lost the conflict or the delete was undone to achieve data convergence. 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)	Subscription for which the delete of the row was undone or the delete lost the conflict.
conflict_type	int	Type of conflict: 4 = Update wins. 7 = Upload delete failed. 8 = Download delete failed.
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 (T-SQL)

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 user 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 (T-SQL)

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.
updateable_row	bit	Set if the history row can be overwritten.


MSmerge_replinfo (T-SQL)

Contains one row for each subscription. This table tracks internal information about the sent and received generation. This table is stored in the user 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)	Merge job ID for this subscription.
snapshot_jobid	binary(16)	Snapshot job ID servicing this publication.


MSmerge_subscriptions (T-SQL)

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.
subscription_time	datetime	Time the subscription was added.


MSmerge_tombstone (T-SQL)

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 when a row is deleted. If a Subscriber requests generation N, only tombstones with generation >= N are sent.
reason	varchar(255)	Text field containing the reason that tombstone was created.


MSpublication_access (T-SQL)

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
publication_id	int	ID of the publication
login	sysname	Microsoft Windows NT® accounts that exist at both Publisher and Distributor side


MSpublications (T-SQL)

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).
retention	int	Retention period of the publication.


MSpublisher_databases (T-SQL)

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 (T-SQL)

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 (T-SQL)

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.
immediate_sync	bit	Indicates whether synchronization files are created or re-created each time the Snapshot Agent runs.


MSrepl_commands (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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	Number of 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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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_database_id	int	ID of the Publisher database.
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.
loopback_detection	bit	Whether the Distribution Agent sends transactions originated at the Subscriber back to the Subscriber: True = Does not send back. False = Sends back.
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 (T-SQL)

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 = Transactional 2 = Merge
publisher_login	sysname	Login ID used at the Publisher for SQL Server Authentication.
publisher_password	sysname	Password (encrypted) 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 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.
distributor_login	sysname	Login ID used at the Distributor for SQL Server Authentication.
distributor_password	sysname	Password (encrypted) used at the Distributor for SQL Server Authentication.
distributor_security_mode	int	Security mode implemented at the Distributor: 0 = SQL Server Authentication 1 = Windows NT Authentication
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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

Contains a row for each allocation unit. This table is stored in each database.

Column name	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. For more information, see Space Allocation and Reuse.


sysaltfiles (T-SQL)

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 (KB).
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 (T-SQL)

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	Bitmask of the article options. status is tinyint, and can be one of these values: 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.
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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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.
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. For internal use only by SQL Server tools and in upgrade processing.


sysdepends (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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(816)	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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 the job 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 (T-SQL)

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 (T-SQL)

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	nvarchar(40)	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 attempts.
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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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: 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: 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 (T-SQL)

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.
dynamic_filters	bit	Indicates whether the publication is filtered on a dynamic property.


sysmergeschemachange (T-SQL)

Contains information about the published articles generated by the Snapshot Agent. 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 (T-SQL)

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	ID of the publication from which the current subscription was created.
status	tinyint	Status of the subscription:  0 = Inactive 1 = Active 2 = Deleted
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	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 (T-SQL)

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 of join_tablename: 0 = Not a unique key. 1 = A unique key.
join_filterclause	nvarchar(1000)	Filter clause used for the join.


sysmessages (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 representing 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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

Contains information about the conditions causing a replication alert to fire. This table is stored in the msdb database.

Column name	Data type	Description
alert_id	int	ID of the alert.
status	int	User-defined value: 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_agents, MSlogreader_agents, MSdistribution_agents, or MSmerge_agents.
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 (T-SQL)

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(30)	Reserved (currently the same as the srvname).


syssubscriptions (T-SQL)

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: 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	Timestamp.
update_mode	tinyint	Update mode: 0 = Read only 1 = Immediate-updating
loopback_detection	bit	Whether the Distribution Agent sends transactions originated at the Subscriber back to the Subscriber: True = Does not send back False = Sends back


systargetservergroupmembers (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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 (T-SQL)

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

Allowing Null Values	Managing Security
ALTER TABLE	SESSION_USER
CREATE TABLE	USER
CURRENT_TIMESTAMP	Using Constraints, Defaults, and Null Values
CURRENT_USER	System Functions


TAN (T-SQL)

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 (T-SQL)

For information about the text data type, see ntext, text, and image.

See Also

Data Type Conversion	Data Types


TEXTPTR (T-SQL)

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 (T-SQL)

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 (T-SQL)

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	DECLARE @local_variable
CAST and CONVERT	DELETE
CREATE TABLE	INSERT
Data Type Conversion	SET @local_variable
Data Types	UPDATE


tinyint (T-SQL)

For information about the tinyint data type, see int, smallint, and tinyint.

See Also

Data Type Conversion	Data Types


Trace Flags (T-SQL)

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). For more information about __GetXpVersion(), see Creating Extended Stored Procedures.
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

See Also

Data Types	SELECT
DBCC INPUTBUFFER	SET NOCOUNT
DBCC OUTPUTBUFFER	sp_dboption
DBCC TRACEOFF	SQL Server Backward Compatibility Details
DBCC TRACEON	sqlservr Application
EXECUTE


Transactions (T-SQL)

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.

For more information, see Transactions.

See Also

BEGIN DISTRIBUTED TRANSACTION	ROLLBACK WORK
BEGIN TRANSACTION	SAVE TRANSACTION
COMMIT TRANSACTION	SET IMPLICIT_TRANSACTIONS
COMMIT WORK	@@TRANCOUNT
ROLLBACK TRANSACTION


TRIGGER_NESTLEVEL (T-SQL)

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 (T-SQL)

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.

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 (T-SQL)

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 (T-SQL)

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	Using Unicode Data
NCHAR	String Functions


UNION (T-SQL)

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 (T-SQL)

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 Type Conversion	Overview of Replication
Data Types	SET @local_variable
DECLARE @local_variable	UPDATE


UPDATE (T-SQL)

Changes existing data in a table.

Syntax

UPDATE
{
  table_name WITH ( <table_hint_limited> [...n])
 	| view_name
 	| 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
| MAXDOP
| ROBUST PLAN
| KEEP PLAN
}

Arguments

table_name

Is the name 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

Is the name 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 capabilities needed by the provider, see UPDATE and DELETE Requirements for OLE DB Providers. 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 of 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.

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. For more information, see max degree of parallelism Option.

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. 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,060 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 (T-SQL)

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. For more information, see Using 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	sp_autostats
CREATE STATISTICS	sp_createstats
Cursors	sp_dboption
DBCC SHOW_STATISTICS	sp_helpindex
DROP STATISTICS	sp_updatestats
EXECUTE	STATS_DATE
Functions


UPDATETEXT (T-SQL)

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. For more information, see Using 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. For more information, see sp_dboption and Setting Database Options.

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 (T-SQL)

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 (T-SQL)

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_adduser
DROP DATABASE	sp_defaultdb
EXECUTE	Using Identifiers
sp_addalias


USER (T-SQL)

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	Modifying Column Properties
CREATE TABLE	SESSION_USER
CURRENT_TIMESTAMP	SYSTEM_USER
CURRENT_USER	USER_NAME
Creating and Modifying PRIMARY KEY Constraints	Security Functions


USER_ID (T-SQL)

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 (T-SQL)

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	Modifying Column Properties
CREATE TABLE	SESSION_USER
CURRENT_TIMESTAMP	SYSTEM_USER
CURRENT_USER	System Functions


VAR (T-SQL)

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 (T-SQL)

For information about the varbinary data type, see binary and varbinary.

See Also

Data Type Conversion	Data Types


varchar (T-SQL)

For information about the varchar data type, see char and varchar.

See Also

Data Type Conversion	Data Types


VARP (T-SQL)

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 (T-SQL)

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 date 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 (T-SQL)

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
Predicate	UPDATE
Search Condition


WHILE (T-SQL)

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 (T-SQL)

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. For more information, see Using 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 and Setting Database Options.

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 (T-SQL)

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


See SQL Server Books Online to review this topic.