Introduction to Transact-SQL Help

To use this Help file, choose the Search button, and then type the word you want to search for. You can also use the previous topic (<<) and next topic (>>) buttons to browse through the topics in this Help file.

If you are in a Query window and want help on Transact-SQL syntax, select the syntax and press SHIFT+F1. To get information about a specific object, highlight the object and press ALT+F1.

The following table identifies Transact-SQL features as new or enhanced in SQL Server 6.5. Features are in alphabetical order.

Feature	New	Enhanced
@@OPTIONS global variable	•
ANSI-standard null handling	•
Bound connections	•
Catalog stored procedures
sp_column_privileges		•
sp_columns		•
sp_datatype_info		•
sp_fkeys		•
sp_sproc_columns		•
sp_table_privileges		•
Composite indexes		•
CUBE operator	•
Data definition language     in transactions		•
Disabling constraints	•
Distributed transactions	•
Extended stored procedures
xp_cmdshell		•
xp_readmail		•
xp_sendmail		•
xp_snmp_getstate	•
xp_snmp_raisetrap	•
xp_sqlinventory	•
xp_sqltrace	•
float datatype		•
Functions
APP_NAME built-in	•
ISDATE and ISNUMERIC	•
USER	•
Joins		•
Replication stored procedures
sp_addsubscriber		•
sp_addsubscription		•
sp_changearticle
sp_changesubscriber		•
sp_dsninfo	•
sp_enumdsn	•
sp_helpsubscriberinfo		•
sp_replcmds		•
Replication of text and image    datatypes	•
ROLLUP operator	•
SQL Executive stored procedures
sp_addtask		•
sp_helphistory		•
sp_helptask		•
sp_runtask		•
sp_updatetask		•
Statements
ALTER TABLE		•
BEGIN DISTRIBUTED    TRANSACTION	•
CREATE INDEX		•
CREATE SCHEMA	•
CREATE TABLE		•
DECLARE CURSOR		•
DBCC DBREINDEX	•
DBCC UPDATEUSAGE	•
DUMP		•
EXECUTE		•
FETCH		•
GRANT		•
INSERT		•
LOAD		•
RAISERROR		•
REVOKE		•
SELECT		•
SET		•
UPDATE		•
System stored procedures
sp_addlogin		•
sp_bindsession	•
sp_certify_removable		•
sp_change_users_login	•
sp_coalesce_fragments	•
sp_configure		•
sp_dboption		•
sp_dropwebtask	•
sp_fallback_activate_svr_db	•
sp_fallback_deactivate_svr_db	•
sp_fallback_enroll_svr_db	•
sp_fallback_help	•
sp_fallback_permanent_svr	•
sp_fallback_upd_dev_drive	•
sp_fallback_withdraw_svr_db	•
sp_getbindtoken	•
sp_helplogins	•
sp_helprotect		•
sp_help_revdatabase	•
sp_helpserver		•
sp_makewebtask	•
sp_rename	•
sp_runwebtask	•
sp_serveroption		•
sp_setnetname	•
sp_who		•
Tables
MSsubscriber_info		•
sysbackupdetail	•
sysbackuphistory	•
syscolumns		•
sysindexes		•
sysprocesses		•
sysprotects		•
sysrestoredetail	•
sysrestorehistory	•
text datatype		•
Trace flags		•
Utilities
isql options		•
ISQLPASSWORD		•
SQLMAINT.EXE command-line    utility	•
Web pages	•


ALTER DATABASE Statement

Increases the amount of disk space allocated to a database.

Syntax

ALTER DATABASE database_name
[ON {DEFAULT | database_device} [= size]
[, database_device [= size]]...]
[FOR LOAD]

where

database_name

Is the database whose storage size is to be changed.

ON

Indicates a size and/or location for the database extension. The default extension size is 1 megabyte (MB).

If extending the amount of space allocated to the transaction log, give the name of the log's database device. This will automatically allocate new space only for the transaction log if the database was originally created using the LOG ON clause.

If the database was not created with the LOG ON clause and you want to move the log to a newly added device, then, after altering the database, use the sp_logdevice system stored procedure to make the newly allocated space available only for the log.

Note  You must use the sp_logdevice system stored procedure or the LOG ON extension of CREATE DATABASE to put your transaction log on a separate device before you can use the DUMP TRANSACTION statement. Placing the log on the same device as the database minimizes the number of recoverability features available for your database.

DEFAULT

Indicates that ALTER DATABASE can put the database extension on any default database device(s). To see a listing of all available database devices, use the sp_helpdevice system stored procedure. To specify a size for the database extension without specifying the location, use ON DEFAULT = size. To change the status of a database device to default, use the sp_diskdefault system stored procedure.

database_device

Is the logical name of the database device on which you want to place the database extension. A database can reside on more than one database device with different amounts of space on each. To create a device, use the DISK INIT statement.

size

Specifies the amount of space, in megabytes, allocated to the database extension. The minimum, and default, extension is 1 MB (512 2K pages). Legal values range from 1 through 2^24 MB. If SQL Server can't allocate the requested size, it allocates as much space as possible, in 0.5-MB units (allocation units).

When an explicit value is not supplied, SQL Server will use the larger value between the size of the model database or the configured database size (configured with sp_configure). For example, if database size is configured to 2 (the default) and the model database has been altered to 3MB, the database will be 3MB.

FOR LOAD

Prevents use of the database until after a successful database load. This can be used only if the database was created with the FOR LOAD option. For details, see the CREATE DATABASE statement.

Remarks

ALTER DATABASE increases the size of a database. To rename a database, use the sp_renamedb system stored procedure. To decrease the size of a database, see the DBCC statement's SHRINKDB option.

It is important to back up the master database using the DUMP DATABASE statement after each use of ALTER DATABASE. This makes recovery easier and safer if the master database becomes damaged. (If you use ALTER DATABASE and fail to back up the master database, you might still be able to recover the changes with the DISK REFIT statement. For details, see the DISK REFIT statement.)

The SYSTEM and DEFAULT segments are mapped to each new database device included in an ALTER DATABASE statement. When ALTER DATABASE extends a database on a device already in use by that database, the segments mapped to that device are also extended. The maximum number of segments for any database is 32.

Permission

ALTER DATABASE permission defaults to the database owner if he or she has CREATE DATABASE permission. Permission cannot be transferred. The system administrator can also alter databases.

Examples

A.	Alter a Single Database on a Single Device

This example alters the testing database on the DEVICE1 device by adding an 8-MB fragment.

ALTER DATABASE testing

ON DEVICE1 = 8

B.	Alter a Database's Log Space

This example increases the size of the sales_info database by 5 MB. After the database has been altered, that fragment is made log-only by executing the sp_logdevice system stored procedure.

ALTER DATABASE sales_info

ON DEVICE9 = 5

go

sp_logdevice sales_info, DEVICE9

See Also

CREATE DATABASE	sp_helpdb
DROP DATABASE	sp_helpsegment
DBCC	sp_logdevice
sp_addsegment	sp_spaceused
sp_diskdefault


ALTER TABLE Statement

For more information about how SQL Server 6.5 affects existing database systems and for updated SQL Server 6.5 syntax, see ALTER TABLE Statement.

Adds new columns or constraints to an existing table.

Syntax

ALTER TABLE [database.[owner].]table_name
[WITH NOCHECK]
[ADD
{col_name column_properties [column_constraints]
| [[,] table_constraint]}
[, {next_col_name | next_table_constraint}]...]
|
[DROP [CONSTRAINT]
constraint_name [, constraint_name2]...]

where

table_name

Specifies which table to alter. You can include local or global temporary tables, but FOREIGN KEY constraints are not enforced on temporary tables.

WITH NOCHECK

Allows CHECK or FOREIGN KEY constraints to be added to a table without verifying existing data for constraint violations. PRIMARY KEY and UNIQUE constraints are always checked. When this option is not specified (the default), any added constraints will be validated against existing data. If there are any constraint violations, the ALTER TABLE statement fails and a message is returned, stating the type of constraint and name that caused the violation. Use this option with extreme caution. This option is useful when you know your data already meets the new constraints or when a business rule requires the constraint to be enforced only from this point forward.

Note  The WITH NOCHECK option will bypass checking FOREIGN KEY and CHECK constraints only at the time the table is altered. Future data modifications made against any column will demand that all columns satisfy all CHECK constraints, even those columns not included in the UPDATE column list.

ADD

Allows a column or table-level constraint to be added to an existing table.

col_name

Is a new column for the table. Column names must conform to the rules for identifiers and must be unique in the table.

column_properties =

datatype [NULL | IDENTITY[(seed, increment)]]

datatype

Specifies the datatype of the column. System or user-defined datatypes are acceptable. Columns added to a table must be defined as NULL. When a column is added, the initial value for the column will be set to NULL. This restriction forces the ALTER TABLE statement to fail if the bit or timestamp datatypes are used.

IDENTITY[(seed, increment)]

Generates values for existing rows based on the seed and increment parameters. If used, the seed value will be assigned to the first row in the table and each subsequent row will receive the next identity value, equal to the last identity plus the increment value. If neither argument is given, both default to 1.

Note  If the maximum value, based on the datatype for the identity column, is exceeded during the generation of identity values, the ALTER TABLE statement fails and an error is returned.

The IDENTITY property cannot be added to an existing column; it can be added only to a new column. The IDENTITY property can be assigned a tinyint, smallint, int, decimal(p,0) or numeric(p,0) column that does not allow null values. Defaults and DEFAULT constraints cannot be bound to an identity column, and an identity value cannot be changed. Only one column per table can be defined as an identity column.

column_constraints =

Can include up to one UNIQUE or FOREIGN KEY constraint, one DEFAULT constraint, and any number of CHECK constraints for each new or existing column. All can be entered within the same ALTER TABLE statement.

For a column-level UNIQUE constraint:

[CONSTRAINT constraint_name]
UNIQUE [CLUSTERED | NONCLUSTERED] [(col_name)]
[WITH FILLFACTOR = fillfactor]
[ON segment_name]

For a column-level FOREIGN KEY constraint:

[CONSTRAINT constraint_name]
[FOREIGN KEY [(col_name)]]
REFERENCES [owner.]ref_table [(ref_col)]

For a column-level DEFAULT constraint:

[CONSTRAINT constraint_name]
DEFAULT {constant_expression | niladic-function | NULL}

For a column-level CHECK constraint:

[CONSTRAINT constraint_name]
CHECK [NOT FOR REPLICATION] (expression)

table_constraint =

Can include up to one PRIMARY KEY constraint per table, one DEFAULT constraint per column, and any number of FOREIGN KEY, UNIQUE, or CHECK constraints on any column or columns. All can be entered within the same ALTER TABLE statement.

For a table-level PRIMARY KEY constraint:

[CONSTRAINT constraint_name]
PRIMARY KEY [CLUSTERED | NONCLUSTERED]
(col_name [, col_name2 [..., col_name16]])
[WITH FILLFACTOR = fillfactor]
[ON segment_name]

For a table-level UNIQUE constraint:

[CONSTRAINT constraint_name]
UNIQUE [CLUSTERED | NONCLUSTERED]
(col_name [, col_name2 [..., col_name16]])
[WITH FILLFACTOR = fillfactor]
[ON segment_name]

For a table-level FOREIGN KEY constraint:

[CONSTRAINT constraint_name]
FOREIGN KEY (col_name [, col_name2 [..., col_name16]])
REFERENCES [owner.]ref_table [(ref_col [, ref_col2
[..., ref_col16]])]

For a table-level DEFAULT constraint:

[CONSTRAINT constraint_name]
DEFAULT {constant_expression | niladic-function | NULL}
FOR col_name

For a table-level CHECK constraint:

[CONSTRAINT constraint_name]
CHECK [NOT FOR REPLICATION] (expression)

Important  When a PRIMARY KEY or UNIQUE constraint is added, an index is automatically created to enforce the constraint. If the constraint creates a clustered index, other indexes (previously created with CREATE INDEX or with other constraints) will need to be rebuilt by the system. Rebuilding indexes can be a potentially time-intensive operation with numerous concurrency ramifications. Whenever possible, make data definition changes when database activity is minimal.

CONSTRAINT constraint_name

Names the given constraint within the database. Constraint names must follow the rules for identifiers, except that the name cannot begin with a pound sign (#). If constraint_name is not supplied, a system-generated name is assigned to the constraint.

UNIQUE [CLUSTERED | NONCLUSTERED]

Provides entity integrity for a given column or columns. Although columns participating in UNIQUE constraints can allow null values, it is not recommended that you use null values. If null values are necessary, the complete key (a single column or multiple columns for a composite index) cannot be NULL for more than one row. Multiple UNIQUE constraints can be defined on a specific table. SQL Server automatically creates a UNIQUE index on this column or columns. UNIQUE key constraints can be dropped only by dropping the associated table or constraint. If no index type is specified, a NONCLUSTERED index is created by default.

WITH FILLFACTOR = fillfactor

Specifies how full SQL Server makes each index page when creating an index with existing data.

ON segment_name

Creates the index on the specified segment. If the index specified is a clustered index, the entire table will be moved to the specified segment. It is important that the segment have at least 1.2 times the space required for the entire table. For more information, see the CREATE INDEX statement.

[FOREIGN KEY [(col_name)]] REFERENCES [owner.]ref_table [(ref_col)]

or

FOREIGN KEY (col_name [, col_name2 [..., col_name16]])
REFERENCES [owner.]ref_table [(ref_col [, ref_col2 [..., ref_col16]])]

Provides single- or multicolumn referential integrity. When defined, the number of columns and datatypes of each column specified in the FOREIGN KEY clause must identically match the columns in the REFERENCES clause. Values entered in this column or columns must exist in the table, and column(s) defined in the REFERENCES clause and the referenced table's columns should have a PRIMARY KEY or UNIQUE constraint defined on them. For column-level constraints, using the FOREIGN KEY and col_name identifiers are optional.

When a FOREIGN KEY constraint is added to a table, all non-null values in the foreign key column(s) must reference an existing key within the referenced table. If any rows are invalid, the ALTER TABLE statement will fail.

Important  REFERENCE constraints can reference only tables within the same database; this can include the same table on which the reference is defined (self-referenced tables). If you want cross-database referential integrity or custom messaging, implement these through triggers.

A table can have a maximum of 31 FOREIGN KEY constraints. This limit is an absolute upper limit; the maximum may be lower depending on the number of work tables the server has to create to enforce the constraint and varies by the type of query being executed. FOREIGN KEY constraints are not enforced for temporary tables.

FOREIGN KEY constraints, unlike PRIMARY KEY constraints, do not create an index. To improve performance of data retrieval operations, use the CREATE INDEX statement to create an index on a column with a FOREIGN KEY constraint. This will allow for quicker execution times when a referenced key is modified.

For a FOREIGN KEY to be successfully created, the user must have SELECT or REFERENCES permission on the referenced column or columns. For details, see the GRANT statement. When a specific reference column(s) is not provided, the primary key for the referenced table is used.

Note  If REFERENCE constraints are added or altered, any stored procedures that reference the table will be recompiled. This allows changes made to a table definition (through the ALTER TABLE statement) to be visible to procedures created prior to the schema change.

DEFAULT constant_expression | niladic-function | NULL

Specifies the value that will be provided for the column when one is not explicitly supplied during an insert. A DEFAULT constraint can contain constant values, functions, built-in functions that do not take arguments (niladic-function), or NULL. A constant_expression must follow the same rules as defaults.

DEFAULT constraints can be added to columns that are not the timestamp datatype or have the IDENTITY property. If the column was defined with a user-defined datatype that has a default bound to it or if the column has a default bound to it, the DEFAULT constraint will not be allowed and the ALTER TABLE statement will fail. If a default or a DEFAULT constraint already exists for that column, it must be dropped before a DEFAULT constraint can be added. If the default exists on a user-defined datatype, the default must be unbound before that datatype can be used in a table definition with a DEFAULT constraint.

Niladic-functions allow a system-supplied value to be inserted when no value is specified. ANSI-standard niladic-functions include:

•	USER

•	CURRENT_USER

•	SESSION_USER

•	SYSTEM_USER

•	CURRENT_TIMESTAMP

USER, CURRENT_USER, and SESSION_USER all default to the database username of the user performing the insert or update. SYSTEM_USER will provide the login ID, and CURRENT_TIMESTAMP will provide the same information as the GETDATE() function.

A benefit to using a DEFAULT constraint instead of a default (created with the CREATE DEFAULT statement) is that no explicit binding/unbinding is required and DEFAULT constraints are removed when the table is dropped.

When a DEFAULT is added for an existing column (as a table-level constraint), the column to which it applies is specified with FOR col_name.

CHECK (expression)

Enforces domain integrity by limiting the possible values that can be entered into a column or columns. The search condition must evaluate to a Boolean expression and cannot contain subqueries. CHECK constraints adhere to the same policies as rules, but they are automatically bound to the column(s) on which they are defined and can reference other columns. Multiple CHECK constraints can be defined for a table; however, only one can be defined per column per ALTER TABLE statement (although each column constraint can have multiple conditions). When a rule and one or more CHECK constraints exist for a column or columns, all restrictions are evaluated. If defined on multiple columns, they must be defined as table-level constraints.

NOT FOR REPLICATION

Prevents the specified CHECK constraint from being enforced for the distribution process used by replication; however, CHECK constraints will be enforced for all other users (including the system administrator). NOT FOR REPLICATION is used to protect horizontally partitioned tables that receive "source" data from a publishing server from data modifications made to the replicated data. When replication is in effect, any modifications to the data that is replicated should be made on the publishing server (the main source of the data) and not on any of the subscribing servers (each of which receives exact copies of the publishing server's data).

The NOT FOR REPLICATION CHECK constraint will be 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 will be checked; if they fall within the replicated range, they will be rejected.

When NOT FOR REPLICATION is used with ALTER TABLE, existing data is not checked to see if it meets the requirements of the constraint. The NOT FOR REPLICATION clause behaves as though the NOCHECK option were used on the column(s). All future data modifications, except those occurring through replication, will be checked.

PRIMARY KEY [CLUSTERED | NONCLUSTERED]

Enforces entity integrity only for an existing column or columns. New columns cannot be added as a PRIMARY KEY because a new column cannot be defined NOT NULL and a PRIMARY KEY constraint must be NOT NULL. All columns changed to PRIMARY KEY constraint columns must have been defined as NOT NULL.

To enforce uniqueness of a primary key, SQL Server automatically creates a unique index on this column or columns. This unique index can be dropped only by dropping the associated table or PRIMARY KEY constraint.

If no index type is specified, a clustered index is created by default. If NONCLUSTERED is specified or if CLUSTERED is specified for a different UNIQUE constraint in the same statement block, a nonclustered index is created.

Only one PRIMARY KEY constraint can be specified for a given table. However, "alternate" or "candidate" keys can be effectively created with a UNIQUE constraint.

DROP CONSTRAINT constraint_name

Allows an existing column- or table-level constraint to be removed from the table definition.

Remarks

ALTER TABLE adds columns or constraints to a table, or drops constraints from a table, but it does not allow columns to be removed. When constraints are added, all existing data will be verified for constraint violations. If you do not want to verify new CHECK or FOREIGN KEY constraints against existing data, use the WITH NOCHECK option; but this is not recommended.

The number of columns in a table cannot exceed 250. The maximum number of bytes per row is 1962, not including text or image columns, which are stored with their own separate chain of data pages.

Important  If a stored procedure using SELECT * references a table that has been altered with new columns, the procedure (even if you use the WITH RECOMPILE option) does not recognize the columns you added to the table. In order for the new columns to be visible to the procedure, you must drop the stored procedure and then re-create it.

To rename a table, execute the sp_rename system stored procedure. To get information on a table and its columns, use the sp_help system stored procedure or the sp_helpconstraint system stored procedure.

Permission

ALTER TABLE permission defaults to the table owner. Permission cannot be transferred; however, the database owner can impersonate the table owner by using the SETUSER statement. The system administrator can also alter users' tables.

Examples

A.	Add a PRIMARY KEY Constraint

The authors table in SQL Server 6.0 includes a PRIMARY KEY constraint on the au_id column. This example shows how to add only this constraint (with an explicit name).

ALTER TABLE authors

ADD

CONSTRAINT UPKCL_auidind PRIMARY KEY CLUSTERED (au_id)

B.	Add a FOREIGN KEY Constraint

The titles table in SQL Server 6.0 includes a foreign key reference to the authors table. This example adds only this constraint (allowing the system to supply a name).

ALTER TABLE titles

ADD

CONSTRAINT FK_pub_id FOREIGN KEY (pub_id) REFERENCES publishers(pub_id)

C.	Add a UNIQUE Constraint

The stores table has columns of stor_id, stor_name, and city, where stor_id is the primary key; however, no two stores in the same city should have the same name. This example adds only this constraint.

ALTER TABLE stores

ADD

CONSTRAINT UNC_name_city UNIQUE NONCLUSTERED (stor_name, city)

D.	Add a DEFAULT Constraint

The authors table has a phone column where a value is required. This example adds a default value of UNKNOWN for future inserts that do not explicitly enter a phone number.

ALTER TABLE authors

ADD

DEFAULT 'UNKNOWN' FOR phone

E.	Add a CHECK Constraint

The authors table has a zip column where a 5-digit character string is required. This example adds a CHECK constraint to guarantee that only numbers are entered.

ALTER TABLE authors

ADD

CONSTRAINT CK_zip CHECK (zip LIKE '[0-9][0-9][0-9][0-9][0-9]')

F.	Add a New Column with Constraints

In SQL Server 6.0, the publishers table has a new column called country with a default value of USA. This example adds the country column.

ALTER TABLE publishers

ADD

country varchar(30)	NULL

DEFAULT('USA')

G.	Complex ALTER TABLE Statement with Multiple Changes

In SQL Server 6.0, the publishers table has a CHECK and PRIMARY KEY constraint on the pub_id column and a new column called country with a default value of USA. This example alters the table with all of these changes.

ALTER TABLE publishers

ADD

country varchar(30)	NULL

DEFAULT('USA'),

CONSTRAINT UPKCL_pubind PRIMARY KEY CLUSTERED (pub_id) ,

CHECK (pub_id IN ('1389', '0736', '0877', '1622', '1756')

OR pub_id LIKE '99[0-9][0-9]')

H.	Drop a Constraint

To drop a constraint, you must first know the constraint name. If the constraint names were not explicitly entered, use either the sp_help or the sp_helpconstraint system stored procedure to retrieve the system-supplied constraint names.

This example drops the UPKCL_auidind created in example A.

ALTER TABLE authors

DROP CONSTRAINT UPKCL_auidind

See Also

CREATE TABLE	sp_help
DROP TABLE	sp_rename


Batches

A batch is a set of SQL statements submitted together and executed as a group. A script is often a series of batches submitted one after the other. A batch is compiled only once as a whole and is terminated by an end-of-batch signal. Because of this, certain restrictions on batch size exist.

These rules apply to batches:

•	CREATE DEFAULT, CREATE PROCEDURE, CREATE RULE, CREATE TRIGGER, and CREATE VIEW statements cannot be combined with other statements in a batch. They must be submitted one at a time.

•	Rules and defaults cannot be bound to columns and used within the same batch. That is, the sp_bindrule and sp_bindefault system stored procedures cannot be used in the same batch as INSERT statements that invoke the rule or default.

•	CHECK constraints follow the same rule as rules and defaults. A table created with CHECK constraints cannot enforce those constraints in the same batch as the definition.

•	You cannot drop an object and then reference or re-create it in the same batch.

•	You cannot alter a table and then reference the new columns in the same batch.

•	Options changed with a SET statement take effect only at the end of the batch. For details, see the SET statement.

•	You can submit batches through a graphical tool such as the ISQL/w utility, through a command-line utility such as isql, or through files (scripts) passed to isql. A file submitted to isql can include more than one batch of SQL statements if each batch is terminated by the GO command batch separator.

•	The SQL Server batch size of 128K limits the maximum amount of explicit data values that can be inserted or updated in a single batch. Since some memory is required for a query's execution plan, the actual size of the data you can insert or update is somewhat less than 128K. For example, you might be able to insert or update one column of 125K or two columns of 60K each. This limit does not apply to text or image data inserted or updated with WRITETEXT or UPDATETEXT, data inserted with the bcp command-line utility, data inserted from another table, or data passed by remote procedure calls.

Examples

A.	Multiple SELECTs

This example shows multiple selects in one batch. Two results sets will be returned.

SELECT COUNT(*) FROM titles

SELECT COUNT(*) FROM authors

B.	Create and Use an Object

This example shows a table creation, an insert, and then a select.

CREATE TABLE test

(

column1 	char(10)	NOT NULL,

column2 	int	NULL

)

INSERT test

VALUES ('hello', 598)

SELECT * FROM test

C.	INSERT with Constraints in Separate Batches

This example shows how batches that include table definition and inserts into the table should be written. First, create the table in a separate batch from the INSERT statements(s), and then place the INSERT(s) in a separate batch.

This INSERT fails because 1234 is not a valid publisher ID.

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')
)
go

INSERT publishers (pub_id, pub_name) VALUES('1234', 'Publishers test')

See Also

CREATE DEFAULT	CREATE TABLE
CREATE INDEX	CREATE TRIGGER
CREATE PROCEDURE	CREATE VIEW
CREATE RULE	SET


CASE Expression

The CASE expression allows SQL expressions to be simplified for conditional values. The CASE expression in SQL Server 6.0 is ANSI SQL-92−compliant and allowed anywhere an expression is used.

Syntax

Simple CASE expression:

CASE expression
WHEN expression1 THEN expression1
[[WHEN expression2 THEN expression2] [...]]
[ELSE expressionN]
END

Searched CASE expression:

CASE
WHEN Boolean_expression1 THEN expression1
[[WHEN Boolean_expression2 THEN expression2] [...]]
[ELSE expressionN]
END

CASE-related functions:

COALESCE (expression1, expression2)
COALESCE (expression1, expression2, ...expressionN)
NULLIF (expression1, expression2)

where

expression

Is a constant, column name, function, subquery, and any combination of arithmetic, bitwise, and string operators.

In a simple CASE expression, the first expression is compared to the expression in each WHEN clause for equivalency. If these expressions are equivalent, the expression in the THEN clause will be returned.

Boolean_expression

Determines whether to use the THEN clause. The searched CASE expression allows comparison operators, and the use of AND and/or OR between each Boolean_expression. A simple CASE expression does not. The simple CASE expression checks only for equivalent values.

ELSE expressionN

Specifies the result to be returned when all other WHEN clauses fail. ELSE expressionN is optional. When not included, if all other WHEN clauses fail, CASE returns NULL.

COALESCE (expression1, expression2)

Is equivalent to a searched CASE expression where a NOT NULL expression1 returns expression1 and a NULL expression1 returns expression2. In searched CASE expression form, it would look like this:

CASE
WHEN expression1 IS NOT NULL THEN expression1
ELSE expression2
END

COALESCE (expression1, expression2, ... expressionN)

Is equivalent to the COALESCE function where each of the expressions return that expression when the value is NOT NULL. A NULL expressionN will return the first non-null expressionN in the list. If no non-null values are found, CASE returns NULL. In searched CASE statement form, it would look like this:

CASE
WHEN value_expression1 IS NOT NULL THEN value_expression1
ELSE COALESCE(value_expression2, ... value_expressionN)
END

NULLIF (expression1, expression2)

Is equivalent to a searched CASE expression where expression1 = expression2 and the resulting expression is NULL. In searched CASE expression form, it would look like this:

CASE
WHEN expression1=expression2 THEN NULL
ELSE expression1
END

Remarks

All datatypes used for the replacement expression in the THEN clause must include compatible datatypes. This table shows compatible and resulting datatypes.

Datatypes in THEN expressions	Resulting datatype
Mixed.	If the datatype used is not compatible (implicit conversion not supported by SQL Server), an error will occur.
Combination of fixed-length char with lengths cl1, cl2, and cl3.	Fixed-length char with length equal to the greater of cl1, cl2, and cl3.
Combination of fixed-length binary with lengths bl1, bl2, and bl3.	Fixed-length binary with length equal to the greater of bl1, bl2, and bl3.
Combination of fixed and variable-length char.	Variable-length char with length equal to the maximum-length expression.
Combination of fixed and variable-length binary.	Variable-length binary with length equal to the maximum-length expression.
Combination of numeric datatypes (for example, smallint, int, float, money, numeric, and decimal).	Datatype equal to the maximum precision expression. For example, if one expression resulted in an int and another in a float, the resulting datatype would be float, because float is more precise than int.
Examples

A.	SELECT Statement with a Simple CASE Expression

Within a SELECT statement, a simple CASE expression allows only an equality check; no other comparisons are made. In this example, the CASE expression is used to alter the display of book categories to make them more understandable.

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,
"Shortended Title" = CONVERT(varchar(30), title),
Price = price
FROM titles
WHERE price IS NOT NULL
ORDER BY type
COMPUTE AVG(price) BY type
go

Category            Shortended Title               Price
------------------- ------------------------------ -----------
Business            Cooking with Computers: Surrep 11.95
Business            Straight Talk About Computers  19.99
Business            The Busy Executive's Database  19.99
Business            You Can Combat Computer Stress 2.99

                                                   avg
                                                   ===========
                                                   13.73

Category            Shortended Title               Price
------------------- ------------------------------ -----------
Modern Cooking      Silicon Valley Gastronomic Tre 19.99
Modern Cooking      The Gourmet Microwave          2.99

                                                   avg
                                                   ===========
                                                   11.49

Category            Shortended Title               Price
------------------- ------------------------------ -----------
Popular Computing   But Is It User Friendly?       22.95
Popular Computing   Secrets of Silicon Valley      20.00

                                                   avg
                                                   ===========
                                                   21.48

Category            Shortended Title               Price
------------------- ------------------------------ -----------
Psychology          Computer Phobic And Non-Phobic 21.59
Psychology          Emotional Security: A New Algo 7.99
Psychology          Is Anger the Enemy?            10.95
Psychology          Life Without Fear              7.00
Psychology          Prolonged Data Deprivation: Fo 19.99

                                                   avg
                                                   ===========
                                                   13.50

Category            Shortended Title               Price
------------------- ------------------------------ -----------
Traditional Cooking Fifty Years in Buckingham Pala 11.95
Traditional Cooking Onions, Leeks, and Garlic: Coo 20.95
Traditional Cooking Sushi, Anyone?                 14.99

                                                   avg
                                                   ===========
                                                   15.96

(21 row(s) affected)

B.	SELECT Statement with Simple and Searched CASE Expressions

Within a SELECT statement, the searched CASE expression allows values to be replaced in the results set based on comparison values. In this example, the price (a money column) is displayed as a text comment based on ranges of cost for the books. It is important that all possibilities are checked.

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,
"Shortened Title" = CONVERT(varchar(20), title),
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
FROM titles
ORDER BY price
go

Price Category        Shortened Title      Category
--------------------- -------------------- -------------------
Not yet priced        Net Etiquette        Popular Computing
Not yet priced        The Psychology of Co Not yet categorized
Very Reasonable Title The Gourmet Microwav Modern Cooking
Very Reasonable Title You Can Combat Compu Business
Very Reasonable Title Life Without Fear    Psychology
Very Reasonable Title Emotional Security:  Psychology
Coffee Table Title    Is Anger the Enemy?  Psychology
Coffee Table Title    Cooking with Compute Business
Coffee Table Title    Fifty Years in Bucki Traditional Cooking
Coffee Table Title    Sushi, Anyone?       Traditional Cooking
Coffee Table Title    Prolonged Data Depri Psychology
Coffee Table Title    Silicon Valley Gastr Modern Cooking
Coffee Table Title    Straight Talk About  Business
Coffee Table Title    The Busy Executive's Business
Expensive book!       Secrets of Silicon V Popular Computing
Expensive book!       Onions, Leeks, and G Traditional Cooking
Expensive book!       Computer Phobic and  Psychology
Expensive book!       But Is It User Frien Popular Computing

(18 row(s) affected)

C.	SELECT Statement with Searched CASE Expressions and Nested Subquery

Within a SELECT statement, the searched CASE expression allows values to be replaced in the results set based on comparison values. In this example, the royalty percentage is checked in a separate table to determine a royalty category for each author.

SELECT "Author's Full Name" = CONVERT(varchar(25), (RTRIM(au_fname) +
 ' ' + RTRIM(au_lname))),

"Shortened Title" = CONVERT(varchar(25), title),

"Royalty Category" =
CASE

WHEN (SELECT AVG(royaltyper) FROM titleauthor ta

WHERE t.title_id = ta.title_id) > 60
THEN 'High Royalty'

WHEN (SELECT AVG(royaltyper) FROM titleauthor ta

WHERE t.title_id = ta.title_id)
BETWEEN 41 and 59

THEN 'Medium Royalty'

ELSE 'Low Royalty'

END

FROM authors a, titles t, titleauthor ta

WHERE a.au_id = ta.au_id AND ta.title_id = t.title_id

ORDER BY "Royalty Category", "Author's Full Name"

go

Author's Full Name        Shortened Title           Royalty Category
------------------------- ------------------------- ----------------
Akiko Yokomoto            Sushi, Anyone?            Low Royalty
Burt Gringlesby           Sushi, Anyone?            Low Royalty
Michael O'Leary           Sushi, Anyone?            Low Royalty
Albert Ringer             Life Without Fear         High Royalty
Charlene Locksley         Emotional Security: A New High Royalty
Charlene Locksley         Net Etiquette             High Royalty
Cheryl Carson             But Is It User Friendly?  High Royalty
Innes del Castillo        Silicon Valley Gastronomi High Royalty
Johnson White             Prolonged Data Deprivatio High Royalty
Marjorie Green            You Can Combat Computer S High Royalty
Reginald Blotchet-Halls   Fifty Years in Buckingham High Royalty
Sylvia Panteley           Onions, Leeks, and Garlic High Royalty
Abraham Bennet            The Busy Executive's Data Medium Royalty
Albert Ringer             Is Anger the Enemy?       Medium Royalty
Ann Dull                  Secrets of Silicon Valley Medium Royalty
Anne Ringer               Is Anger the Enemy?       Medium Royalty
Anne Ringer               The Gourmet Microwave     Medium Royalty
Livia Karsen              Computer Phobic and Non-P Medium Royalty
Marjorie Green            The Busy Executive's Data Medium Royalty
Michael O'Leary           Cooking with Computers: S Medium Royalty
Michel DeFrance           The Gourmet Microwave     Medium Royalty
Sheryl Hunter             Secrets of Silicon Valley Medium Royalty
Stearns MacFeather        Computer Phobic and Non-P Medium Royalty
Stearns MacFeather        Cooking with Computers: S Medium Royalty

(25 row(s) affected)

D.	UPDATE Statement with CASE Expressions

With an UPDATE statement and CASE expressions, it's easy to modify a significant number of rows based on multiple columns of conditional information. In this example, reviews have been turned in and salary increases are due. A review rating of 4 will double the worker's salary, 3 will increase it by 60 percent, 2 will increase it by 20 percent, and a rating lower than 2 results in no raise. Also, a raise will not be given if the employee has been at the company for less than 18 months.

UPDATE employee_salaries
SET salary =
CASE
WHEN (review = 4 AND
(DATEDIFF(month, hire_date, GETDATE()) > 18))
THEN salary * 2
WHEN (review = 3 AND
(DATEDIFF(month, hire_date, GETDATE()) > 18))
THEN salary * 1.6
WHEN (review = 2 AND
(DATEDIFF(month, hire_date, GETDATE()) > 18))
THEN salary * 1.2
ELSE salary
END

E.	CASE-related Function (COALESCE)

In this example, a 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 non-null value found in hourly_wage, salary, and commission.

CREATE TABLE wages
(
emp_id	tinyint 	identity,
hourly_wage	decimal	NULL,
salary	decimal 	NULL,
commission	decimal	NULL,
num_sales	tinyint	NULL
)
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

SELECT "Total Salary" = CONVERT(money,

(COALESCE(hourly_wage * 40 * 52,

salary,

commission * num_sales)))
FROM wages

go

Total Salary
--------------------------
20,800.00
41,600.00
62,400.00
83,200.00
10,000.00
20,000.00
30,000.00
40,000.00
45,000.00
50,000.00
120,000.00
56,000.00

(12 row(s) affected)

F.	CASE-related Functions (NULLIF and COALESCE)

In this example, the budgets table is created 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 whose budget will not change from the prior year, and 0 is used for budgets that have not yet been determined. To find out the average of only those departments that have received a budget as well as include the budget value from the prior year (use the previous_year value, where the current_year is 0), combine the NULLIF and COALESCE functions.

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)

SELECT "Average Budget" = AVG(NULLIF(COALESCE(current_year,
 previous_year), 0.00))

FROM budgets

go

Average Budget
----------------------------------------
212500.000000

(1 row(s) affected)

See Also

Expressions	SELECT
Search Conditions	UPDATE


CHECKPOINT Statement

Forces all dirty pages (those that have been updated since the last checkpoint) in the current database to be written to disk. Checkpoints caused by the CHECKPOINT statement supplement automatic checkpoints, which occur at intervals calculated by SQL Server on the basis of the configurable value for maximum acceptable recovery time.

Syntax

CHECKPOINT

Remarks

The CHECKPOINT statement saves time in recovery by identifying a point at which all completed transactions 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.

The automatic checkpoint interval is calculated by SQL Server on the basis of system activity and the recovery interval value in the syscurconfigs system table. The recovery interval determines checkpoint frequency by specifying the amount of time it should take the system to recover. Reset this value by executing the sp_configure system stored procedure and the RECONFIGURE statement. For details, see the Microsoft SQL Server Administrator's Companion.

Although automatic recovery will always recover rows after a power failure, use CHECKPOINT as a precautionary measure and to speed up recovery after power failures. For example, if the automatic checkpoint is infrequent because the recovery interval is set high, use the CHECKPOINT statement to force the dirty pages out of the data cache and onto the actual disk pages.

Note  In addition to occurring automatically at the recovery interval, a checkpoint will also occur at two other times: After you change a database option with the sp_dboption system stored procedure, a checkpoint will automatically occur within the database where the option was changed. Using the SHUTDOWN statement or stopping the server with the SQL Service Manager also forces a checkpoint in every database.

Permission

Permission to use the CHECKPOINT statement defaults to the database owner. It cannot be transferred.

See Also

RECONFIGURE	sp_dboption
SHUTDOWN


Comments

Comments provide user-documented information about SQL statements, statement blocks, and stored procedures.

Syntax

/* text_of_comment */

Or

-- text_of_comment

where

text_of_comment

Represents a statement or section that should not be evaluated by the server. 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.

Remarks

Multiple-line comments are allowed as long as they are surrounded by /* and */. A stylistic convention often used for multiple-line comments is to begin the first line with /*, subsequent lines with **, and end with */.

Single-line or nested comments are supported with the ANSI-standard comments of the double hyphens (--). Comments inserted with -- are delimited by the end-of-line (NEWLINE) character.

There is no maximum length for comments.

Note  To avoid generating an error message, do not include a GO command within a comment.

Example

Combining Comments

In this example, comments are used to document and test the behavior during different phases of development for a trigger. In this "in progress" 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; ANSI-style comments are shown both alone and nested.

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. For information about

triggers, see the Microsoft SQL Server Transact-SQL Reference.

*/
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


Control-of-Flow Language

Control-of-flow language controls the flow of execution of SQL statements, statement blocks, and stored procedures. These keywords can be used in ad hoc SQL statements, in batches, and in stored procedures.

These are the control-of-flow keywords:

Keyword	Description
BEGIN...END	Defines a statement block.
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.
...BREAK	Exits the innermost WHILE loop.
...CONTINUE	Restarts a WHILE loop.
In addition to the keywords used for conditional processing and control-of-flow for SQL statements, a variety of helpful Transact-SQL extensions and ANSI-standard additions are available:

Feature	Description
CASE Expression	Allows an expression to have conditional return values. This is the ANSI SQL-92−standard CASE expression.
Comments	Inserts a comment anywhere in an SQL statement. Two commenting styles are supported: Transact-SQL style (/* and */) and as ANSI-standard comment style (--).
DECLARE Statement	Declares local variables as well as cursors.
PRINT Statement	Prints a user-defined message on the user's screen.
RAISERROR Statement	Returns a sysmessages entry or a dynamically built message with user-specified severity and state. RAISERROR also sets a system flag (in the global variable @@ERROR) to record that an error condition has occurred.
The control-of-flow keywords and their syntax are shown in the following sections.


BEGIN...END Block

Encloses a series of SQL statements so that control-of-flow language, such as IF...ELSE, affects the performance of a group of statements instead of only the statement that immediately follows IF...ELSE. BEGIN...END blocks can be nested.

Syntax

BEGIN
{sql_statement | statement_block}
END

where

sql_statement | statement_block

Is any valid grouping of Transact-SQL statements. Although all SQL statements are valid within a BEGIN...END block, certain SQL statements should not be grouped together within the same block (or batch). For details, see the Batches topic and the individual statements you're using.


GOTO label

Alters the flow of execution to a label. The 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, and they can be nested.

Syntax

Define the label:

label:

Alter the execution:

GOTO label

where

label

Defines the point after which processing will begin if a GOTO is targeted to that label. Labels must follow the rules for identifiers. A label can be used as a commenting method regardless of 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.


IF...ELSE Block

Imposes conditions on the execution of an SQL statement. The 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 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 [Boolean_expression]
{sql_statement | statement_block}]

where

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 SQL statement or statement grouping as defined with a statement block. The IF or ELSE condition can affect the performance of only a single SQL statement unless a statement block is used. To define a statement block, use the control-of-flow keywords BEGIN and END.

Remarks

IF...ELSE constructs can be used in batches, in stored procedures (where 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 levels of nesting.


RETURN Statement

Exits unconditionally from a query or procedure. RETURN is immediate and complete; statements following RETURN are not executed.

Syntax

RETURN ([integer_expression])

where

integer_expression

Is the integer value returned. Stored procedures can return an integer value to a calling procedure or an application.

Remarks

The RETURN keyword can be used at any point where you want to exit from a procedure, batch, or statement block.

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 where @@status is NULL), a warning message is generated and a value in the range of 0 through − 14 is returned.

SQL Server reserves 0 to indicate a successful return and reserves negative values from − 1 through − 99 to indicate different reasons for failure. If no user-defined return value is provided, the SQL Server value is used. User-defined return status values should not conflict with those reserved by SQL Server. The values 0 through −14 are currently in use.

Value		Meaning
0	Procedure was executed successfully.
−1	Object is missing.
−2	Datatype error occurred.
−3	Process was chosen as deadlock victim.
−4	Permission error occurred.
−5	Syntax error occurred.
−6	Miscellaneous user error occurred.
−7	Resource error, such as out of space, occurred.
−8	Nonfatal internal problem was encountered.
−9	System limit was reached.
−10	Fatal internal inconsistency occurred.
−11	Fatal internal inconsistency occurred.
−12	Table or index is corrupt.
−13	Database is corrupt.
−14	Hardware error occurred.
If more than one error occurs during execution, the status with the highest absolute value is returned. User-defined return values always take precedence over those supplied by SQL Server.

You can include the return status value in subsequent Transact-SQL statements in the batch or procedure that executed the current procedure, but you must enter it in the following form:

EXECute @@return_status = procedure_name

For more information, see the EXECUTE statement.


WAITFOR Statement

Specifies a time, time interval, or event that triggers execution of a statement block, stored procedure, or transaction.

Syntax

WAITFOR {DELAY 'time' | TIME 'time'}

where

DELAY

Instructs SQL Server to wait until the specified amount of time has passed, up to a maximum of 24 hours.

TIME

Instructs SQL Server to wait until the specified time.

time

Specifies a time in one of the acceptable formats for datetime data. The time you specify can include hours, minutes, and seconds. Use the format 'hh:mm:ss'. You cannot specify dates — the date portion of the datetime value is not allowed. You can also specify a local variable in place of the 'time' string. For details, see the Datatypes topic.

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 the sp_who system stored procedure.


WHILE Construct

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]

where

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 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 WHILE loop. BREAK is often (but not always) activated by an IF test. Any statements that appear after the END keyword that marks the end of the loop are executed.

CONTINUE

Causes the WHILE loop to restart, skipping any statements after CONTINUE. CONTINUE is often (but not always) activated by an IF test.

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.

Control-of-Flow
Examples

A.	Statement Block Definition with BEGIN...END

In this example, BEGIN and END define the group of SQL statements that should always 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.

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

ELSE

PRINT 'Deletion successful. No sales for this title.'

B.	IF...ELSE with a Statement Block

This example shows an IF condition with a statement block. If the average price of the titles is not less than $15, nothing will be executed.

IF (SELECT AVG(price) FROM titles) < $15

BEGIN

UPDATE titles

SET price = price * $2

SELECT title, price

FROM titles

WHERE price > $28

END

C.	WHILE Construct (Using BREAK and CONTINUE) with Nested IF...ELSE

In this example, if the average price is less than $30 this WHILE loop doubles the prices and then selects the maximum price. If the maximum price is less than or equal to $50, restart the WHILE loop and double 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.

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'

D.	WHILE Within a Procedure Using 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 global variable used with cursors. Because @@fetch_status will return −2, −1, or 0, all three cases must be tested. In this case, if a row is deleted from the cursor results since the time this stored procedure was executed, that row will be skipped. A successful fetch (0) will cause the SELECT within the BEGIN...END loop to execute.

FETCH NEXT FROM tnames_cursor INTO @@tablename

WHILE (@@fetch_status <> -1)
BEGIN
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
END

For details on this procedure, see the Cursors topic examples.

E.	Use GOTO as an Alternative to the WHILE Construct from Example D

This example shows GOTO looping as an alternative to using WHILE from example D.

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

F.	Return from a Procedure

In this example, if no username is given as a parameter when findobjs 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 findobjs @@nm varchar(30) = 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, master..syslogins l

WHERE l.name = @@nm

AND o.uid = l.suid

END

G.	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 non-CA value for state or an au_id that did not match a row).

CREATE PROC checkstate @@param varchar(11)

AS

DECLARE @@status int

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. They show an author in California, an author not in California, and an invalid author. The @@return_status 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

Return Status
-------------
1

EXEC @@return_status = checkstate '648-92-1872'
SELECT 'Return Status' = @@return_status

Return Status
-------------
2

EXEC @@return_status = checkstate '12345678901'
SELECT 'Return Status' = @@return_status

Return Status
-------------
2

H.	WAITFOR TIME

At 10:20 p.m., the stored procedure update_all_stats will be executed.

BEGIN

WAITFOR TIME '22:20'

EXECUTE update_all_stats

END

For details on using this procedure to update all statistics for a database, see the UPDATE STATISTICS statement examples.

I.	WAITFOR DELAY

This example shows how a local variable can be used with the WAITFOR DELAY option. In this example, a stored procedure is created to wait for a variable amount of time and then return 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

time_delay '000:00:10'

go

A total time of 000 hours, 00 minutes, and 10 seconds, has elapsed! Your time is up.

See Also

Batches	EXECUTE
CASE Expression	PRINT
Comments	RAISERROR
CREATE PROCEDURE	sp_addmessage
CREATE TRIGGER	sp_altermessage
Cursors	sp_dropmessage
DECLARE	Variables


CREATE DATABASE Statement

Creates a new database. You must be in the master database to create a new database.

Syntax

CREATE DATABASE database_name
[ON {DEFAULT | database_device} [= size]
[, database_device [= size]]...]
[LOG ON database_device [= size]
[, database_device [= size]]...]
[FOR LOAD]

where

database_name

Is the name of the new database. Database names must conform to the rules for identifiers.

ON

Indicates that you will specify a location and (optionally) a size for the database.

DEFAULT

Indicates that CREATE DATABASE can put the new database on any default database device(s) shown in the sysdevices table. To specify a size for the database without specifying a location, use ON DEFAULT = size. To change the status of a database device to default, use the sp_diskdefault system stored procedure.

database_device

Is the logical name of the database device on which you want to put a database. A database can occupy different amounts of space on each of several database devices. To create a device, use the DISK INIT statement.

size

Specifies the amount of space, in megabytes, allocated to the database. A database can range from 1 to 2^24 MB.

When an explicit value is not supplied, SQL Server will use the larger value between the size of the model database or the configured database size (configured with sp_configure). For example, if database size is configured to 2 (the default) and the model database has been altered to 3MB, the database will be 3MB.

LOG ON

Is the name of the device that stores the database log. You can specify more than one device in the LOG ON clause.

FOR LOAD

Prevents anyone from using the database between the CREATE DATABASE, ALTER DATABASE, and LOAD statements. FOR LOAD can also be specified with the ALTER DATABASE statement, but only if the database was created with FOR LOAD.

When a database is created with FOR LOAD, SQL Server ensures that only the database owner, by setting the database to dbo use only, can use the database. After the database has been loaded, you can change the database option by using the sp_dboption system stored procedure.

Note  This capability is similar to that provided in SQL Server 4.21a via trace flag 1802, but FOR LOAD guarantees that only the database owner can use the database between the CREATE and LOAD statements.

Remarks

When the CREATE DATABASE statement is executed, SQL Server makes a copy of the model database (the database catalog). You can update the model database just like any other database and add your own tables, stored procedures, user-defined datatypes, and so on.

In SQL Server 6.0, CREATE DATABASE is intelligent during the initialization of the device(s) on which the database will reside. When executing a CREATE DATABASE statement, SQL Server determines whether the devices are newly created. If the devices have not previously contained data, the devices will not be reinitialized.

SQL Server can manage up to 32,767 databases, each of which can be up to 1 TB in size. Each database can have a maximum of 32 device fragments. Each time you use CREATE DATABASE or ALTER DATABASE to allocate space on a database device, that allocation represents a device fragment and is entered as a row in the sysusages system table.

The total number of physical devices that can be used or the total size of each logical device is not limited (this is limited by the physical device(s) used, with an absolute maximum of 32 GB for each logical device). Instead, only the total number of logical device fragments is limited. Each device fragment can actually exist on one or more physical devices if some form of hardware or software striping is used. Whenever possible, it is recommended that striping is used. Striping can provide performance improvements and, in some cases, fault tolerance. For more information, see the Microsoft SQL Server Administrator's Companion.

If you don't specify a location and size for a database, the default location is any default database device, and the default size is the size of the model database or the configuration setting for database size. To display available devices, use the sp_helpdevice system stored procedure. To see configuration settings, use the sp_configure system stored procedure.

If SQL Server can't give as much space as you've requested, SQL Server creates the database, allocating as much space as possible (in 0.5-MB increments) on each database device, and then prints a message showing how much space was allocated and where.

Each new database inherits its database option settings from the model database. For example, the database option select into/bulkcopy is originally set to "off." You can change that setting for each newly created database by using the sp_dboption system stored procedure in the model database.

It is important to back up the master database with the DUMP DATABASE statement after each use of CREATE DATABASE. This makes recovery easier and safer in case the master database is damaged. (If you create a database and fail to back up master, you may be able to recover the changes with the DISK REFIT statement.)

To display a report on a database or on all the databases on a SQL Server, execute the sp_helpdb system stored procedure. For a report on the space used in a database, use the sp_spaceused system stored procedure.

Using the LOG ON Clause

For full recoverability, place the transaction log on a different physical device or devices from the device that stores the data. If a disk crashes, you can recover the database from database dumps and from the transaction log dumps. Although you can create a database on a single device and store the transaction log together with the rest of the database, this is not recommended because you would have to rely solely on the DUMP DATABASE statement for recovery.

Note  If you do not create the database with the LOG ON option, you can still move the transaction log later by using the sp_logdevice system stored procedure.

The size of the database device required for the transaction log varies according to the amount of update activity and the frequency of transaction log dumps. As a rule, allocate to the transaction log 10 to 25 percent of the space you allocate to the database. It is best to start small, since space allocated to a transaction log database device cannot be reclaimed and cannot be used for storage of data.

Permission

CREATE DATABASE permission defaults to the system administrator, who can transfer it. However, CREATE DATABASE permission is often centralized to maintain control over disk allocation. CREATE DATABASE permission is not included when you use the GRANT statement. For more information, see the Microsoft SQL Server Administrator's Companion.

Examples

A.	Create a Single Database on a Single Device

This example creates a 12-MB database called testing on DEVICE1.

CREATE DATABASE testing

ON DEVICE1 = 12

B.	Create a Single Database on Two Devices — Separate Data and Log

This example creates a single database (sales) with the data portion on DEVICE3 and the log portion on DEVICE4.

CREATE DATABASE sales

ON DEVICE3 = 125

LOG ON DEVICE4 = 60

C.	Create a Database FOR LOAD

This example creates a single database (personnel) with the data portion spanning three devices (DEVICE5, DEVICE6, and DEVICE7) and the log portion on DEVICE8. The total database size is 200 MB composed of 150 MB for data and 50 MB for log.

CREATE DATABASE personnel

ON DEVICE5 = 50, DEVICE6 = 50, DEVICE7 = 50

LOG ON DEVICE8 = 50

FOR LOAD

go

See Also

ALTER DATABASE	sp_helpdb
DISK INIT	sp_logdevice
DROP DATABASE	sp_renamedb
sp_changedbowner	sp_spaceused
sp_diskdefault


CREATE DEFAULT Statement

Creates an object that, when bound to a column or a user-defined datatype, 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 datatype) when no value is explicitly supplied during an insert. An alternate and preferred method to creating defaults is to create DEFAULT constraints as described with the CREATE TABLE statement. Using constraints is the preferred method of restricting column data because the constraint definition is stored with the table and automatically dropped when the table is dropped. A default is beneficial, however, when the default will be used again and again for multiple columns.

Syntax

CREATE DEFAULT [owner.]default_name
AS constant_expression

where

default_name

Is the name of the default. Default names must conform to the rules for identifiers.

constant_expression

Specifies an expression that contains only constant values (it cannot include the names of any columns or other database objects). You can use any constant, built-in function, mathematical expression, or global variable. Enclose character and date constants in single quotation marks ('); money, integer, and floating-point constants do not require quotation marks. Binary data must be preceded by 0x, and money data must be preceded by a dollar sign ($). The default value must be compatible with the datatype of the column.

Remarks

You can create a default only in the current database. Within a database, default names must be unique by owner.

After you've created a default, use the sp_bindefault system stored procedure to bind it to a column or to a user-defined datatype.

You cannot use "N/A," for example, as a default for a numeric column. If the default is not compatible with the column to which you've bound it, SQL Server generates an error message when trying to insert the default value, but not when you bind it.

If the default value is too long for the column to which you've bound it, the value will be truncated.

CREATE DEFAULT statements cannot be combined with other SQL statements in a single batch.

To display definitions and binding information, execute the sp_helptext. You can find the value of a default by using the sp_helptext system stored procedure with the default name as the parameter.

You must drop a default before you create a new one of the same name, and you must unbind a default (with the sp_unbindefault system stored procedure) before you drop it.

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.

Once bound to a column, a default value is inserted when:

•	You do not explicitly insert a value.

•	You use the DEFAULT VALUES or DEFAULT keyword with INSERT. For details and examples, see the INSERT statement.

If you specify NOT NULL when you create a column and do not create a default for it, an error message is generated whenever a user fails to make an entry in that column. The following 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.

Column  definition	No entry,  no default	No entry,  default	Enter NULL,  no default	Enter NULL,  default
NULL  NOT NULL	NULL  error	default  default	NULL  error	NULL  error
To rename a default, use the sp_rename system stored procedure. For a report on a default, use the sp_help system stored procedure.

Permission

CREATE DEFAULT permission defaults to the database owner, who can transfer it to other users.

Examples

A.	Simple Character Default

This example creates a character default of 'unknown'.

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.

sp_bindefault phonedflt, 'authors.phone'

See Also

Batches	sp_bindefault
CREATE RULE	sp_help
CREATE TABLE	sp_helptext
DROP DEFAULT	sp_rename
DROP RULE	sp_unbindefault


CREATE INDEX Statement

For more updated SQL Server 6.5 syntax, see CREATE INDEX Statement.

Creates an index on a given table that either changes the physical ordering of the table or provides the optimizer with a logical ordering of the table to increase efficiency for queries. When creating an index for the primary key, use the table- and column-level PRIMARY KEY constraint provided with the CREATE TABLE statement.

Syntax

CREATE [UNIQUE] [CLUSTERED | NONCLUSTERED] INDEX index_name
ON [[database.]owner.]table_name (column_name [, column_name]...)
[WITH
[FILLFACTOR = x]
[[,] IGNORE_DUP_KEY]
[[,] {SORTED_DATA | SORTED_DATA_REORG}]
[[,] {IGNORE_DUP_ROW | ALLOW_DUP_ROW}]]
[ON segment_name]

where

UNIQUE

Specifies to create a unique index (one in which no two rows are permitted to have the same index value). The system 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 there are duplicate key values, the statement is canceled and an error message giving the first duplicate is returned. You cannot create a unique index on a single column or multiple columns (composite index) where the complete key (all columns of that key) is NULL in more than one row; these are treated as duplicate values for indexing purposes.

Specifying a unique index makes sense only when uniqueness is a characteristic of the data itself. If uniqueness is required, create a UNIQUE or PRIMARY KEY constraint on the column. Specify a unique index only when manually enforcing a primary key (not recommended).

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 would have changed many rows but caused only one duplicate. If you try to change data on which there is a unique index and you have used the IGNORE_DUP_KEY option, only the rows that violate the UNIQUE index will fail. (For details, see the IGNORE_DUP_KEY option, later in this section.)

You cannot create a unique index on columns that already include duplicate values, whether or not IGNORE_DUP_KEY is set. If you attempt to do so, SQL Server displays an error message and lists the duplicate values. You must eliminate duplicates before you can create a unique index on the column.

CLUSTERED

Creates an object where the physical order of rows is the same as the indexed order of the rows, and the bottom, or leaf, level of the clustered index contains the actual data pages. Because a clustered index changes the physical order of the rows, create the clustered index before creating any nonclustered indexes so that the nonclustered indexes will not have to be rebuilt. By definition, only one clustered index is permitted per table (regardless of how it is created: implicitly, with constraints, or explicitly, with CREATE INDEX). Often it is created on the column(s) that is frequently accessed in groupings. Before you create indexes, it is important to know how your data will be accessed.

Using a clustered index to find data is almost always faster than using a nonclustered index. In addition, using a clustered index is advantageous when many rows with contiguous key values are being retrieved — that is, on columns that are often searched for ranges of values. Once the row with the first key value is found, rows with subsequent indexed values are guaranteed to be physically adjacent.

For example, it would be helpful on an employee table to include a nonclustered index on the primary key of emp_id; however, the clustered index could be created on lname, fname (last name, first name) as that is often how employees are grouped.

If you do not specify CLUSTERED, a nonclustered index will be 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 segment_name clause effectively moves a table from the device on which the table was created to the new segment. Before creating tables or indexes on specific segments, verify which segments are available and that they have enough empty space for the index. It is important that the segment 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 pointers to rows on data pages. That is, each leaf page contains an indexed value and a pointer to the row with that value. A nonclustered index, in comparison with a clustered index, has an extra level between the index structure and the data itself.

You can have as many as 249 nonclustered indexes per table (regardless of how they are created: implicitly, with constraints, or explicitly, with CREATE INDEX). Each can provide access to the data in a different sorted 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. You must be the owner of a table to create an index on it. 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 qualifying the database name.

table_name

Specifies the table that contains the column or columns to be indexed.

column_name

Specifies the column or columns to which the index applies. Specify two or more column names if you want 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_name.

Composite indexes are used when two or more columns are best searched as a unit. You can combine as many as 16 columns 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 256 bytes. (That is, the sum of the lengths of the columns that make up the composite index cannot exceed 256.)

FILLFACTOR

Specifies how full SQL Server should make each index page. It is seldom necessary to include the FILLFACTOR option in a CREATE INDEX statement. It is provided for fine-tuning performance and is useful only when you are creating a new index on a table with existing data, and then it is useful only when you can accurately predict future changes in that data.

The amount of empty space on an index page is important because when an index page fills up, the system must take time to split it to make room for new rows. The value of the original FILLFACTOR is stored with the index in the sysindexes table.

Note  Using 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 you don't specify a value, the default is 0. When FILLFACTOR is set to 0, only the leaf pages are filled. Space is left in nonleaf pages for at least one entry (two for nonunique clustered indexes). You can change the default with the sp_configure system stored procedure.

Use a FILLFACTOR of 100 only when there will be no inserts or updates. If FILLFACTOR is 100, SQL Server creates indexes with each page 100 percent full. A FILLFACTOR of 100 makes sense only for read-only tables. An INSERT or UPDATE made after the creation of an index with a 100 percent FILLFACTOR would cause page splits for each INSERT and possibly each UPDATE. The default FILLFACTOR algorithm assumes that there will be at least enough space for one more entry in an internal page.

Smaller FILLFACTOR values (except 0) cause SQL Server to create new indexes with pages that are not completely full. For example, a FILLFACTOR of 10 can be a reasonable choice if you are creating an index on a table that you know contains a small portion of the data 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 entry (two for nonunique clustered indexes), and the space is left in leaf pages such that no leaf page is more full than the percentage specified by FILLFACTOR, as shown in the following table.

FILLFACTOR	Internal page	Leaf page
0%	One free slot*	100% full
1 − 99%	One free slot*	<= FILLFACTOR % full
100%	100% full	100% full
* Two free slots for nonunique clustered indexes
Important  Creating a clustered index with a FILLFACTOR affects the amount of storage space your data occupies, since SQL Server redistributes the data when it creates the clustered index.

IGNORE_DUP_KEY

Controls what happens when you attempt to enter a duplicate key in a unique clustered index. It is meaningful only when the UPDATE or INSERT statement affects multiple rows. SQL Server issues a warning and does not insert the row containing the duplicate. If IGNORE_DUP_KEY is set and you issue an UPDATE or INSERT statement that creates duplicate keys, the row that causes the duplicates is ignored. In the case of UPDATE, the row is discarded.

Other changes to the database caused by the UPDATE or INSERT attempt (for example, changes to index pages) are also backed out. However, if the UPDATE or INSERT attempt affects multiple rows, the other rows are added or changed as usual. If IGNORE_DUP_KEY is not specified, no rows will be inserted by the UPDATE or INSERT statement. For more information on duplicate rows, see the IGNORE_DUP_ROW | ALLOW_DUP_ROW option, later in this section.

You cannot create a unique index on a column that already includes duplicate values, whether or not IGNORE_DUP_KEY is set. If you attempt to do so, SQL Server displays an error message and lists the duplicate values. You must eliminate duplicates before you can create a unique index on the column.

Caution  With IGNORE_DUP_KEY set, if you try to update a row in a way that creates a duplicate key, that row is discarded. Neither the new value nor the original value of the row that would produce the duplicate exists in the updated table. For example, if you try to update "Smith" to "Jones" and "Jones" already exists, you have one "Jones" and no "Smith." Essentially, the original row is lost because an UPDATE statement is actually a DELETE followed by an INSERT. SQL Server has no way to know about the disallowed duplicate when it deletes the row, and the whole transaction can't be rolled back because the purpose of IGNORE_DUP_KEY (and of the IGNORE_DUP_ROW option) is to allow a transaction to proceed in spite of the presence of duplicates.

SORTED_DATA | SORTED_DATA_REORG

Are options that eliminate the sort performed when a clustered index is created. Both options verify that the data has been sorted by checking each index value to determine whether it is higher than the previous one. If any row fails this check, the CREATE INDEX statement terminates. You can either fix the data or rerun the CREATE INDEX statement without the SORTED_DATA option (in which case the data will be sorted). The SORTED_DATA option, when the data satisfies the checks, will always be faster than the SORTED_DATA_REORG because the data is not copied and nonclustered indexes will not be rebuilt.

SORTED_DATA_REORG differs from SORTED_DATA because it physically reorganizes the data. This option is useful when a FILLFACTOR is specified to compact or expand the pages on which a table is stored. The effects of these options change slightly if used with the ON segment_name option. For details, see the ON segment_name section, later in this section.

Reorganizing the data is a good idea when a table becomes fragmented. To determine whether or not a table is contiguous, use the DBCC statement's SHOW_CONTIG. For details about what causes table fragmentation and recommended solutions, see the DBCC statement.

IGNORE_DUP_ROW | ALLOW_DUP_ROW

Are options for creating a nonunique clustered index; they are mutually exclusive. When creating a nonunique nonclustered index, these options are irrelevant because SQL Server attaches a unique row identification number internally; it never checks for duplicate rows or for identical data values.

The IGNORE_DUP_KEY, IGNORE_DUP_ROW, and ALLOW_DUP_ROW index options control what happens when a duplicate key or duplicate row is created with the INSERT or UPDATE statement. This table shows when these options can be used.

Index type	Options
Clustered	IGNORE_DUP_ROW or ALLOW_DUP_ROW
Unique clustered	IGNORE_DUP_KEY
Nonclustered	None
Unique nonclustered	IGNORE_DUP_KEY
This table illustrates how ALLOW_DUP_ROW and IGNORE_DUP_ROW affect attempts to create a nonunique clustered index on a table that includes duplicate rows and attempts to enter duplicate rows into a table.

Option set	Table has duplicate rows	Insert duplicate rows
Neither option	CREATE INDEX statement fails.	INSERT statement fails.
ALLOW_DUP_ROW	Statement is completed.	Statement is completed.
IGNORE_DUP_ROW	Index created but duplicate rows deleted; error message returned.	All rows accepted except duplicates; error message returned (see earlier caution).
ON segment_name

Specifies the database segment on which the index is to be created. A nonclustered index can be created on a different segment from the data pages. Before creating an index on a segment, verify which segments you can use. Certain segments can be allocated to specific tables or indexes for performance reasons or for other considerations.

The ON segment_name clause can affect the placement of the data portion and the index portions of a table:

•	Creating a nonclustered index on a specified segment_name ensures that index pages (current and future) will be placed on that segment. All data pages will continue to be allocated from the original segment on which the table was created.

•	Creating a clustered index with SORTED_DATA_REORG on a specified segment_name causes the entire table to be moved to that segment.

•	Creating a clustered index with SORTED_DATA on specified segment_name causes all future data pages to be allocated from the new segment_name only. The index pages (the B-tree) is created on the new seqment_name only. Current page allocations will not be affected.

Caution  If you create a table on a segment and then create a clustered index on that table without specifying a segment name, the entire table migrates to the default segment (unless the SORTED_DATA option is used).

Remarks

Space is allocated to tables and indexes in increments of one extent (8 2K pages) at a time. Each time an extent is filled, another is allocated. For a report on the amount of space allocated and used by an index, use the sp_spaceused system stored procedure.

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 (unless SORTED_DATA is specified) in order to create the clustered index, and the old, nonindexed data is deleted when the index is complete.

You can neither create an index on a view nor create indexes on columns of bit, text, and image types. As the syntax signifies, you can create an index on a table in another database as long as you are the owner of that table.

You can create an index on a temporary table. When the table is dropped or the session ends, all indexes and triggers are dropped.

If there is no data in the table when an index is created, run the UPDATE STATISTICS statement after data is added. To check when the statistics were last updated, use DBCC SHOW_STATISTICS.

A composite index, like any other index, is represented by one row in the sysindexes table.

To display a report on an object's indexes, execute the sp_helpindex system stored procedure.

Permission

CREATE INDEX permission defaults to the table owner and is not transferable.

Examples

A.	Simple Index

This example creates an index on the au_id column of the authors table.

CREATE INDEX au_id_ind

ON authors (au_id)

B.	Unique Clustered Index

This example creates an index on the au_id column of the authors table that enforces uniqueness. This index will physically order the data on disk because the CLUSTERED option is specified.

CREATE UNIQUE CLUSTERED INDEX au_id_ind

ON authors (au_id)

C.	Simple Composite Index

This example creates an index on the au_id and title_id columns of the authors table.

CREATE INDEX ind1

ON titleauthor (au_id, title_id)

D.	FILLFACTOR

This example uses the FILLFACTOR option set to 100. A FILLFACTOR of 100 fills every page completely and is useful only when you know that no index values in the table will ever change.

CREATE NONCLUSTERED INDEX zip_ind

ON authors (zip)

WITH FILLFACTOR = 100

E.	IGNORE_DUP_KEY

This example creates a unique clustered index on the stores table. If a duplicate key is entered, the INSERT or UPDATE statement will be ignored.

CREATE UNIQUE CLUSTERED INDEX stor_id_ind

ON stores(stor_id)

WITH IGNORE_DUP_KEY

See Also

CREATE TABLE	sp_helpindex
DROP INDEX	sp_spaceused
INSERT	UPDATE
RECONFIGURE	UPDATE STATISTICS
SET


CREATE PROCEDURE Statement

Creates a stored procedure (a precompiled collection of SQL statements) that can take and/or return user-supplied parameters. Stored procedures help to increase performance and consistency when performing repetitive tasks because stored procedures are compiled the first time they are executed. When executed again, subsequent run time is much shorter than for the equivalent set of stand-alone statements. 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).

Syntax

CREATE PROCedure [owner.]procedure_name[;number]
[(parameter1 [, parameter2]...[parameter255])]
[{FOR REPLICATION} | {WITH RECOMPILE}
[{[WITH] | [,]} ENCRYPTION]]
AS sql_statements

where

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.

You can create local or global temporary procedures by preceding the procedure_name with a single pound sign (#table_name) for local temporary procedures and a double pound sign (##table_name) for global temporary procedures. The complete name, including # or ##, cannot exceed 20 characters. For more information, see "Temporary Stored Procedures," later in this topic.

Stored procedures can also be created for auto execution. Auto execution stored procedures are run automatically when SQL Server starts. For more information, see "Auto Execution Stored Procedures," later in this topic.

;number

Is an optional integer used to group procedures of the same name so that they can be dropped together with a single DROP PROCEDURE statement. When grouping is used with a procedure whose name was created using quoted identifiers, the number should not be included as part of the identifier; use double quotation marks only around the procedure_name. Procedures used in the same application are often grouped this way. For example, the procedures used with the application orders might be named orderproc;1, orderproc;2, and so on. The statement DROP PROCEDURE orderproc drops the entire group. Once procedures have been grouped, individual procedures within the group cannot be dropped.

parameter =

@parameter_name datatype [= default] [OUTPUT]

parameter_name

Specifies a parameter in the procedure. One or more parameters can optionally 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 255 parameters.

The first character of a parameter name must be the "at" symbol (@) and 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 the EXECUTE statement.

datatype

Specifies the datatype of the parameter. All datatypes except image are supported. For a list of SQL Server − supplied datatypes and their syntax, see the Datatypes topic.

default

Specifies a default value for the parameter. If a default is defined, a user can execute the procedure without specifying a value for that parameter. The default must be a constant. It can include wildcard characters (%, _, [], and [^]) if the procedure uses the parameter with the LIKE keyword. The default can be NULL. The procedure definition can specify that some action be taken if the parameter value is NULL.

OUTPUT

Indicates that the parameter is a return parameter. The value of this option can be returned to the EXECUTE statement that called the procedure. Use return parameters to return information to the calling procedure. Text parameters cannot be used as OUTPUT parameters.

FOR REPLICATION

Is mutually exclusive of the WITH RECOMPILE option. Stored procedures created for replication cannot be executed on the subscribing server. FOR REPLICATION should be used when creating a stored procedure that will be executed only by replication.

RECOMPILE

Indicates that SQL Server does not cache a plan for this procedure and the procedure is recompiled each time it is executed. Use this optional clause when you expect that the parameters you supply to the procedure won't be typical (that is, they won't result in the same optimal plan each time the procedure is executed). This can be beneficial when using wildcards in passing parameters because the distribution may be drastically different depending on the number of matches with the wildcard pattern.

Note  If any constraints are added or altered, any stored procedures that reference the table will be automatically recompiled.

ENCRYPTION

Encrypts the syscomments table entry that contains the text of the CREATE PROCEDURE statement.

Important  When a database is upgraded, syscomments entries are required in order to re-create procedures. Use encryption only when absolutely necessary; never delete entries from syscomments.

AS sql_statements

Specifies the actions the procedure is to take. Any number and type of SQL statements can be included in the procedure; however, there are some general limitations. For more information, see "sql_statement Limitations," later in this topic.

Remarks

When defining a stored procedure, you can create a stored procedure only in the current database (except for temporary procedures, which are always created in tempdb), and the CREATE PROCEDURE statement cannot be combined with other SQL statements in a single batch.

Stored procedures can use nesting, when one stored procedure calls 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 of 16 levels of nesting causes the whole calling procedure chain to fail. The current nesting level is stored in the @@NESTLEVEL global variable.

The maximum amount of text in a stored procedure is 65,025 characters. This limit is imposed because the text is stored in the syscomments system tables, where each procedure can occupy 255 rows of 255 bytes each (255 * 255 = 65,025).

To estimate the size of a compiled stored procedure, use DBCC MEMUSAGE. For details, see the DBCC statement.


Executing Stored Procedures

When a CREATE PROCEDURE statement is successfully executed, the procedure's name is stored in the sysobjects system table, its normalized plan in sysprocedures, and the text of the CREATE PROCEDURE statement in syscomments. When executed for the first time, the procedure is compiled to determine an optimal access plan to retrieve the data.

A stored procedure can be run by issuing the EXECUTE statement along with the procedure's name and any parameters. Parameters supplied in the format of @@parameter = value can be supplied in any order; however, if you supply one parameter in the form @@parameter = value, you must supply all subsequent parameters this way. If you do not supply parameters in the form @@parameter = value, you must supply them in the order given in the CREATE PROCEDURE statement. Although you can omit parameters for which defaults have been supplied, you cannot skip any — that is, if a procedure has five parameters, you can omit both the fourth and the fifth parameters, but you cannot skip the fourth and still include the fifth.

If a procedure is the first statement in a batch, you can give its name without using the EXECUTE keyword. When a procedure is executed successfully, the global variable @@ERROR is set to 0.


Referencing Objects

Objects referenced within a stored procedure must already exist. If objects are created within the stored procedure, you can reference them only after they've been created. The same holds true for temporary objects. A stored procedure can reference a temporary object only if the temporary object exists at the time the procedure is created or if the procedure itself creates the temporary object. A temporary object created in a procedure is dropped when the procedure exits.

If tables are created within a stored procedure, the column nullability decision is determined when the procedure is created. If column nullability is not explicitly defined, the nullability for each column will be defined based on the rules discussed in the CREATE TABLE topic and set based on the default nullability of the session and the database. To avoid any potential nullability problems, make sure to always explicitly define the nullability for each column.

Within a stored procedure, you cannot create an object (including a temporary one), drop the object, and then create a new object with the same name.

If you execute a procedure that calls another procedure, the called procedure can access objects created by the calling procedure.


sql_statement Limitations

You can use a SET statement  inside a stored procedure. The SET option you choose remains in effect during the execution of the stored procedure and then reverts to its former setting.

Inside a stored procedure, object names used with certain statements (the utility statements) must be qualified with the object owner's name if other users are to use the stored procedure. The utility statements are:

•	ALTER TABLE/CREATE TABLE

•	DROP TABLE/TRUNCATE TABLE

•	CREATE INDEX/DROP INDEX

•	UPDATE STATISTICS

•	DBCC

If you use SELECT * in a CREATE PROCEDURE statement, the procedure (even with the WITH RECOMPILE option to EXECUTE) does not recognize any new columns you might have added to the table after the procedure was created. To include new columns, you must drop the procedure and then re-create it.


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 table. Normally, this is when the session that created the procedure ends.

Temporary procedures named with # and ## can be created by any user. Once 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 explicitly revoked. Explicitly creating a temporary procedure in tempdb (naming without a pound 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 tables.


Auto Execution Stored Procedures

It is now possible to have one or more stored procedures execute automatically when SQL Server starts. The stored procedures must be created by the system administrator (SA) and will execute under the SA account 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 need to execute multiple procedures at startup, but don't need to execute them in parallel, you can make one procedure the startup procedure and have that procedure call the other procedures. This will use 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 the Trace Flags topic or the Utilities and Executables topic.

To create a startup stored procedure, you must be logged in as system administrator and create the stored procedure in the master database.

To make an existing stored procedure a startup procedure, type:

sp_makestartup procedure_name

To stop a procedure from executing at startup, type:

sp_unmakestartup procedure_name

To view a list of all procedures that will execute at startup, type:

sp_helpstartup

For more information, see the specific stored procedures within the System Stored Procedures topic.


User-defined System Procedures
User-defined System Stored Procedures

During installation, numerous system stored procedures are provided for convenience as shortcuts to retrieve or manipulate information stored in the system tables. Most SQL Server database administration tasks are accomplished with these predefined system procedures; however, you can also create user-defined system stored procedures. By default, each frequently used system stored procedure name begins with the sp_ prefix. To create a user-defined system stored procedure, use sp_ for the beginning of the procedure_name. Once created, this procedure will have the following characteristics:

•	It can be executed in any database.

•	When executed, a stored procedure is typically found within the current database. If the procedure name begins with sp_ and is not found in the current database, SQL Server will look in the master database. Tables referenced within a stored procedure named with sp_ that are not resolved within the current database will be looked up in the master database.

•	Objects referenced within a stored procedure are resolved when the procedure is executed, not when it is created.


Getting Information About Stored Procedures

To display the text used to create the procedure, execute the sp_helptext system stored procedure (in the database where the procedure exists) with the procedure name as the parameter.

Note  Procedures created with the ENCRYPTION option cannot be viewed with the sp_helptext system stored procedure.

For a report on the objects referenced by a procedure, use the sp_depends system stored procedure.

To rename a procedure, use the sp_rename system stored procedure.

Permission

CREATE PROCEDURE permission defaults to the database owner, who can transfer it to other users. Permission to execute a stored procedure is given to the procedure owner, who can grant execution permission on it to other database users.

Examples

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 have any parameters.

CREATE PROCEDURE au_info_all

AS

SELECT au_lname, au_fname, title, pub_name

FROM authors a, titles t, publishers p, titleauthor ta

WHERE a.au_id = ta.au_id

AND t.title_id = ta.title_id

AND t.pub_id = p.pub_id

The au_info_all stored procedure can be executed in the following ways:

EXECUTE au_info_all

EXEC au_info_all

Or, if this procedure is the first statement within the batch:

au_info_all

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

CREATE PROCEDURE au_info

@@lastname varchar(40),

@@firstname varchar(20)

AS

SELECT au_lname, au_fname, title, pub_name

FROM authors, titles, publishers, titleauthor

WHERE au_fname = @@firstname

AND au_lname = @@lastname

AND authors.au_id = titleauthor.au_id

AND titles.title_id = titleauthor.title_id

AND titles.pub_id = publishers.pub_id

The au_info stored procedure can be executed in the following ways:

EXECUTE au_info 'Dull', 'Ann'

EXECUTE au_info @@lastname = 'Dull', @@firstname = 'Ann'

EXECUTE au_info @@firstname = 'Ann', @@lastname = 'Dull'

EXEC au_info 'Dull', 'Ann'

EXEC au_info @@lastname = 'Dull', @@firstname = 'Ann'

EXEC au_info @@firstname = 'Ann', @@lastname = 'Dull'

Or, if this procedure is the first statement within the batch:

au_info 'Dull', 'Ann'

au_info @@lastname = 'Dull', @@firstname = 'Ann'

au_info @@firstname = 'Ann', @@lastname = 'Dull'

C.	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 defaults.

CREATE PROCEDURE au_info2

@@lastname varchar(30) = 'D%',

@@firstname varchar(18) = '%'

AS

SELECT au_lname, au_fname, title, pub_name

FROM authors a, titles t, publishers p, titleauthor ta

WHERE au_fname LIKE @@firstname

AND au_lname LIKE @@lastname

AND a.au_id = ta.au_id

AND t.title_id = ta.title_id

AND t.pub_id = p.pub_id

The au_info2 stored procedure can be executed in many combinations. For simplicity, only a few combinations are shown.

EXECUTE au_info2

EXECUTE au_info2 'Wh%'

EXECUTE au_info2 @@firstname = 'A%'

EXECUTE au_info2 '[CK]ars[OE]n'

EXECUTE au_info2 'Hunter', 'Sheryl'

EXECUTE au_info2 'H%', 'S%'

D.	Use OUTPUT Parameters

OUTPUT parameters are used to allow an external procedure, a batch, or SQL statements access to 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:

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

Next, use the OUTPUT parameter with control-of-flow extensions. Note that the OUTPUT variable must be defined during the table creation as well as during use of the variable. When using a variable, the parameter name and variable name do not need to match; however, the datatype 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(convert(varchar(20), @@totalcost))

go

Title Name
------------------------------------------------------------
The Busy Executive's Database Guide
The Gourmet Microwave
The Psychology of Computer Cooking

All of these titles can be purchased for less than $200.

E.	WITH RECOMPILE

The WITH RECOMPILE clause is helpful when the parameters you supply to the procedure won't be typical.

CREATE PROCEDURE titles_by_author @@lname_pattern varchar(30) = '%'
WITH RECOMPILE
AS
SELECT 'Authors full name' = RTRIM(au_fname) + ' ' + RTRIM(au_lname),
Title = title
FROM authors a, titles t, titleauthor ta
WHERE au_lname LIKE @@lname_pattern
AND a.au_id = ta.au_id
AND ta.title_id = t.title_id

F.	WITH ENCRYPTION

The WITH ENCRYPTION clause is helpful to "hide" the text of a stored procedure from users. This example creates an encrypted procedure and the sp_helptext system stored procedure and then attempts to select directly from the syscomments table.

CREATE PROCEDURE encrypt_this
WITH ENCRYPTION
AS
SELECT * FROM authors
go

sp_helptext encrypt_this

go

The object's comments have been encrypted.

SELECT c.id, c.text

FROM syscomments c, sysobjects o

WHERE c.id = o.id and o.name = 'encrypt_this'

go

id          text
----------- --------------------------------------------
1088006907  LýsåvùO_Oéf:3j"ØË"/WÉm¢?CùŸ'0_%Û'	™²Î_Ú?­

G.	Define a Stored Procedure for Auto Execution

Stored procedures used for auto execution are executed after recovery. Remember that all auto-execution procedures will be added to the startup of the system.

sp_makestartup procedurename

H.	Create a User-defined System Stored Procedure

Once defined, user-defined system stored procedures can be used from within any database; however, they must be created by the system administrator in the master database.

USE master

go

CREATE PROCEDURE sp_showindexes

@@table varchar(30) = 'sys%'

AS

SELECT TABLE_NAME = o.name,

INDEX_NAME = i.name,

INDEX_ID = indid

FROM sysindexes i, sysobjects o

WHERE o.name LIKE @@table

AND o.id = i.id

go

USE pubs

go

sp_showindexes 'emp%'

go

TABLE_NAME                     INDEX_NAME                     INDEX_ID
------------------------------ ------------------------------ --------
employee                       employee_ind                   1
employee                       PK_emp_id                      2

(2 row(s) affected)

See Also

Batches	sp_makestartup
Comments	sp_helpstartup
Control-of-Flow Language	sp_helptext
DECLARE	sp_recompile
DROP PROCEDURE	sp_rename
EXECUTE	sp_unmakestartup
GRANT	System Stored Procedures
SELECT	System Tables-Database Catalog
sp_addextendedproc	Variables
sp_depends	Wildcard Characters


CREATE RULE Statement

Creates an object called a rule, which, when bound to a column or a user-defined datatype, specifies the acceptable values that can be inserted into that column. An alternative method to creating rules is to create table- and column-level CHECK constraints as described with the CREATE TABLE. Using constraints is the preferred method of restricting column data because multiple constraints can be defined on a column or multiple columns. A column or user-defined datatype can have only one rule bound to it. However, a column can have a rule and one or more CHECK constraints associated with it. When this is true, all restrictions are evaluated.

Syntax

CREATE RULE [owner.]rule_name
AS condition_expression

where

rule_name

Is the name of the new rule. Rule names must conform to the rules for identifiers.

AS condition_expression

Specifies the conditions that define the rule. A rule can be any expression that is valid in a WHERE clause, and it can include such elements as arithmetic operators, relational operators, IN, LIKE, BETWEEN, and so on. It cannot reference columns or other database objects. Built-in functions that do not reference database objects can be included.

A condition_expression includes one variable. The at symbol (@) precedes each local variable. The expression refers to the value that is entered with the UPDATE or INSERT statement. You can use any name or symbol to represent the value when you write the rule, but the first character must be @.

Remarks

CREATE RULE statements cannot be combined with other 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 datatypes. You can create a rule only in the current database. After creating a rule, execute the sp_bindrule System Stored Procedure to bind the rule to a column or to a user-defined datatype.

The rule must be compatible with the datatype of the column. You cannot bind a rule 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, you cannot use "@value like A%" as a rule for a numeric column. If the rule is not compatible with the column to which you've bound it, SQL Server returns an error message when you try to insert a value (not when you bind the rule).

A rule bound to a user-defined datatype is activated only when you attempt to insert a value into or to update a database column of the user-defined datatype. Because rules do not test variables, do not assign a value to a user-defined datatype variable that would be rejected by a rule bound to a column of the same datatype.

To get a report on a rule, use the sp_help System Stored Procedure. To display the text of a rule, execute the sp_helptext System Stored Procedure with the rule name as the parameter. To rename a rule, use the sp_rename System Stored Procedure.

You must drop a rule (using the DROP RULE) before you can create a new one with the same name, and you must unbind a rule (using the sp_unbindrule System Stored Procedure) before you drop it. Use the sp_unbindrule System Stored Procedure to unbind a rule from a column.

You can bind a new rule to a column or datatype 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 datatypes. Binding a rule to a column replaces a rule already bound to the user-defined datatype of that column. But binding a rule to a datatype does not replace a rule bound to a column of that user-defined datatype. The following table shows the precedence in effect when binding rules to columns and to user-defined datatypes where rules already exist:

	Old rule bound to
New rule bound to	User-defined datatype	Column
User-defined datatype	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.

Permission

CREATE RULE permission defaults to the database owner, who can transfer it 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

@value LIKE '_ _-%[0-9]'

See Also

Batch Queries	sp_help System Stored Procedure
CREATE DEFAULT	sp_helptext System Stored Procedure
DROP DEFAULT	sp_rename System Stored Procedure
DROP RULE	sp_unbindrule System Stored Procedure
sp_bindrule System Stored Procedure	Wildcard characters


CREATE TABLE Statement

For more information about how SQL Server 6.5 affects existing database systems and for updated SQL Server 6.5 syntax, see CREATE TABLE Statement.

Creates a new table.

Syntax

CREATE TABLE [database.[owner].]table_name
(
{col_name column_properties [constraint [constraint [...constraint]]]
| [[,] constraint]}
[[,] {next_col_name | next_constraint}...]
)
[ON segment_name]

where

table_name

Is the name of the new table. Table names must conform to the rules for identifiers and must be unique within the database and for its owner.

You can create local and global temporary tables. Local temporary tables are visible in the current session only; global temporary tables are visible to all sessions. Temporary tables names are stored in the tempdb..sysobjects table by their names and a system-supplied numeric suffix. Local temporary tables are automatically dropped at the end of the current session or, for global temporary tables, at the end of the last session using the table. Normally, this is when the session that created the table ends.

Signify temporary tables by preceding the table_name with a single pound sign (#table_name) for local temporary tables and a double pound sign (##table_name) for global temporary tables. For local temporary tables, the complete name, including #, cannot exceed 20 characters.

When creating local or global temporary tables, the CREATE TABLE syntax supports constraint definitions; however, FOREIGN KEY constraints are not enforced on temporary tables.

If you are listed in that database's sysusers table and have CREATE TABLE permission in that database, you can create a table in a database different from the current one by fully qualifying the table_name.

col_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_properties =

datatype [NULL | NOT NULL | IDENTITY[(seed, increment)]]

datatype

Specifies the datatype of the column. System or user-defined datatypes are acceptable.

IDENTITY[(seed, increment)]

Generates incremental values for new rows based on the seed and increment parameters. If used, the seed value will be assigned to the first row in the table and each subsequent row will receive the next identity value, equal to the last identity plus the increment value. If neither argument is given, both will default to 1.

The IDENTITY property can be assigned to a tinyint, smallint, int, decimal(p,0), or numeric(p,0) column that does not allow null values. Only one column per table can be defined as an identity column. Defaults and DEFAULT constraints cannot be bound to an identity column, and an identity value cannot be changed. For more information, see "DENTITY Property, later in this topic.

constraint =

Can include a table- or column-level constraint(s) where there are at most, one PRIMARY KEY per table, no more than 249 UNIQUE constraints, no more than 31 FOREIGN KEY constraints per table (each of which can reference at most 16 columns), one DEFAULT constraint per column, and any number of CHECK constraints. All can be entered within the same CREATE TABLE statement.

For a PRIMARY KEY constraint:

[CONSTRAINT constraint_name]
PRIMARY KEY [CLUSTERED | NONCLUSTERED]
(col_name [, col_name2 [..., col_name16]])
[ON segment_name]

For a UNIQUE constraint:

[CONSTRAINT constraint_name]
UNIQUE [CLUSTERED | NONCLUSTERED]
(col_name [, col_name2 [..., col_name16]])
[ON segment_name]

For a FOREIGN KEY constraint:

[CONSTRAINT constraint_name]
[FOREIGN KEY (col_name [, col_name2 [..., col_name16]])]
REFERENCES [owner.]ref_table [(ref_col [, ref_col2
[..., ref_col16]])]

For a DEFAULT constraint:

[CONSTRAINT constraint_name]
DEFAULT {constant_expression | niladic-function | NULL}
[FOR col_name]

For a CHECK constraint(s):

[CONSTRAINT constraint_name]
CHECK [NOT FOR REPLICATION] (expression)

CONSTRAINT constraint_name

Names the given constraint within the database. Constraint names must follow the rules for identifiers, except that the name cannot begin with a pound sign (#). If constraint_name is not supplied, a system-generated name is assigned to the constraint. The constraint_name will appear in any error message about constraint violations. If constraint requirements change, the constraint must be dropped and re-created using the ALTER TABLE statement.

PRIMARY KEY [CLUSTERED | NONCLUSTERED]

Enforces entity integrity for a given column or columns. 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 will have their nullability set to NOT NULL.

To enforce uniqueness of a primary key, SQL Server automatically creates a unique index on that column or columns. This unique index can be dropped only by dropping the associated table or the PRIMARY KEY constraint.

If no index type is specified, a CLUSTERED index is created by default. If NONCLUSTERED is specified or if CLUSTERED is specified for a different constraint in the same statement block, a NONCLUSTERED index is created.

Only one PRIMARY KEY constraint can be specified for a given table. However, "alternate" or "candidate" keys can be effectively created with a UNIQUE constraint.

UNIQUE [CLUSTERED | NONCLUSTERED]

Provides entity integrity for a given column or columns. Although columns participating in UNIQUE constraints can allow null values, it is not recommended that you use null values. If null values are necessary, the complete key (a single column or multiple columns for a composite index) cannot be NULL for more than one row. Multiple UNIQUE constraints can be defined on any given table. SQL Server automatically creates a unique index on this column or columns. Indexes created for use in UNIQUE constraint enforcement can be dropped only by dropping the associated table or constraint. If no index type is specified, a NONCLUSTERED index is created by default.

[FOREIGN KEY (col_name [, col_name2 [..., col_name16]])]
REFERENCES [owner.]ref_table [(ref_col [, ref_col2 [..., ref_col16]])]

Provide single- or multicolumn referential integrity. When defined, the number of columns and datatypes of each column specified in the FOREIGN KEY clause must identically match the REFERENCES clause. A non-null value entered in this column(s) must exist in the table and column(s) defined in the REFERENCES clause, and the referenced table's columns should have a PRIMARY KEY or UNIQUE constraint defined on them. For column-level constraints, using the FOREIGN KEY and col_name identifiers are optional.

Important  REFERENCE constraints can reference only tables within the same database; this can include the same table on which the reference is defined (self-referenced tables). If you want cross-database referential integrity or custom messaging, implement these through triggers.

A table can have a maximum of 31 FOREIGN KEY references. This limit is an absolute upper limit, but the maximum may be lower depending on the number of work tables the server has to create to enforce the constraint, and the limit varies by the type of query being executed. FOREIGN KEY constraints are not enforced for temporary tables.

FOREIGN KEY constraints, unlike PRIMARY KEY constraints, do not create an index. To improve performance for data retrieval operations, use the CREATE INDEX statement to create an index on a foreign key column. This will allow for quicker execution times when a referenced key is modified.

For a FOREIGN KEY to be successfully created, the user must have SELECT or REFERENCES permission on the column or columns to which the FOREIGN KEY refers. For details, see the GRANT statement. When a specific reference column(s) is not provided, the primary key for the referenced table is used.

DEFAULT constant_expression | niladic-function | NULL

Specifies the value that will be provided for the column when a value is not explicitly supplied during an insert. A DEFAULT constraint can contain constant values, functions, built-in functions that do not take arguments (niladic-functions), or NULL. If used, a constant_expression must follow the same rules as defaults.

DEFAULT constraints can be created on columns of any datatype except columns that are the timestamp datatype or have the IDENTITY property. If a DEFAULT constraint is bound to a column defined with a user-defined datatype that has a default bound to it, the DEFAULT constraint is not allowed and the CREATE TABLE statement will fail. The default must be unbound from the user-defined datatype before that datatype can be used in a table definition with a DEFAULT constraint.

Niladic-functions allow a system-supplied value to be inserted when no value is specified. ANSI-standard niladic-functions include:

•	USER

•	CURRENT_USER

•	SESSION_USER

•	SYSTEM_USER

•	CURRENT_TIMESTAMP

In SQL Server 6.0, USER, CURRENT_USER, and SESSION_USER all default to the database username of the user performing the insert or update. SYSTEM_USER will provide the login ID, and CURRENT_TIMESTAMP will provide the same information as the GETDATE() function.

Benefits to using a DEFAULT constraint instead of a default (created with the CREATE DEFAULT statement) are that no explicit binding/unbinding is required and DEFAULT constraints are removed when the table is dropped.

When a DEFAULT is created as a table-level constraint, the column to which it applies is specified with FOR col_name.

CHECK (expression)

Enforces domain integrity by limiting the possible values that can be entered into a column or columns. The search condition must evaluate to a Boolean expression and cannot contain subqueries. CHECK constraints adhere to the same policies as rules; however, they are automatically bound to the columns on which they are defined and can reference another column(s). Multiple CHECK constraints can be defined for a table; however, only one can be defined per column per CREATE TABLE statement (although each column constraint can have multiple conditions). When a rule and one or more CHECK constraints exist for a column or columns, all restrictions are evaluated. If defined on multiple columns, CHECK constraints must be defined as table-level constraints.

NOT FOR REPLICATION

Prevents the specified CHECK constraint from being enforced for the distribution process used by replication; however, CHECK constraints will be enforced for all other users (including the system administrator). NOT FOR REPLICATION is used to protect horizontally partitioned tables that receive "source" data from a publishing server of data modifications to the replicated data. When replication is in effect, any modifications to the data that is replicated should be made on the publishing server (the main source of the data) and not on any of the subscribing servers (each of which receives exact copies of the publishing server's data).

The NOT FOR REPLICATION CHECK constraint will be 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 will be checked; if they fall within the replicated range, they will be rejected.

ON segment_name

If specified with a PRIMARY KEY or UNIQUE constraint, creates only the index on the named segment. If that key is defined with a clustered index, the entire table will be placed on the named segment. For more information, see the CREATE INDEX statement.

If not specified with a constraint, ON segment_name creates the table on the named segment.

Caution  If you create a table on a segment and then create a clustered index on that table without specifying a segment name, the entire table migrates to the default segment (unless the SORTED_DATA option is used).

When using ON segment_name, the logical device must already be assigned to the database by the CREATE DATABASE statement or the ALTER DATABASE statement, and the segment must have been previously created in the database with the sp_addsegment system stored procedure. To see a list of segment names available in your database, use the sp_helpsegment system stored procedure.

Important  Constraints are not enforced in the same batch as CREATE TABLE. If you want constraints to take effect for all new rows, do not insert, delete, or update data in the batch in which CREATE TABLE is executed.

When a constraint is violated, the command is terminated. However, the transaction (if the statement is part of an explicit transaction) will continue to be processed. If desired, use the ROLLBACK TRANSACTION statement with the transaction definition by checking the @@error global variable.

FOREIGN KEY constraints are not enforced on temporary tables.

Remarks

SQL Server can have as many as 2 billion tables per database and 250 columns per table. The number of rows and total size of the table are limited only by the available storage. The maximum size of a database is 1 terabyte (TB). A table can be as large as 1 TB minus the size of the database catalog and any other objects. The maximum number of bytes per row is 1962. If you create tables with varchar or varbinary columns whose total defined width exceeds 1962 bytes, the table is created but a warning message appears. Trying to insert more than 1962 bytes into such a row or to update a row so that its total row size exceeds 1962, produces an error message and the statement fails. For details on calculating row size, see the Microsoft SQL Server Administrator's Companion.

The table is created in the currently open database unless a different database is explicitly specified in the CREATE TABLE statement with the optional database name. (Cross-database creation of tables and indexes is allowed as long as the creator is listed in the sysusers table of the other database and has CREATE TABLE permission in that database. However, cross-database creation of views, rules, defaults, stored procedures, and triggers is not allowed.)

User-defined datatypes are defined in terms of system datatypes. User-defined datatypes permit frequently used type information to be accessed by a name you choose with a specified rule, default, and display format attached to it. User-defined datatypes are created with the sp_addtype system stored procedure before they can be used in a table definition.

The NULL/NOT NULL assignment for a user-defined datatype can be overridden during the CREATE TABLE statement. However, the length specification cannot be changed; you cannot specify a length for a user-defined datatype in a CREATE TABLE statement.

For a report on a table and its columns, use the sp_help or sp_helpconstraint system stored procedure. To rename a table, use the sp_rename system stored procedure. For a report on the views and stored procedures that depend on a table, use the sp_depends system stored procedure.

Space is allocated to tables and indexes in increments of one extent, (eight pages) at a time. An extent is allocated when the table or index is created, and another extent is allocated each time the previous extent becomes full. For a report on the amount of space allocated and used by a table, execute the sp_spaceused system stored procedure.


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 0 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 creating or altering a table with the CREATE TABLE or ALTER TABLE statements, database and session settings will influence and possibly override the nullability of the datatype used in a column definition. It is recommended that you always explicitly define a column as NULL or NOT NULL or, if using a user-defined datatype, allow the column to use the datatype's default nullability.

When not explicitly specified, column nullability follows these rules:

1.	If the column is defined with a user-defined datatype:

•	SQL Server will use the nullability specified when the datatype was created. Use the sp_help system stored procedure to get the datatype's default nullability.

Note  When creating a user-defined datatype with the sp_addtype system stored procedure, the nullability of that datatype will default to NOT NULL if it is not explicitly defined. It is recommended that you should always explicitly define the nullability of a user-defined datatype.

2.	If the column is defined with a system-supplied datatype:

•	If the system-supplied datatype has only one option, it will take precedence. Currently, the bit and timestamp datatypes can be defined only as NOT NULL.

•	If any session settings are ON (turned on with the SET), then:

•	If ANSI_NULL_DFLT_ON is ON, NULL will be assigned.

•	If ANSI_NULL_DFLT_OFF is ON, NOT NULL will be assigned.

•	If any database settings are configured (changed with the sp_dboption System Stored Procedure), then:

•	If 'ANSI null default' is TRUE, NULL will be assigned.

•	If 'ANSI null default' is FALSE, NOT NULL will be assigned.

3.	When not explicitly defined (neither of the ANSI_NULL_DFLT options are set), the session has not been changed and the database is set to the default ('ANSI null default' is FALSE), then the SQL Server default of NOT NULL will be assigned.


Temporary Tables

SQL Server supports two types of temporary tables: local and global. A local temporary table is visible only to the connection that created it. A global temporary table is available to all connections. Local temporary tables are automatically dropped at the end of the current session. Global temporary tables are dropped at the end of the last session using the table (normally, this is when the session that created the table ends).

Temporary tables named with # and ## can be created by any user. Once the temporary table is created, the owner of the local table is the only one who can access that table. Permissions cannot be granted on local temporary tables. Once a global temporary table is created, all users can access it; permissions cannot be explicitly revoked. Explicitly creating a temporary table in tempdb (named without a pound sign) can be performed only by those with explicit CREATE TABLE permission in the tempdb database. Permission can be granted to and revoked from these tables.

Because temporary tables are not generally maintained for long (they are automatically dropped by the system), because referenced objects could be dropped (drop dependencies), and because FOREIGN KEY constraints are not enforced, a simplified CREATE TABLE syntax can be used:

CREATE TABLE #[#]table_name
(column_definition
[, next_column_definition]...)

Note  In addition to naming a temporary table with # or ##, temporary tables can be created without the pound sign by qualifying the table name with tempdb as the database. If created in tempdb, the table will exist until SQL Server is restarted.

Stored procedures can reference temporary tables that are created during the current session. If a temporary table is created by a stored procedure or created within an EXECUTE statement, it is deleted when the procedure or EXECUTE is completed. Within a stored procedure, you cannot create a temporary table, drop it, and then create a new temporary table that has the same name.

If user-defined datatypes are used within a temporary table's definition, the user-defined datatypes must first be added to tempdb. There are two ways to add a user-defined datatype (or any other object) to the tempdb database:

•	To add an object for the current session only, execute the sp_addtype system stored procedure while using tempdb.

•	To permanently add a user-defined datatype, execute the sp_addtype system stored procedure in the model database and then restart SQL Server so that model is copied to tempdb.

If you execute system stored procedures from within the tempdb database, system stored procedures such as the sp_help system stored procedure will work only on temporary tables.


IDENTITY Property

Columns that have the IDENTITY property contain system-generated values that uniquely identify each row within a table. You can use this feature to generate sequential numbers (for example, employee identification numbers). When inserting values into a table with an identity column, SQL Server automatically generates the next identifier based on the last used identity value (incremented by adding rows) and the increment value specified during column creation.

There is no need to remember which column has the IDENTITY property — simply use the IDENTITYCOL keyword instead. When referencing data in a table, use the keyword IDENTITYCOL in place of the identity column name. It can be qualified with a table name if necessary. The IDENTITYCOL keyword can be used in SELECT, INSERT, UPDATE, and DELETE statements to reference an identity column.

Two system functions return identity information for an object containing an identity column. IDENT_SEED returns the seed value specified during creation of an identity column. IDENT_INCR returns the increment value specified during creation of an identity column.

Manipulating Data in Identity Columns

Data inserted into the table should not include a value for an identity column in the INSERT statement; instead, use the DEFAULT VALUES option (available with the INSERT statement).

By default, data cannot be inserted directly into an identity column; however, if a row was accidentally deleted, an identity value can be re-created and reconstructed. To get the last identity value, use the @@IDENTITY global variable. This variable is accurate after an insert into a table with an identity column; however, this value is reset after an insert into a table without an identity column occurs. To allow an insert with a specific identity value, see the SET statement for the IDENTITY_INSERT option.

Important  When explicitly inserting values into the identity column, SQL Server does not validate uniqueness or the possibility of a gap based on the explicitly entered value. To ensure that this value is unique, use a UNIQUE or PRIMARY KEY constraint, or create a unique index on the identity column.

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 the IDENTITY_INSERT option ON. If reusing a removed identity value, use the following sample code to check for the next available identity value. Replace tablename, column_type, and max(column_type) − 1 with your table name, identity column datatype, and numeric value of the maximum allowable value (for that datatype) −1.

SET IDENTITY_INSERT tablename ON
go
DECLARE @@nextidentval column_type
SELECT @@nextidentval = MIN(IDENTITYCOL)+ IDENT_INCR(tablename)
FROM tablename t1
WHERE IDENTITYCOL BETWEEN IDENT_SEED(tablename) AND max(column_type) - 1
AND NOT EXISTS (SELECT * FROM tablename t2
WHERE t2.IDENTITYCOL = t1.IDENTITYCOL + IDENT_INCR(tablename))
go
SET IDENTITY_INSERT tablename OFF

To check that no gaps exist, this example uses a smallint identity column on a table named images, where the identity column was defined with a seed of 6 and an increment value of 8:

SET IDENTITY_INSERT images ON
go
DECLARE @@nextidentval smallint
SELECT @@nextidentval = MIN(IDENTITYCOL)+ IDENT_INCR(images)
FROM images t1
WHERE IDENTITYCOL BETWEEN IDENT_SEED(images) AND 32766
AND NOT EXISTS (SELECT * FROM images t2
WHERE t2.IDENTITYCOL = t1.IDENTITYCOL + IDENT_INCR(images))
go

Using the IDENTITY Property with SELECT [INTO] or a View

Ordinarily, selecting an existing identity column into a new table or view, the new column inherits the identity property. If one of the following conditions is true, the new column does not inherit the identity property:

•	The SELECT statement contains a union, join, group by, or aggregate function

•	The identity column is selected more than once

•	The identity column is part of an expression

If one of these conditions is true, the column is created NOT NULL instead of inheriting the identity property. Because this column does not have the identity property, a column value must be explicitly specified when inserting a row into the new table.

If none of these conditions is true, the new table will inherit the identity column. All rules and restrictions, for the identity columns apply to the new table.

Permission

CREATE TABLE permission defaults to the database owner, who can transfer it to other users. Any user can create temporary tables.

Examples

A.	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 employee table's emp_id column. This column is based on a user-defined datatype.

emp_id	empid

CONSTRAINT PK_emp_id PRIMARY KEY NONCLUSTERED

B.	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.	UNIQUE Constraints

UNIQUE constraints are used to enforce uniqueness on nonprimary key columns. A PRIMARY KEY constraint column automatically includes a restriction for uniqueness; however, a UNIQUE constraint differs in that it can allow null values. This example shows a column called pseudonym on the authors table. It enforces a restriction that for authors who use a pen name, the name 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.	DEFAULT Constraints

Defaults supply a value (with the INSERT and UPDATE statements) when no value is supplied. In the pubs database, many DEFAULT constraints are used to ensure that valid data or placeholders are entered.

On the jobs table, a character string default showing that a description (column job_desc) has not been defined is supplied 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 constraints 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.	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.	IDENTITY Property

This example shows an identity that begins at 1 and monotonically increases by 1 at a time. This is for the job_id column of the jobs table:

IDENTITY(1,1)

An IDENTITY column can also be used to increase a number by any number from a different starting point. This example shows an IDENTITY column that begins at 144 and monotonically increases by 12 at a time:

IDENTITY(144,12)

G.	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)

)

go

/* ************************* 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. */

)

go

/* ***************** 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')

)

go

See Also

ALTER TABLE	DROP TABLE
CREATE INDEX	sp_addtype
CREATE RULE	sp_depends
CREATE VIEW	sp_help
Datatypes	sp_helpconstraint
DROP INDEX	sp_rename
DROP RULE	sp_spaceused


CREATE TRIGGER Statement

Creates a trigger, a special kind of stored procedure that is executed automatically when a user attempts the specified data-modification statement on the specified table. Triggers are often used for enforcing business rules and data integrity. Referential integrity can be defined by using FOREIGN KEY constraints with the CREATE TABLE statement. If constraints exist on the "trigger table," they are checked prior to the trigger execution. If constraints are violated, the trigger is not run.

Triggers have been commonly used in earlier versions of SQL Server to enforce complex business rules and referential integrity (integrity rules about relationships between the primary and foreign keys of tables or views). SQL Server 6.0 provides declarative referential integrity through the CREATE TABLE statement. Triggers are useful to ensure appropriate actions when cascading deletions or updates need to occur.

In performance terms, trigger overhead is usually very low. The time involved in running a trigger is spent mostly in referencing other tables, which may be either in memory or on disk.

Syntax

CREATE TRIGGER [owner.]trigger_name
ON [owner.]table_name
FOR {INSERT, UPDATE, DELETE}
[WITH ENCRYPTION]
AS sql_statements

Or, using the IF UPDATE clause:

CREATE TRIGGER [owner.]trigger_name
ON [owner.]table_name
FOR {INSERT, UPDATE}
[WITH ENCRYPTION]
AS
IF UPDATE (column_name)
[{AND | OR} UPDATE (column_name)...] sql_statements

where

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.

table_name

Specifies the table on which the trigger will be executed; sometimes called the trigger table.

INSERT, UPDATE, DELETE

Are keywords that specify which data modification statements, when attempted against this table, will activate the trigger. Any combination (in any order) of these are allowed in the trigger definition.

ENCRYPTION

Encrypts the syscomments entries that contain the text of the CREATE TRIGGER statement.

Important  When a database is upgraded, syscomments entries are required in order to re-create triggers. Use encryption only when absolutely necessary; never delete entries from syscomments.

AS sql_statements

Specify trigger conditions and actions. Trigger conditions specify additional criteria that determine whether the attempted INSERT, DELETE, or UPDATE statements will cause the trigger action(s) to be carried out.

The trigger actions specified in the SQL statements go into effect when the user action (UPDATE, INSERT, or DELETE) is attempted. If multiple trigger actions are specified, they are grouped within a BEGIN...END block.

Triggers can include any number and kind of SQL statements but should not include the SELECT statement. A trigger is meant to check or change data based on a data modification statement; it should not return data to the user. The 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 like 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 would be changed by the user action. For details, see "Inserted and Deleted Tables," later in this topic.

The following SQL statements are not allowed in a trigger:

•	All CREATE statements (DATABASE, TABLE, INDEX, PROCEDURE, DEFAULT, RULE, TRIGGER, and VIEW)

•	All DROP statements

•	ALTER TABLE and ALTER DATABASE

•	TRUNCATE TABLE

•	GRANT and REVOKE

•	UPDATE STATISTICS

•	RECONFIGURE

•	LOAD DATABASE and LOAD TRANSACTION

•	All DISK statements

•	SELECT INTO (because it creates a table)

IF UPDATE

Tests for an INSERT or UPDATE action to a specified column. It is not used with DELETE. More than one column can be specified. Because you specify the table name in the ON clause, do not use the table name in front of the column name with IF UPDATE.

Remarks

In earlier releases of SQL Server, triggers were commonly used to enforce referential integrity (rules about the relationships between the primary and foreign keys of tables). SQL Server 6.0 provides declarative referential integrity (DRI) through the table creation statements (ALTER TABLE and CREATE TABLE); however, DRI does not provide cross-database referential integrity in this release.

When creating a trigger, it must be the first statement in the batch and can apply to only one table. You can create a trigger only in the current database; however, a trigger can reference objects outside the current database. If you use an owner name to qualify a trigger, qualify the table name the same way. A table can have a maximum of three different triggers — one each for INSERT, UPDATE, and DELETE. However, the same trigger action can be defined for more than one user action (for example, INSERT and UPDATE) in the same CREATE TRIGGER statement.

If a trigger is defined for an operation (INSERT, UPDATE, or DELETE) that already has a trigger association, the existing trigger is replaced. No warning message is given before the replacement occurs. When you drop a table, all triggers associated with it are also dropped.

Triggers can be nested 16 levels deep. 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 will be exceeded and the trigger will be canceled. If nested triggers are not desired, use the sp_configure System Stored Procedure to set the nested triggers option to 0 (off). The default configuration allows nested triggers.

A trigger does not call itself in response to a second update to the same table within the trigger. For example, if an update trigger on one column of a table results in an update to another column, the update trigger is activated only once.


Inserted and Deleted Tables

When an INSERT, UPDATE or DELETE statement is executed, rows are added to the trigger table and to the inserted or deleted table(s) at the same time. Deleted and inserted tables can be examined by the trigger to determine whether or how the trigger action(s) should be carried out. Deleted tables are used with DELETE and UPDATE; inserted tables are used with INSERT and UPDATE. Thus, the rows in the inserted table are always duplicates of one or more rows in the trigger table.

Triggers are often used to roll back that transaction if an error is detected.

A trigger is activated only once per command or once per single data modification statement (even if it affects multiple rows). A complex query containing a WHILE loop can repeat an UPDATE or INSERT many times, and the trigger is activated each time.

If a desired result (such as a summary value) depends on the number of rows affected by data modification, use the global variable @@ROWCOUNT to test for modification to multiple rows (an INSERT, DELETE, or UPDATE based on a SELECT statement) and take appropriate action. Any Transact-SQL statement that does not return rows (such as an IF statement) sets @@ROWCOUNT to 0, so be sure to test with @@ROWCOUNT at the beginning of a trigger.

An UPDATE or INSERT trigger can use the IF UPDATE statement. It tests whether the UPDATE or INSERT action changed a particular column. IF UPDATE (column_name) is true for an INSERT statement whenever the column is assigned a value in the select list or in the VALUES clause. IF UPDATE (column_name) is true for an UPDATE statement if the column is assigned a value in the SET clause. An explicit NULL or a default assigns a value to a column and thus activates the trigger. An implicit NULL, however, does not assign a value to a column and does not activate the trigger.


Trigger Limitations

It is recommended that a trigger not include SELECT statements that return results to the user, since special handling for these returned results would have to be written into every application in which modifications to the trigger table are allowed.

You cannot create a trigger on a view.

You can use the SET statement inside a trigger. With SET, the option you invoke remains in effect during the execution of the trigger and then reverts to its former setting when the trigger is completed.

A TRUNCATE TABLE statement is not caught by a DELETE trigger. Although a TRUNCATE TABLE statement is, in effect, like a DELETE without a WHERE clause (it removes all rows), it is not logged and thus cannot execute a trigger. Since 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.


Getting Information About Triggers

The text of the CREATE TRIGGER statement is stored in the syscomments table. To see this text, execute the sp_helptext System Stored Procedure.

Note  Triggers created with the ENCRYPTION option cannot be viewed with the sp_helptext system stored procedure.

The normalized tree for the trigger is stored in the sysprocedures table.

For a report on a trigger, execute the sp_help System Stored Procedure. For a report on the tables and views that are referenced by a trigger, use the sp_depends System Stored Procedure. To rename a trigger, use the sp_rename System Stored Procedure.

Permission

CREATE TRIGGER permission defaults to the table owner and is not transferable.


CREATE TRIGGER Examples
Examples

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. This trigger is helpful because it reminds anyone who updates or inserts rows into this table that they should also notify the distributors.

CREATE TRIGGER reminder

ON titles

FOR INSERT, UPDATE

AS RAISERROR (50009, 16, 10))

Message 50009 is a user-defined message in sysmessages. For details on creating user-defined messages, see the sp_addmessage system stored procedure.

B.	Trigger with a Reminder E-mail Message

This example sends an e-mail message to a specified person (MaryM) when the titles table changes. Sending e-mail is helpful when only a single person (or group) needs information about a table change.

CREATE TRIGGER reminder

ON titles

FOR INSERT, UPDATE, DELETE

AS xp_sendmail 'MaryM', 'Don't forget to print a report for the
distributors.'

C.	Trigger Business Rule Between the employee and jobs Tables

Because CHECK constraints can only reference 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.

Employee job levels (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 or UPDATE only.

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

go

See Also

CREATE PROCEDURE	sp_help
DROP TRIGGER	sp_helptext
TRANSACTIONS	sp_rename
sp_depends	sp_spaceused


CREATE VIEW Statement

Creates a virtual table that represents an alternative way of looking at the data in one or more tables. You can use views as security mechanisms by granting permission on a view but not on underlying tables.

Syntax

CREATE VIEW [owner.]view_name
[(column_name [, column_name]...)]
[WITH ENCRYPTION]
AS select_statement [WITH CHECK OPTION]

where

view_name

Is the name of the view. View names must follow the rules for identifiers.

column_name

Is the name to be used for a column in a view. Naming a column in CREATE VIEW is always legal but only necessary when a column is derived from an arithmetic expression, a function, or a constant, when two or more columns could otherwise have the same name (usually because of a join), or when you want to give a column in a view a name different from the column from which it is derived. Column names can also be assigned in the SELECT statement.

If column_name is not specified, the view columns acquire the same names as the columns in the SELECT statement.

ENCRYPTION

Encrypts the syscomments entries that contain the text of the CREATE VIEW statement.

Important  When a database is upgraded, syscomments entries are required in order to re-create views. Use encryption only when absolutely necessary; never delete entries from syscomments.

AS select_statement

Is the SELECT statement that defines the view. It can use more than one table and other views. You must have permission to select from the objects referenced in the SELECT clause of a view you are creating.

A view need not be a simple subset of the rows and columns of one particular table. You can create a view using more than one table and/or other views with a SELECT clause of any complexity.

There are, however, a few restrictions on the SELECT clauses in a view definition:

•	You cannot include ORDER BY, COMPUTE, or COMPUTE BY clauses.

•	You cannot include the INTO keyword.

•	You cannot reference a temporary table.

WITH CHECK OPTION

Forces all data modification statements executed against the view to adhere to the criteria set within the select_statement defining the view. When a row is modified through a view, the WITH CHECK OPTION guarantees that the data will remain visible through the view after the modification has been committed.

Remarks

You can create a view only in the current database. A view can reference a maximum of 250 columns.

In a view defined with a SELECT * clause, if you alter the structure of its underlying table(s) by adding columns, the new columns do not appear in the view unless the view is first deleted and redefined. The asterisk shorthand is interpreted and expanded when the view is first created.

When you query through a view, 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 to replace the one dropped, the view again becomes usable.

When you create a view, the name of the view is stored in the sysobjects table and the view's normalized query tree is stored in the sysprocedures 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 view creation 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.


View Restrictions

When creating and using a view, these rules apply:

•	CREATE VIEW statements cannot be combined with other SQL statements in a single batch.

•	You cannot create a trigger on a view.

•	The UNION operator cannot be used within a CREATE VIEW statement.

•	Data modification statements (INSERT or UPDATE) are allowed on multitable views if the data modification statement affects only one base table. You cannot use data modification statements on more than one table in a single statement.

•	INSERT statements are not allowed if a computed column exists within the view.

•	INSERT statements are not accepted unless all the NOT NULL columns without defaults in the underlying table or view are included in the view through which you are inserting new rows. (SQL Server has no way to supply values for NOT NULL columns in the underlying table or view.)

•	All column(s) being modified must adhere to all restrictions for the data modification statement as if it were executed directly against the base table. This applies to column nullability, constraints, identity columns, and columns with rules and/or defaults and base table triggers.

•	UPDATE statements cannot change any column in a view that is a computation, nor can they change a view that includes aggregate functions, built-in functions, a GROUP BY clause, or DISTINCT.

•	You cannot use READTEXT or WRITETEXT on text or image columns in views.

•	By default, data modification statements on views are not checked to determine whether the rows affected will be within the scope of the view. You can issue an INSERT statement on a view to add a row to the underlying base table, but not to add it to the view. Similarly, you can issue an UPDATE statement that changes a row so that the row no longer meets the criteria for the view. If all modifications should be checked, use the WITH CHECK option.

Important  If you define a view with an outer join and then query the view with a qualification on a column from the inner table of the outer join, the results can differ from what you expect. All rows from the inner table are returned. Rows that do not meet the qualification show a null value in the appropriate columns for those rows.


Getting Information About Views

To display the text used to create a view, execute the sp_helptext system stored procedure with the view name as the parameter.

Note  Views created with the ENCRYPTION option cannot be viewed with the sp_helptext system stored procedure.

To get a report of the tables or views on which a view depends, and of objects that depend on a view, execute the sp_depends system stored procedure.

You can rename a view with the sp_rename system stored procedure.

Permission

CREATE VIEW permission defaults to the database owner, who can transfer it to other users. The creator of a view must have SELECT permission for any object referenced in the view definition to SELECT from the view.


CREATE VIEW Examples
Examples

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.

CREATE VIEW titles_view

AS

SELECT title, type, price, pubdate

FROM titles

B.	WITH ENCRYPTION

This example uses the WITH ENCRYPTION option and shows computed columns and renaming the columns.

CREATE VIEW accounts (title, advance, amt_due)

WITH ENCRYPTION

AS

SELECT title, advance, price * royalty * ytd_sales

FROM titles

WHERE price > $5

sp_helptext accounts

go

The object's comments have been encrypted.

SELECT c.id, c.text

FROM syscomments c, sysobjects o

WHERE c.id = o.id and o.name = 'accounts'

go

id          text
----------- --------------------------------------------
1088007403  GýtåvùO_Oéq:4h"ØË"/WÉm¢?BùŸ'0_%Û'	™²Î_Ú?­

C.	WITH CHECK OPTION

This example shows a view named CAonly that will allow data modifications to apply only to authors within the state of California.

CREATE VIEW CAonly

AS

SELECT au_lname, au_fname, city, state

FROM authors

WHERE state = 'CA'

WITH CHECK OPTION

D.	Built-in Functions Within a View

This example shows a view definition that includes a built-in function. When using functions, the derived column must include a column name in the CREATE VIEW statement:

CREATE VIEW categories (category, average_price)

AS

SELECT type, AVG(price)

FROM titles

GROUP BY type

See Also

DELETE	sp_help
DROP VIEW	sp_helptext
INSERT	sp_rename
SELECT	UPDATE
sp_depends


Cursors

For more information about how SQL Server 6.5 affects existing database systems, see Cursors.

Server cursors allow individual row operations to be performed on a given results set or on the entire set. In SQL Server 6.0, ANSI SQL cursors are server based. In earlier releases, cursors were provided only through the DB-Library and Open Database Connectivity (ODBC) cursor APIs.

The addition of cursors to the server provides an efficient way for single-row operations to occur within a given results set. ANSI SQL cursors support only single-row cursors. Each fetch will return only one row from the results set. Server cursors enhance the general use of relational databases by allowing row-level operations when set-oriented operations are impractical. In relational systems, set operations are preferred; cursors provide a powerful complement to set operations. Using cursors, multiple operations can be performed row by row against a results set with or without returning to the original table. In other words, cursors conceptually return a results set based on tables within the database(s). For example, a cursor can be generated to include a list of all user-defined table names within a database. After the cursor has been opened, movement (fetching) through the results set can include multiple operations against each table by passing each table name as a variable. Cursors are extremely powerful when combined with stored procedures and the EXECUTE statement (to dynamically build strings).

SQL Server provides two interfaces for cursor functions. When using cursors in Transact-SQL batches or stored procedures, ANSI-standard SQL syntax has been added for declaring, opening, and fetching from cursors as well as positioned updates and deletes. When using cursors from a DB-Library or ODBC program, the SQL Server 6.0 client libraries transparently call built-in server functions to handle cursors more efficiently.

This overview shows the statements, in order, used to implement a cursor.

Statement	Description
DECLARE CURSOR Statement	Defines a cursor.
OPEN Statement	Opens a declared cursor.
FETCH Statement	Retrieves a specific row from the cursor.
CLOSE Statement	Closes an open cursor.
DEALLOCATE Statement	Removes the cursor data structures.
In addition to browsing through the cursor results with FETCH, the current row of an open cursor can be modified. The UPDATE statement and the DELETE statement, when used against a cursor, affect only the row on which the cursor is currently positioned.

Syntax

To update the current row:

UPDATE table_name
SET column_name1 =
{expression1 | NULL | (select_statement)}
[, column_name2 =
{expression2 | NULL | (select_statement)}...]
WHERE CURRENT OF cursor_name

To delete the current row:

DELETE FROM table_name
WHERE CURRENT OF cursor_name

Modifications made with WHERE CURRENT OF cursor_name affect only the single row on which the cursor is positioned. In the case of a cursor based on a join, only the table_name specified in the DELETE or UPDATE statement is modified. Other tables participating in the cursor are not affected. For complete syntax and more information, see the DELETE and UPDATE statements.

The following sections discuss each of the statements used to define, access, and close a cursor.


DECLARE Statement

Defines a cursor. Once declared, row sets for cursors are assigned by using the OPEN statement. (The DECLARE statement can also be used to define the name and type of local variables for a batch or procedure. For more information on variable declaration and assignment, see the DECLARE Statement.)

Syntax

DECLARE cursor_name [INSENSITIVE] [SCROLL] CURSOR
FOR select_statement
[FOR {READ ONLY | UPDATE [OF column_list]}]

where

cursor_name

Is the name of the cursor being defined. The cursor_name must conform to the rules for identifiers.

INSENSITIVE

Defines a cursor that makes a temporary copy of the data to be used by the cursor. All requests to the cursor are answered from this temporary table; therefore, modifications made to base tables will not be reflected in the data returned by fetches made to this cursor, and this cursor does not allow modifications.

SCROLL

Specifies that all methods of fetching data are available. Committed deletes and updates made to the underlying tables (by any users) are reflected in subsequent fetches (provided that the cursor is not declared with the INSENSITIVE option).

select_statement

Is a standard SELECT statement used to identify a set of rows from a given table or tables within a database. If each of the underlying tables does not have a unique index, the cursor will automatically be an INSENSITIVE 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, and/or HAVING are used, one or more of the underlying tables does not have a unique index, or a constant expression is included in the select_list, the cursor will be created as INSENSITIVE.

READ ONLY

Prevents updates from occurring against any row within this cursor. This option overrides the default capability of a cursor to be updated.

UPDATE [OF column_list]

Defines updatable columns within the cursor. If OF column_list 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.


OPEN Statement

Opens a cursor.

Syntax

OPEN cursor_name

where

cursor_name

Specifies the name of an already-declared cursor. In the case of an INSENSITIVE cursor, this will generate the required temporary table. At the time the cursor is opened, results set membership and ordering are fixed.

Note  Membership and ordering are fixed when the cursor is opened; updates and deletes that have been committed against the base tables of the cursor by other users will be reflected in fetches made against all cursors defined without the INSENSITIVE option. This behavior is commonly called keyset-driven. Rows that have been deleted from a results set will appear with NULLs in all variable columns, spaces in all char columns, and default or zero values in all other non-null columns. To differentiate between a deleted row and a row that has been inserted with NULL data values, use the global variable @@FETCH_STATUS after each FETCH is made against the cursor.

Remarks

Once a cursor has been opened, use the global variable @@CURSOR_ROWS to receive the number of qualifying rows in the last opened cursor. Depending on the number of rows expected in the results set, SQL Server may choose to populate the keyset asynchronously on a separate thread. This allows fetches to proceed immediately, even if the keyset is not fully populated. @@CURSOR_ROWS returns:

−m	If the cursor is being populated asynchronously. The value returned (−m) refers to the number of rows currently in the keyset.
n	If the cursor is fully populated. The value returned (n) refers to the number of rows.
0	If no cursors have been opened or the last opened cursor has been closed or deallocated.
To set the threshold at which SQL Server will generate keysets asynchronously, use the cursor threshold configuration option. For details, see the sp_configure system stored procedure.


FETCH Statement

For more information about how SQL Server 6.5 affects existing database systems, see FETCH Statement.

Retrieves a specific row from the cursor.

FETCH [[NEXT | PRIOR | FIRST | LAST | ABSOLUTE n | RELATIVE n] FROM] cursor_name
[INTO @@variable_name1, @@variable_name2, ...]

where

NEXT

Returns the first row of the results set if this is the first fetch against the cursor; otherwise, it moves the cursor one row within the results set. NEXT is the primary method used to move through a results set. NEXT is the default cursor fetch.

Note  PRIOR, FIRST, LAST, ABSOLUTE n, and RELATIVE n are available only with cursors defined with the SCROLL option.

PRIOR

Returns the previous row within the results set.

FIRST

Moves the cursor to the first row within the results set and returns the first row.

LAST

Moves the cursor to the last row within the results set and returns the last row.

ABSOLUTE n

Returns the nth row within the results set. If n is a negative value, the returned row will be the nth row counting backward from the last row of the results set.

RELATIVE n

Returns the nth row after the currently fetched row. If n is a negative value, the returned row will be the nth row counting backward from the relative position of the cursor.

FROM cursor_name

Defines the cursor from which the fetch should be made. Multiple cursors are allowed within any session provided that each has a unique name.

INTO @@variable_name1, @@variable_name2, ...

Allows data returned within a fetch to be placed into local variables. Each of the variables must match the datatype. Errors will occur when the datatypes are incompatible. Implicit datatype conversions are not provided here.

A global variable, @@FETCH_STATUS, will be updated at every execution of FETCH. At a successful fetch, @@FETCH_STATUS will be set to 0. If no data was fetched because the requested cursor position exceeded the results set, −1 will be returned. If the row returned is no longer a member of the results set (for example, the row was deleted from the base table after the cursor was opened), @@FETCH_STATUS will return −2. Always use this to determine the validity of the data returned from a cursor fetch prior to attempting any operation against that data.


CLOSE Statement

Closes an open cursor. CLOSE leaves the data structures accessible for reopening; however, modifications or fetches are not allowed until the cursor is reopened.

Syntax

CLOSE cursor_name

where

cursor_name

Specifies the name of an already-declared cursor.


DEALLOCATE Statement

Removes the cursor data structures. DEALLOCATE is different from CLOSE in that a closed cursor can be re-opened. DEALLOCATE releases all data structures associated with the cursor and removes the definition of the cursor.

Syntax

DEALLOCATE cursor_name

where

cursor_name

Specifies the name of an already-declared cursor.


Cursors Examples

A.	Simple Cursor and Syntax

The results 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 will be 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.	Ad hoc Fetches and Complex Join Cursor

In this example, a SCROLL cursor is created to allow full scrolling capabilities. This cursor's results set is determined when the open cursor occurs; however, when fetches are made, updated or deleted rows will be reflected. Ad hoc fetches are shown for emphasis in this example, but these are not commonly done in practice. In actuality, positioning within the cursor would be performed within a stored procedure (see example C) or within a client application using DB-Library or ODBC API cursor calls.

In addition to full scrolling capabilities, this example shows that string concatenation, string functions such as RTRIM, data conversions, and explicit columns headings are available within the definition of a cursor.

USE pubs

go

SET NOCOUNT ON

go

DECLARE complex_join_cursor SCROLL CURSOR

FOR

SELECT Author = CONVERT(char(18),

RTRIM(a.au_fname) + " " +  RTRIM(a.au_lname)),

"Short Title" = CONVERT(char(30), t.title),

Sales = t.ytd_sales

FROM authors a, titles t, titleauthor ta

WHERE a.au_id = ta.au_id

AND ta.title_id = t.title_id

AND t.ytd_sales > 0

OPEN complex_join_cursor

/*

This next select shows a listing of authors with

which the cursor results can be compared. Some authors have

written multiple titles; this list of authors expects duplicates.

*/

SELECT Author = CONVERT(char(18),

RTRIM(a.au_fname) + " " + RTRIM(a.au_lname)),

"Short Title" = CONVERT(char(25), t.title),

Sales = t.ytd_sales

FROM authors a, titles t, titleauthor ta

WHERE a.au_id = ta.au_id

AND ta.title_id = t.title_id

AND t.ytd_sales > 0

go

 Author             Short Title               Sales

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

 Marjorie Green     The Busy Executive's Data        4095

 Abraham Bennet     The Busy Executive's Data        4095

 Michael O'Leary    Cooking with Computers: S        3876

 Stearns MacFeather Cooking with Computers: S        3876

 Marjorie Green     You Can Combat Computer S       18722

 Dean Straight      Straight Talk About Compu        4095

 Innes del Castillo Silicon Valley Gastronomi        2032

 Michel DeFrance    The Gourmet Microwave           22246

 Anne Ringer        The Gourmet Microwave           22246

 Cheryl Carson      But Is It User Friendly?         8780

 Ann Dull           Secrets of Silicon Valley        4095

 Sheryl Hunter      Secrets of Silicon Valley        4095

 Stearns MacFeather Computer Phobic and Non-P         375

 Livia Karsen       Computer Phobic and Non-P         375

 Anne Ringer        Is Anger the Enemy?              2045

 Albert Ringer      Is Anger the Enemy?              2045

 Albert Ringer      Life Without Fear                 111

 Johnson White      Prolonged Data Deprivatio        4072

 Charlene Locksley  Emotional Security: A New        3336

 Sylvia Panteley    Onions, Leeks, and Garlic         375

 Reginald Blotchet- Fifty Years in Buckingham       15096

 Michael O'Leary    Sushi, Anyone?                   4095

 Burt Gringlesby    Sushi, Anyone?                   4095

 Akiko Yokomoto     Sushi, Anyone?                   4095

/*

All of the fetches that follow are in separate batches to allow

the results to follow immediately. In practice, fetches most

commonly occur within some looping construct. See Example C for

more detail.

*/

FETCH NEXT FROM complex_join_cursor

select "Fetch_Status" = @@fetch_status

go

 Author             Short Title                    Sales

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

 Marjorie Green     The Busy Executive's Database         4095

 Fetch_Status

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

            0

FETCH LAST FROM complex_join_cursor

SELECT "Fetch_Status" = @@FETCH_STATUS

go

 Author             Short Title                    Sales

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

 Akiko Yokomoto     Sushi, Anyone?                        4095

 Fetch_Status

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

            0

FETCH RELATIVE 0 FROM complex_join_cursor

SELECT "Fetch_Status" = @@FETCH_STATUS

go

 Author             Short Title                    Sales

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

 Akiko Yokomoto     Sushi, Anyone?                        4095

 Fetch_Status

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

            0

FETCH FIRST FROM complex_join_cursor

SELECT "Fetch_Status" = @@FETCH_STATUS

go

 Author             Short Title                    Sales

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

 Marjorie Green     The Busy Executive's Database         4095

 Fetch_Status

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

            0

FETCH NEXT FROM complex_join_cursor

SELECT "Fetch_Status" = @@FETCH_STATUS

go

 Author             Short Title                    Sales

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

 Abraham Bennet     The Busy Executive's Database         4095

 Fetch_Status

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

            0

/*

Without having used the INSENSITIVE option, this cursor will

receive current data from the base table. When a row is deleted

the membership of that row does not change; however, no data is

available to be returned to the client. The following statement

could have been executed by anyone on the system with DELETE

privileges.

*/

DELETE authors

WHERE au_lname = 'Green' and au_fname = 'Marjorie'

go

/*

Notice the status value returned when the row requested

has been deleted.

*/

FETCH FIRST FROM complex_join_cursor

SELECT "Fetch_Status" = @@FETCH_STATUS

go

 Author             Short Title                    Sales

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

 NULL               NULL                                  NULL

 Fetch_Status

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

           -2

FETCH ABSOLUTE 8 FROM complex_join_cursor

SELECT "Fetch_Status" = @@FETCH_STATUS

go

 Author             Short Title                    Sales

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

 Michel DeFrance    The Gourmet Microwave                22246

 Fetch_Status

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

            0

/*

In addition to data modification with the Transact-SQL DELETE

statement, a cursor-specific DELETE can be made.

*/

DELETE FROM authors WHERE CURRENT OF complex_join_cursor

go

/*

Notice that the status value returned when the row requested

has been deleted is the same regardless of the type of

DELETE performed.

*/

FETCH RELATIVE 0 FROM complex_join_cursor

SELECT "Fetch_Status" = @@FETCH_STATUS

go

 Author             Short Title                    Sales

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

 NULL               NULL                                  NULL

 Fetch_Status

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

           -2

FETCH RELATIVE -1 FROM complex_join_cursor

SELECT "Fetch_Status" = @@FETCH_STATUS

go

 Author             Short Title                    Sales

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

 Innes del Castillo Silicon Valley Gastronomic Tre        2032

 Fetch_Status

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

            0

FETCH ABSOLUTE 200 FROM complex_join_cursor

SELECT "Fetch_Status" = @@FETCH_STATUS

go

/*

Notice that when the requested row is outside the

cursor, no row is returned, the fetch status is -1,

and the cursor is positioned after the end of the results

set. FETCH PRIOR demonstrates this.

*/

 Fetch_Status

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

           -1

FETCH PRIOR FROM complex_join_cursor

SELECT "Fetch_Status" = @@FETCH_STATUS

go

/* Notice the positioning

 Author             Short Title                    Sales

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

 Akiko Yokomoto     Sushi, Anyone?                        4095

 Fetch_Status

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

            0

FETCH ABSOLUTE -200 FROM complex_join_cursor

SELECT "Fetch_Status" = @@FETCH_STATUS

go

/*

In this example, the cursor is positioned before the first row, no row is returned, and the fetch status is -1. FETCH NEXT demonstrates these results. Remember that Marjorie

Green has been deleted from the authors table.

*/

 Fetch_Status

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

           -1

FETCH NEXT FROM complex_join_cursor

SELECT "Fetch_Status" = @@FETCH_STATUS

go

 Author             Short Title                    Sales

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

 NULL               NULL                                  NULL

 Fetch_Status

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

           -2

CLOSE complex_join_cursor

DEALLOCATE complex_join_cursor

go

C.	Cursor with a Stored Procedure

This example shows the cursor declaration and use within a stored procedure.

This example shows how to use the global variable @@FETCH_STATUS within a looping data structure and also shows a simple report structure for the output.

/*
Create the stored procedure that declares, opens and then
uses the cursor.
*/

CREATE PROCEDURE dbcc_all_tables
AS
/*
This procedure will generate a short report of the DBCC
output for all tables within this database.
*/
DECLARE @@tablename varchar(30)
DECLARE @@tablename_header varchar(75)
DECLARE tnames_cursor CURSOR FOR SELECT name FROM sysobjects
WHERE type = 'U'
OPEN tnames_cursor
FETCH NEXT FROM tnames_cursor INTO @@tablename
WHILE (@@FETCH_STATUS <> -1)
BEGIN
/*
Because @@FETCH_STATUS will return one of three values, -2,
-1, or 0, all three cases must be tested. In this case, if
a table has been dropped since the time this stored
procedure was executed, it will be skipped. A
successful fetch (0) will cause the DBCC within the
BEGIN..END loop to execute.
*/
IF (@@FETCH_STATUS <> -2)
BEGIN
PRINT " "
SELECT @@tablename_header = "**************  " +
RTRIM(UPPER(@@tablename)) + "  *************"
PRINT @@tablename_header
PRINT " "
EXEC ("DBCC CHECKTABLE(" + @@tablename + ")")
END
FETCH NEXT FROM tnames_cursor INTO @@tablename
END
PRINT " "
PRINT " "
SELECT @@tablename_header = "*************  NO MORE TABLES"
+ "  *************"
PRINT @@tablename_header
PRINT " "
PRINT "DBCC has been run against all user-defined tables."
DEALLOCATE tnames_cursor
go

dbcc_all_tables 'U'
go

**************  AUTHORS  *************

Checking authors
The total number of data pages in this table is 1.
Table has 23 data rows.
DBCC execution completed. If DBCC printed error messages, see your System Administrator.

**************  PUBLISHERS  *************

Checking publishers
The total number of data pages in this table is 1.
Table has 8 data rows.
DBCC execution completed. If DBCC printed error messages, see your System Administrator.

**************  TITLES  *************

Checking titles
The total number of data pages in this table is 3.
Table has 18 data rows.
DBCC execution completed. If DBCC printed error messages, see your System Administrator.

**************  TITLEAUTHOR  *************

Checking titleauthor
The total number of data pages in this table is 1.
Table has 25 data rows.
DBCC execution completed. If DBCC printed error messages, see your System Administrator.

**************  STORES  *************

Checking stores
The total number of data pages in this table is 1.
Table has 6 data rows.
DBCC execution completed. If DBCC printed error messages, see your System Administrator.

**************  SALES  *************

Checking sales
The total number of data pages in this table is 1.
Table has 21 data rows.
DBCC execution completed. If DBCC printed error messages, see your System Administrator.

**************  ROYSCHED  *************

Checking roysched
The total number of data pages in this table is 2.
Table has 86 data rows.
DBCC execution completed. If DBCC printed error messages, see your System Administrator.

**************  DISCOUNTS  *************

Checking discounts
The total number of data pages in this table is 1.
Table has 3 data rows.
DBCC execution completed. If DBCC printed error messages, see your System Administrator.

**************  JOBS  *************

Checking jobs
The total number of data pages in this table is 1.
Table has 14 data rows.
DBCC execution completed. If DBCC printed error messages, see your System Administrator.

**************  EMPLOYEE  *************

Checking employee
The total number of data pages in this table is 2.
Table has 43 data rows.
DBCC execution completed. If DBCC printed error messages, see your System Administrator.

**************  PUB_INFO  *************

Checking pub_info
The total number of data pages in this table is 1.
The total number of TEXT/IMAGE pages in this table is 73.
Table has 8 data rows.
DBCC execution completed. If DBCC printed error messages, see your System Administrator.

*************  NO MORE TABLES  *************

DBCC has been run against all user-defined tables.

See Also

DELETE	UPDATE
SELECT


Datatypes

Datatypes specify the data characteristics of columns, stored-procedure parameters, and local variables.

SQL Server supplies various system datatypes, which can be categorized by the type of data stored within the datatype. In addition to system-supplied datatypes, SQL Server allows user-defined datatypes, which are based on the system datatypes. For details about user-defined datatypes, see the sp_addtype system stored procedure.

In SQL Server 6.0, all system datatype names are case-insensitive. This change allows table definitions, variable declarations, and procedure parameters to include uppercase or lowercase datatype definitions. Because datatypes are case-insensitive, identical user-defined datatype names with only differing capitalization are not allowed for user-defined datatypes.

Important  An existing user-defined datatype whose name conflicts with that of another user-defined datatype or system-supplied datatype will no longer be referenced. If an existing user-defined datatype is found within a table, view, or procedure definition and has a conflict, the user-defined datatype will be mapped to the system datatype and no longer reference the user-defined datatype.

These are the system datatypes:

Type of data	System-supplied datatype
Binary	binary[(n)] varbinary[(n)]
Character	char[(n)] varchar[(n)]
Date and time	datetime smalldatetime
Exact numeric	decimal[(p[, s])] numeric[(p[, s])]
Approximate numeric	float[(n)] real
Integer	int smallint tinyint
Monetary	money smallmoney
Special	bit timestamp user-defined datatypes
Text and image	text image
Synonyms	binary varying for varbinary character for char character for char (1) character (n) for char (n) character varying (n) for varchar (n)  dec for decimal integer for int double precision for float float [(n)] for n = 17 for real float [(n)] for n = 815 for float


Using Datatypes in TransactSQL Statements
Using Datatypes in Transact-SQL Statements

To declare the datatype for a column in a table:

CREATE TABLE [[database.]owner.]table_name
(column_name datatype [NOT NULL | NULL]
[, column_name datatype [NOT NULL | NULL]]...)

ALTER TABLE [[database.]owner.]table_name
ADD column_name datatype NULL
[, column_name datatype NULL...]

For complete syntax, see the CREATE TABLE and ALTER TABLE statements.

To declare the datatype for a local variable:

DECLARE @variable_name datatype
[, @variable_name datatype...]

For complete syntax, see the DECLARE statement.

To declare the datatype for a parameter in a stored procedure:

CREATE PROCedure [owner.]procedure_name[;number]
[(parameter1 [, parameter2]...[parameter255])]
[{FOR REPLICATION} | {WITH RECOMPILE}
[{[WITH] | [,]} ENCRYPTION]]
AS sql_statements

where

parameter =

@parameter_name datatype [= default] [OUTPUT]

For complete syntax, see the CREATE PROCEDURE statement.

To change a value from one datatype to another:

CONVERT (datatype[(length)], expression [, style])

For the complete CONVERT function syntax, see the Functions topic.


Binary Data

Binary data consists of the characters 0 through 9 and A through F (or a through f), in groups of two characters each. Binary strings must be preceded by 0x. For example, to input "FF", type 0xFF. The maximum binary data value is 255 bytes, each of which is "FF". The binary datatypes are not for hexadecimal data, but rather for bit patterns. Conversions and calculations of hexadecimal numbers stored as binary data can be unreliable. For more information, see the CONVERT function in the Functions topic.

When specifying the length of a binary datatype, every two characters count as one. A length of 10 signifies that 10 two-character groupings will be entered.

These are the binary datatypes:

binary[(n)]

Is a datatype that holds as many as 255 bytes of fixed-length binary data. Specify the maximum byte length with n. The binary datatype can contain 0 bytes, but when specified, n must be a value from 1 through 255. Storage size is n regardless of the actual length of the entry.

Choose binary when you think the data entries in the column will be consistently close to the same size. Columns of type binary are accessed somewhat faster than varbinary columns because they use a fixed storage length (n).

Note  When the binary datatype is used with the ALTER TABLE or CREATE TABLE statement, a column defined as NULL will be handled as a varbinary column.

varbinary[(n)]

Is a variable-length binary datatype that holds a maximum of 255 bytes of variable-length binary data. Specify the maximum byte length with n. A varbinary datatype can contain 0 bytes, but when specified, n must be a value from 1 through 255. Storage size is the actual length of the data entered, not n.

Choose varbinary when you expect null values or a variation in data size.

Important  When n is not specified in a data definition statement (such as CREATE TABLE) or in a variable declaration, the length supplied is 1 (the ANSI-standard). When n is not specified with the CONVERT function, SQL Server defaults to a length of 30.

If the data entered is too long for the specified datatype, binary and varbinary entries are truncated.


Character Data

Character data consists of any combination of letters, symbols, and numbers. When entered, character data must be enclosed with single quotation marks ('). If numbers are stored as character data, they must be converted to a numeric datatype (decimal, float, int, money, numeric, real, smallint, smallmoney, or tinyint) before you can use them in calculations. If the value of the string is the null value, do not enclose NULL in single quotation marks ('). To supply the null value, use the keyword NULL during INSERT or UPDATE.

Note  An empty string is not considered the same as NULL. An empty string with no characters, supplied as ' ', will insert a single blank space.

These are the character datatypes:

char[(n)]

Is a datatype that holds a maximum of 255 characters. Specify the maximum length with n. The char datatype can contain 0 characters, but when specified, n must be a value from 1 through 255. Storage size is n regardless of the actual length of the entry.

Choose char when you think the data entries in the column will be consistently close to the same size. Columns of type char are accessed somewhat faster than varchar columns because they use a fixed storage length (n).

Note  When the char datatype is used with the ALTER TABLE or CREATE TABLE statement, a column defined as NULL will be handled as a varchar column.

varchar[(n)]

Is a datatype that holds a maximum of 255 characters. Specify the maximum length with n. The varchar datatype can contain 0 characters, but n must be a value from 1 through 255. Storage size is not fixed with a varchar column. Instead, storage is defined by the actual size of the data entered (ignoring all trailing blanks).

Choose varchar when you expect null values or a wide variation in data size.

Important  When n is not specified in a data definition statement (such as CREATE TABLE) or in a variable declaration, the length supplied is 1 (the ANSI-standard). When n is not specified with the CONVERT function, SQL Server determines the appropriate value of n based on the length of the data being converted.

If the data entered is too long for the specified datatype, char and varchar entries are truncated. Similarly, if you enter strings that are shorter than the maximum length, char columns that do not allow null values and char variables will be padded with trailing blanks; char columns that allow null values and varchar columns or variables will not store trailing blanks. This is important when using the LIKE comparison operator with varchar and char strings. Other comparison operators, such as the equal sign (=), always right-pad the shorter string with blanks before comparing. For more information, see the Search Conditions and Wildcard Characters topics.


Date and Time Data

Date and time data consist of alphanumeric data representing a date and time of day. The default display format for dates is "Mon dd yyyy hh:mmAM" (or PM), such as "Apr 15 1996 10:23AM". When time data is entered, the order of time components is significant: hours; minutes; seconds; milliseconds; AM, am, PM, or pm (12AM is midnight, 12PM is noon). To be recognized as time, a value must contain either a colon (:) or an AM/PM signifier.

Always enclose datetime values with single quotation marks ('). Capitalization (case) is ignored, and spaces can occur anywhere between date parts. SQL Server recognizes the date portion and the time portion of the data separately, so the time can precede or follow the date.

Use date functions with the CONVERT function to display seconds and milliseconds and to get other date styles and date part orderings by converting datetime data to char.

These are the date and time datatypes:

datetime

Is a datatype stored in 8 bytes of two 4-byte integers: 4 bytes for the number of days before or after the base date of January 1, 1900, and 4 bytes for the number of milliseconds after midnight. The date segments of datetime values representing dates prior to the base date are stored as negative values.

Data values for datetime range from January 1, 1753, to December 31, 9999, to an accuracy of one three-hundredth second, or 3.33 milliseconds. SQL Server rejects all values it cannot recognize as dates between 1753 and 9999. You can omit either portion, but if you omit both, datetime defaults to January 1, 1900, 12:00:00:000AM. If you omit the time portion of a datetime value, the default (12:00:00:000AM) is supplied. If you omit the date portion, the default (Jan 1 1900) is supplied. For example, an empty string or missing date is interpreted as the base date, January 1, 1900. A time value without a date, for example 4:33, is interpreted as January 1, 1900, 4:33AM.

smalldatetime

Is a date and time datatype less precise than datetime. This parameter's storage size is 4 bytes, consisting of one small integer for the number of days after January 1, 1900, and one small integer for the number of minutes past midnight. Data values for smalldatetime range from January 1, 1900, through June 6, 2079, with accuracy to the minute.

Date Formats

SQL Server recognizes the following formats (alphabetic, numeric, and unseparated string) for date data. Enclose each format with single quotation marks (').

Alphabetic format

The month can be the full name or the abbreviation given in the current language; commas are optional and capitalization (case) is ignored.

These alphabetic formats are acceptable:

Apr[il] [15][,] 1996

Apr[il] 15[,] [19]96

Apr[il] 1996 [15]

Apr[il] [19]96 15

[15] Apr[il][,] 1996

15 Apr[il][,][19]96

15 [19]96 apr[il]

[15] 1996 apr[il]

1996 APR[IL] [15]

[19]96 APR[IL] 15

1996 [15] APR[IL]

If you specify only the last two digits of the year, values less than 50 are interpreted as 20yy, and values greater than or equal to 50 are interpreted as 19yy. For example, if you specify 3, the result is 2003. If you specify 82, the result is 1982. You must type the century when the day is omitted or when you need a century other than the default.

If the day is missing, the first day of the month is supplied.

The DATEFORMAT session setting is not applied when you specify the month in alphabetic form. For more information, see the SET statement.

Numeric format

You must specify the month, day, and year in a string with slashes (/), hyphens (-), or periods (.) as separators.

This string must appear in the following form:

<num> <sep> <num> <sep> <num> [<time_spec>] [<time_spec>]

These numeric formats are acceptable:

[0]4/15/[19]96 (mdy)

[0]4-15-[19]96 (mdy)

[0]4.15.[19]96 (mdy)

[04]/[19]96/15 (myd)

15/[0]4/[19]96 (dmy)

15/[19]96/[0]4 (dym)

[19]96/15/[0]4 (ydm)

[19]96/[04]/15 (ymd)

When the language is set to us_english, the default order for the date is mdy. You can change the date order with the SET DATEFORMAT statement, which can also affect the date order, depending on the language.

The setting for DATEFORMAT determines how date values are interpreted. If the order doesn't match the setting, the values are not interpreted as dates (because they are out of range), or the values are misinterpreted. For example, 12/10/08 can be interpreted as one of six dates, depending on the DATEFORMAT setting. For more information, see the SET statement.

Unseparated string format

An unseparated string can specify four, six, or eight digits, an empty string, or a time value without a date value.

The DATEFORMAT session setting does not apply to all-numeric date entries (numeric entries without separators). Six- or eight-digit strings are always interpreted as ymd. The month and day must always be two digits.

This is the acceptable unseparated string format:

[19]960415

A string of only four digits is interpreted as the year. The month and date are set to January 1. When specifying only four digits, you must include the century.

Time Formats

SQL Server recognizes the following formats for time data. Enclose each format with single quotation marks ('). The hour can refer to 12-hour or 24-hour time. Capitalization (case) (for AM or PM) is ignored.

14:30

14:30[:20:999]

14:30[:20.9]

4am

4 PM

[0]4[:30:20:500]AM

Milliseconds can be preceded by either a colon (:) or a period (.). If preceded by a colon, the number means thousandths-of-a-second. If preceded by a period, a single digit means tenths-of-a-second, two digits mean hundredths-of-a-second, and three digits mean thousandths-of-a-second. For example, "12:30:20:1" means twenty and one-thousandth seconds past 12:30; "12:30:20.1" means twenty and one-tenth seconds past 12:30.

Using Data and Time Datatypes

You can perform some arithmetic calculations on datetime data with the built-in date functions. For more information, see the Functions topic.

Searching for datetime values with an equal sign (=) and the month, day, and year returns only those time values that are precisely 12:00:00:000 AM (the default).

If you use the keyword LIKE with datetime values, SQL Server first converts the dates to datetime format and then to varchar. Since the standard display formats don't include seconds or milliseconds, you cannot search for them with LIKE and a matching pattern, unless you use the CONVERT function with the style parameter set to 9 or 109. However, LIKE works well when searching for datetime values that contain a variety of date parts. For example, if you insert the value 9:20 into a column named arrival_time, the clause WHERE arrival_time = '9:20', does not find the value because SQL Server converts the entry into Jan 1 1900 9:20AM. However, the clause WHERE arrival_time LIKE '%9:20%' does find the value.

When using LIKE with a single-digit day of the month (1 to 9), you must insert one space between the month and the day to match the varchar conversion of the datetime value. Similarly, if the hour is less than 10, the conversion places two spaces between the year and the hour. The clause 'LIKE May 2%' (with one space between May and 2) finds all dates from May 20 through May 29, but not May 2. You don't need to insert the extra space with other date comparisons, because LIKE is the comparison for which the datetime values are converted to varchar.


Exact Numeric Data

Exact numeric data consists of numeric data with accuracy preserved to the least-significant digit. SQL Server 6.0 supports two exact numeric datatypes: decimal and numeric. Both decimal and numeric data can contain an integer component to the left of the decimal point and a fractional component to the right of the decimal point. Exact numeric datatypes are different from the approximate numeric datatypes float and real, which cannot store all decimal numbers with complete accuracy. The decimal and numeric datatypes are identical in the SQL Server 6.0 implementation. Both are provided for ANSI compatibility.

These are the exact numeric datatypes:

decimal[(p[, s])] and numeric[(p[, s])]

Are exact numeric datatypes that hold values from 10 (38)  − 1 through − 10 (38) . Storage size varies based on the specified precision, and it ranges from a minimum of 2 bytes to a maximum of 17 bytes, as follows:

Precision	Storage bytes
1 − 2	2
3 −4	3
5−7	4
8−9	5
10−12	6
13−14	7
15−16	8
17−19	9
20−21	10
22−24	11
25−26	12
27−28	13
29−31	14
32−33	15
34−36	16
37−38	17
Precision (p) specifies the maximum total number of decimal digits that can be stored, both to the left and to the right of the decimal point. Scale (s) specifies 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.

Specify the precision with p, which must be a value from 1 through the maximum precision, and the scale with s, which must be a value from 0 through p. SQL Server normally supports a maximum precision of 28 digits for compatibility with limits of various front ends, such as Microsoft Visual Basic. However, if a precision greater than 28 is needed, use the /p parameter with SQLSERVR.EXE. For more information on running SQLSERVR.EXE, see the Utilities and Executables topic. If you do not specify the precision, SQL Server uses a default precision of 18. If you do not specify the scale, SQL Server uses a default scale of 0.


Approximate Numeric Data

Approximate numeric data consists of numeric data preserved as accurately as the binary numbering system allows. Many floating-point values cannot be accurately represented in binary notation. For these numbers, it is necessary to store an approximation of the decimal number. Examples of these numbers are floating-point values ending in .3, .6, and .7. The IEEE 754 specification provides four rounding modes: round to nearest, round up, round down, and round toward zero. SQL Server uses round up. All are accurate to guaranteed precision but can result in slightly different floating-point values. Because the binary representation of a floating-point number may use one of many legal rounding schemes, it is impossible to reliably quantify a floating-point value. It is best to avoid referencing to floating-point columns in WHERE clauses.

These are the approximate numeric datatypes:

float[(n)]

Is a datatype that holds positive or negative floating-point numbers. Specify the binary precision with b, which must be from 1 through 15. If the binary precision is from 1 through 7, it is another name for the real datatype. If the binary precision is from 8 through 15, it is considered a synonym for the float datatype. By default, this column has a 15-digit precision. The range of values is approximately from 1.7E − 308 through 1.7E + 308. Storage size is 8 bytes. All arithmetic operations except modulo are available with float.

Data of type float can include an optional exponent. For float data with an exponential component, enter a number (with or without a decimal point and a positive or negative sign), followed by e or E, followed by an optionally signed integer. The value represented by a float is the product of the first number and 10 to the power of the second number.

real

Is a floating-point column similar to float. This column has 7-digit precision. The range of values is approximately from 3.4E − 38 through 3.4E + 38. Storage size is 4 bytes.


Integer Data

Integer data consists of numeric data with precision to a whole number.

These are the integer datatypes:

int

Is a datatype that holds whole numbers from −2 (31)  (−2,147,483,648) through 2 (31)  − 1 (2,147,483,647). Storage size is 4 bytes.

smallint

Is a datatype that holds whole numbers from −2 (15)  (−32,768) through 2 (15)  − 1 (32,767). Storage size is 2 bytes.

tinyint

Is a datatype that holds whole numbers from 0 through 255. Storage size is 1 byte.


Monetary Data

Monetary datatypes consist of numeric data for decimal currency. Precede monetary data with a dollar sign ($). If there is no dollar sign, SQL Server treats the value as a numeric with a scale of 4. Money values, even when input with a dollar sign, do not return dollar signs in the results.

To represent negative monetary data values, place a minus sign (−) after the dollar sign. You cannot enter monetary data values with commas, although the default print format for monetary data places a comma after every three digits.

When monetary data is displayed, they are rounded up to the nearest cent. All arithmetic operations except modulo are available with monetary datatypes.

Note  With both money and smallmoney, you can store monetary values other than U.S. dollars, but SQL Server does not provide any form of conversion.

These are the monetary datatypes:

money

Is a datatype that stores monetary values from −922,337,203,685,477.5808 through +922,337,203,685,477.5807, with accuracy to a ten-thousandth-of-a-monetary-unit. Money values are represented as double-precision integers. Storage size is 8 bytes.

smallmoney

Is a column that stores monetary values from − 214,748.3648 through +214,748.3647, with accuracy to a ten-thousandth-of-a-monetary-unit. Storage size is 4 bytes. When smallmoney values are displayed, they are rounded up to two places.


Special Datatypes

Special datatypes consist of datatypes with a distinct, or special use.

These are the special datatypes:

bit

Is a datatype that holds either 1 or 0. Integer values other than 1 or 0 are accepted but are always interpreted as 1. Storage size is 1 byte. Multiple bit types in a table can be collected into bytes. For example, 7-bit columns fit into 1 byte; 9-bit columns take 2 bytes. The status column in the syscolumns system table indicates the unique offset position for bit columns.

Columns of type bit cannot be NULL and cannot have indexes on them. Use bit for true/false or yes/no types of data.

timestamp

Is a datatype that is automatically updated every time a row containing a timestamp column is inserted or updated. Browse mode requires timestamp columns in tables that are to be browsed in DB-Library applications. Values in timestamp columns are not datetime data, but binary(8) varbinary(8) data, indicating the sequence of SQL Server activity on the row. A table can have only one timestamp column.

The timestamp datatype has no relation to the system time — it is simply a monotonically increasing counter whose values will always be unique within a database.

If you do not supply a datatype, a column named timestamp is automatically defined as a timestamp datatype. You can create a column named timestamp and assign it another datatype (although assigning another datatype can confuse other users and does not allow browsing with the DB-Library BROWSE functions).

By default, the timestamp datatype is defined as binary(8). If timestamp is used with NOT NULL, the column will be stored as varbinary(8). In client applications, the metadata declares the timestamp as varbinary, regardless of the nullability. The current timestamp value for a database can be selected with the global variable @@DBTS.

user_defined_datatype_name

Is the name of a user-defined datatype created with the sp_addtype system stored procedure. For details, see the sp_addtype system stored procedure.


Text and Image Data

Text and image data consists of character or binary data stored and managed as a linked list of 2K data pages that appear as if they were stored in a table row. A text or image column contains NULL or a pointer (assigned at initialization) to the first text page for that entry, and thus to the entire text or image value. Although text and image datatype definitions do not include length, they do allow null values.

At least one 2K data page is allocated for each non-null text or image data value. To save storage space, you can insert null values until you use the text or image column. Note that any update (even an update that sets the value to NULL) to a text or image column initializes the column; that is, it assigns a valid text pointer and causes the first 2K data page to be allocated.

These are the text and image datatypes:

text

Is a variable-length datatype that can hold as many as 2 (31)  − 1 (2,147,483,647) characters. The text definitions do not include a length, and text values must be surrounded by single quotation marks in an INSERT statement. You can use the LIKE keyword and wildcard characters with text data.

You can explicitly convert text data to char or varchar with the CONVERT function, but the limit is the maximum length of these datatypes, 255 bytes.

image

Is a variable-length datatype that can hold as many as 2 (31)  − 1 (2,147,483,647) bytes of binary data. The image definitions do not include a length, and image values must be preceded by 0x in an INSERT statement. The image datatype cannot be used for variables or parameters in stored procedures.

You can explicitly convert image data to binary or varbinary with the CONVERT function, but the limit is the maximum length of these datatypes (255 bytes).

When image is data entered with an odd number of bytes (but less than 255), it is padded with a leading zero. For example, an insert of "0xaaabb" becomes "0x0aaabb". You cannot insert image values with an odd number of characters greater than 255 bytes.

Using text and image Datatypes

To enter text or image data, the column must first be initialized. Initialization causes a 2K data page to be allocated. Initialize the text or image column by providing non-null data with an INSERT statement or any value (including a NULL) with an UPDATE statement. Then use the READTEXT statement to read text or image data, the WRITETEXT statement to replace text or image data, and the UPDATETEXT statement to modify text or image data.

Using UPDATE to replace existing text and image data with NULL reclaims all allocated data pages except the first page, which remains available for WRITETEXT in the future. To release all storage for the row, first delete the row, and then re-insert the non-text or non-image data.

SELECT statements return text and image data up to the limit specified in the global variable @@TEXTSIZE. The SET statement (TEXTSIZE option) changes this limit on a session basis. The initial value of @@TEXTSIZE is 4K; the maximum value for @@TEXTSIZE is 2 (31)  − 1 (2,147,483,647).

Text and image columns cannot be used:

•	As local variables

•	In ORDER BY, COMPUTE, and GROUP BY clauses

•	In an index

•	In a WHERE clause (with the exception of text data—text data can be specified with the keyword LIKE in a WHERE clause)

Each table that contains text or image columns has a row in the sysindexes system table. The name column in sysindexes uses the form t<tablename>. The indid is always 255. These columns provide information about text storage:

Column	Description
Reserved	Number of pages allocated
Used	Number of pages used
First	Pointer to the first page
Segment	Number of the segment where the object resides


Synonyms

Datatype synonyms are included for ANSI compatibility.

The keyword VARYING complies with ANSI-standards to allow variable-length character or binary strings. The VARYING keyword is valid with the character, char, and binary datatypes. Using the VARYING keyword with any other datatype generates syntax errors.

These are the datatype mappings:

User-defined datatype	Mapped to system datatype
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 = 17	real
float[(n)] for n = 815	float
integer	int
See Also

CREATE PROCEDURE	sp_droptype
CREATE TABLE	sp_help
DECLARE	sp_rename
EXECUTE statement	sp_unbindefault
Functions	sp_unbindrule
SET	Text and Image Manipulation
sp_addtype	Variables
sp_bindefault	Wildcard Characters
sp_bindrule


DBCC Statement

Used to check the logical and physical consistency of a database, check memory usage, decrease the size of a database, check performance statistics, and so on. DBCC is the SQL Server "database consistency checker." DBCC helps ensure the physical and logical consistency of a database; however, DBCC is not corrective. It is recommended that you make periodic checks to ensure the logical and physical consistency of your data.

Syntax

DBCC {
CHECKALLOC [(database_name [, NOINDEX])] |
CHECKCATALOG [(database_name)] |
CHECKTABLE (table_name [, NOINDEX | index_id]) |
CHECKDB [(database_name [, NOINDEX])] |
DBREPAIR (database_name, DROPDB) |
dllname (FREE) |
INPUTBUFFER (spid) |
MEMUSAGE |
NEWALLOC [(database_name [, NOINDEX])] |
OPENTRAN ({database_name} | {database_id})
[WITH TABLERESULTS] |
OUTPUTBUFFER (spid) |
PERFMON |
PINTABLE (database_id, table_id) |
SHOW_STATISTICS (table_name, index_name) |
SHOWCONTIG (table_id, [index_id]) |
SHRINKDB (database_name [, new_size [, 'MASTEROVERRIDE']]) |
SQLPERF ({IOSTATS | LRUSTATS | NETSTATS | RASTATS [, CLEAR]} |
{THREADS} | {LOGSPACE}) |
TEXTALL [({database_name | database_id}[, FULL | FAST])] |
TEXTALLOC [({table_name | table_id}[, FULL | FAST])] |
TRACEOFF (trace#) |
TRACEON (trace#) |
TRACESTATUS (trace# [, trace#...]) |
UNPINTABLE (database_id, table_id) |
UPDATEUSAGE ({0 | database_name} [, table_name [, index_id]]) |
USEROPTIONS}
[WITH NO_INFOMSGS]

where

database_id

Specifies the ID of the database in which the command is to be run. If database_id is not supplied, the current database is assumed.

database_name

Specifies the database in which the command is to be run. If database_name is not supplied, the current database is assumed.

index_id

Specifies the ID of the index to be used. When optional and not specified, the statement is used against all indexes for the specified table.

index_name

Specifies the index to be used.

table_id

Specifies the ID of the table to be used. When optional and not specified, the statement is used against all tables in the current or specified database.

table_name

Specifies the table to be used.

CHECKALLOC [(database_name [, NOINDEX])]

Checks the specified database to make sure that all pages are correctly allocated and used. If no database name is given, CHECKALLOC checks the current database. CHECKALLOC reports on the amount of space allocated and used.

DBCC CHECKALLOC is provided for backward compatibility. The preferred DBCC statement is NEWALLOC. NEWALLOC provides more detailed information and will continue to execute even after errors are encountered. For information on the output provided by NEWALLOC, see the NEWALLOC option.

Important  DBCC CHECKALLOC should be executed while minimal database activity is occurring. If DBCC CHECKALLOC is executed while transactions are in progress, the output may return spurious errors. To ensure that no other users have transactions in progress, set the database to readonly or single user with the sp_dboption system stored procedure.

CHECKCATALOG [(database_name)]

Checks for consistency in and between system tables. For example, CHECKCATALOG makes sure that every type in syscolumns has a matching entry in systypes, that every table and view in sysobjects has at least one column in syscolumns, and that the last checkpoint in syslogs is valid. CHECKCATALOG also reports on any segments that have been defined. If no database name is given, CHECKCATALOG checks the current database.

CHECKTABLE (table_name [, NOINDEX | index_id])

Checks the specified table to see that index and data pages are correctly linked, that indexes are in proper sorted order, that all pointers are consistent, that the data information on each page is reasonable, and that page offsets are reasonable. If the log segment is on its own device, running DBCC CHECKTABLE on the syslogs table reports the log's used and free space.

In SQL Server 6.0, the performance of DBCC CHECKTABLE has been significantly improved by spawning multiple threads to automatically check nonclustered indexes in parallel. Because the table will be loaded in the data cache, each of the simultaneous threads will see an improvement because of an increase in the cache hit ratio.

If an index_id is specified, CHECKTABLE will check only that index.

CHECKDB [(database_name [, NOINDEX])]

Runs the same checks as CHECKTABLE, but on every table in the specified database. If database_name is not supplied, CHECKDB checks the current database.

NOINDEX

Specifies that only the clustered index (the B-Tree and the data itself) is to be checked for user-defined tables. If no clustered index exists, only the data is checked. The NOINDEX option decreases the overall execution time of CHECKALLOC, CHECKDB, CHECKTABLE, and NEWALLOC because it does not check nonclustered indexes for user-defined tables. The NOINDEX option does not affect a check made against the system tables. When used against a system table(s), all clustered and nonclustered indexes are checked.

DBREPAIR (database_name, DROPDB)

Drops the specified, and usually damaged, database. No user, including the person executing the statement, can be using the specified database when this DBCC statement is executed. DBCC DBREPAIR is used for backward compatibility only. To drop a damaged database, use the DROP DATABASE statement. If the DROP DATABASE statement fails, use the sp_dbremove system stored procedure.

dllname (FREE)

Unloads the specified dynamic-link library (DLL) from SQL Server memory. After you execute an extended stored procedure, the DLL is loaded by SQL Server until the server is shut down. This statement also allows a DLL to be unloaded without shutting down SQL Server.

INPUTBUFFER (spid)

Returns one row containing the first 255 bytes of the "current input" buffer for the specified spid (system process ID taken from the sp_who system stored procedure output). This can be used to see the last query sent from the client. For processes that do not contain input streams, an error message is returned. DBCC INPUTBUFFER can be executed only by the system administrator.

MEMUSAGE

Provides detailed reports on memory use. DBCC MEMUSAGE reports three different types of information:

•	How the server's memory was allocated at start-up time.

•	How much memory is used by the 20 largest objects in the buffer cache (including "pinned" tables).

•	How much memory is used by the 12 largest objects in the procedure cache  — stored procedures, triggers, views, rules, and defaults. If multiple copies of an object are in the procedure cache, DBCC MEMUSAGE sums the total memory used by them. Of the multiple copies, some are precompiled versions of the object (trees) and some are compiled versions (plans). DBCC MEMUSAGE shows the sizes of both the trees and plans, and it shows the total trees and plans used to evaluate the largest objects.

NEWALLOC [(database_name [, NOINDEX])]

Checks data and index pages against corresponding extent structures. DBCC NEWALLOC details all table information as well as provides the same summary information provided by DBCC CHECKALLOC, which is retained for compatibility. Unlike DBCC CHECKALLOC, DBCC NEWALLOC will not stop processing if it encounters an error.

DBCC NEWALLOC returns a listing for each allocation unit of the number of extents currently reserved for use by objects, the number of pages marked as being used by objects, and the actual number of pages being used by objects. An allocation unit can hold, at most, 32 database objects. An allocation unit is 512K (0.5 MB) made up of 32 extents (8 2K pages). From this, 512K/16K results in 32 objects. The used pages value and the ref pages value should be equivalent for most, if not all, allocation units. A difference of 7 is possible due to the transaction log. A slightly larger difference is acceptable when text or image data exists within the database.

The number of extents tells whether or not you can create new objects on that allocation unit. To estimate the total amount of space reserved by database objects (tables and indexes), multiply the total number of extents by 16K. To estimate the amount of that space being used by data or index information, multiply the total number of used pages by 2K.

Important  DBCC NEWALLOC should be executed while minimal database activity is occurring. If DBCC NEWALLOC is executed while transactions are in progress, the output may return errors. To ensure that no other users have transactions in progress, set the database to read only or single user with the sp_dboption system stored procedure.

OPENTRAN ({database_name} | {database_id}) [WITH TABLERESULTS]

Displays information on the oldest active transaction and the oldest distributed and nondistributed replicated transactions, if any, within the specified database. When the WITH TABLERESULTS option is not used, the results returned are formatted for easy readability. Use the WITH TABLERESULTS option for a table of results that can be inserted into a table for comparisons.

Note  Results are displayed only if there is an active transaction or if the database contains replication information.

DBCC OPENTRAN is extremely useful in determining whether or not an open transaction exists within the log. When using the DUMP TRANSACTION statement, only the inactive portion of the log can be truncated, so an open transaction could cause the log not to be truncated completely. In earlier versions of SQL Server, all users needed to log off or the server needed to be shut down and restarted in order to clear the uncommitted transactions from the log. With DBCC OPENTRAN, an open transaction can be identified (the spid, the system process ID taken from the sp_who system stored procedure output, is returned) and terminated, if necessary.

OUTPUTBUFFER (spid)

Returns the "current output" buffer in hexadecimal and ASCII format for the specified spid. This can be used to see the results that were sent to the specified client (spid). For processes that do not contain output streams, an error message is returned. DBCC OUTPUTBUFFER can be executed only by the system administrator.

PERFMON

Provides a way to view all three types of SQLPERF statistics in order (IOSTATS, LRUSTATS, and NETSTATS). It takes no parameters.

PINTABLE (database_id, table_id)

Marks a table (data pages, text pages, and index pages) to remain in data cache (once used) until "unpinned." DBCC PINTABLE does not automatically read the table into cache; instead, as pages of the table are accessed and put into cache, they are marked so that they do not get flushed later. Once "pinned," data modifications are fully logged and the table can be recovered. Although this can provide performance improvements for some tables, it should be used with caution. As the table is read into cache, the size of the table is limited only by the available cache. If you are not careful, a large table could consume all the data cache, the server need to be restarted, and then the table unpinned. For more information, see DBCC UNPINTABLE, later in this section.

SHOW_STATISTICS (table_name, index_name)

Displays all the statistical information in the distribution page for an index (index_name) on a specified table (table_name). 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 would be useful to the optimizer. The results returned are based on distribution steps of the index. To understand the output of SHOW_STATISTICS, see the examples, later in this section.

To see the last date the statistics were updated, use the system function STATS_DATE. For details, see the Functions topic.

SHOWCONTIG (table_id, [index_id])

Traverses the page chain at the leaf level of the specified index (index_id) or data level (if only table_id is specified) and 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 the normal distribution of these modifications are not usually equally distributed among the records of the table, the "fullness" of each page will begin to vary over time. For queries that scan part of or all of a table, this can cause additional page reads. When the table is heavily fragmented, you can 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 will "compact" the data such that data pages are essentially full again; however, the level of "fullness" can also be configured with the FILLFACTOR option.

To find the index_id of a nonclustered index, specify the nonclustered index name (nc_index_name) in the following query:

SELECT indid FROM sysindexes
WHERE name = 'nc_index_name'

DBCC SHOWCONTIG returns these statistics:

Statistic	Description
Pages Scanned	Number of pages in the table or index.
Extent Switches	The number of times the DBCC statement left an extent while it was traversing the pages of the extent.
Avg. Pages per Extent	The 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 below 100, some fragmentation exists. The Scan Density is a percentage.
Avg. Bytes free per page	The average number of free bytes on the pages scanned. The higher the number, the less full the pages are; lower numbers are better. Be aware, however, that this number is also affected by row size, so a large row size may result in a higher number.
Avg. Page density (full)	The average page density shows how full a page is (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.
Overflow Pages	This value is for internal use.
Disconnected Overflow Pages	This value is for internal use.
SHRINKDB (database_name [, new_size [, 'MASTEROVERRIDE']])

When specified with only the database_name parameter, DBCC SHRINKDB returns the minimum size to which this database can shrink, and it lists all objects and indexes that are preventing you from shrinking it further. You cannot shrink the database to a size smaller than the one returned; use caution and drop or move the database objects until the returned size is acceptable.

When new_size is specified, DBCC SHRINKDB shrinks the size of the specified database to the value, as specified in 2K pages by the new_size parameter. DBCC SHRINKDB may shrink both the data and log portions of the database. To change the size of only the data or the log, shrink the entire database first and then use the ALTER DATABASE statement to increase the size of the data or log portion of the database.

To shrink a user database, the database must be set to single user mode. Use the sp_dboption system stored procedure to set this database option. After setting the database to single-user mode, it is recommended that you dump both the master database and the database you are shrinking, prior to using DBCC SHRINKDB.

To shrink the master or tempdb databases you must start the server in single-user mode (use the sqlservr command-line executable with the -m parameter).

Important  The database cannot be shrunk beyond either the size of the model database or to a size that is not a valid increment of allocation units. That is, new_size must be equal to or greater than the minimum size as returned by DBCC SHRINKDB plus any number of 512-byte increments (each of which is 256 2K pages). For example, if DBCC SHRINKDB returned a message that the 'Database can be shrunk to 5376 pages', the database can be shrunk to 5376 (10.5 MB), 5632 (11 MB), 5888 (11.5 MB), and so on. For more information, see the "Shrink a Database" example, later in this section.

After successfully shrinking a database to the desired size, back up both the master database and the database that has been shrunk.

DBCC SHRINKDB is fully logged and recoverable except when used on the master database. The MASTEROVERRIDE clause is required when decreasing the size of the master database. However, use caution if you need to shrink the size of the master database, because recovery could fail if the system fails while shrinking the master database. Back up the master database prior to shrinking it. You must be the system administrator or database owner to execute this statement.

SQLPERF ({IOSTATS | LRUSTATS | NETSTATS | RASTATS [, CLEAR]}
{THREADS} {LOGSPACE})

Can provide information about performance statistics. Four performance options are available for this statement: IOSTATS, LRUSTATS, NETSTATS, and RASTATS. You can view replication statistics by using the sp_distcounters (subscription server statistics) and sp_replcounters (publication server statistics) system stored procedures.

IOSTATS generates the I/O statistics since the server was last started or since the statistics were last cleared.

LRUSTATS generates statistics about cache use since the server was last started or since the statistics were last cleared. (LRU stands for "least recently used" and is the algorithm used by the SQL Server cache manager.)

NETSTATS provides statistics about network use.

RASTATS provides statistics about Read Ahead.

The CLEAR option clears the statistics and does not display them.

The following list describes the statistics generated for each option:

IOSTATS

Statistic	Definition
Batch Average Size	The average number of pages written in a batch.
Batch Max. Size	The maximum number of simultaneous outstanding physical I/Os.
Batch Writes	The number of times multiple pages were written to disk in a batch.
Log Flush Average	Log flush requests per physical write.
Log Flush Requests	Number of requests to flush the log to disk.
Log Logical IO Average	Logical pages written per physical write.
Log Logical Page IO	Logical page I/O for transaction log.
Log Physical IO	Physical I/O for transaction log.
Log Writes	Total writes for the log.
Page Reads	The number of 2K pages read from disk (physical reads).
Reads Outstanding	The number of read requests issued to the operating system that have not been completed.
Single Page Writes	The number of 2K pages written individually to disk (physical writes, including log writes).
Transactions	The number of Transact-SQL batches executed. This value is useful in computing ratios involving log write numbers.
Transactions/Log Write	The number of transaction records written to disk during each physical log write.
Writes Outstanding	The number of write requests issued to the operating system that have not completed.
LRUSTATS

Statistic	Definition
Cache Flushes	The number of times a page needed to be flushed from cache to make room for another page.
Cache Hit Ratio	The percentage of times a data page was found in the cache.
Cache Size	The total number of pages in the cache.
Free Page Scan (Avg.)	The average number of buffer pages that had to be scanned in order to find a free page.
Free Page Scan (Max.)	The maximum number of buffer pages that had to be scanned in order to find a free page.
Free Buffers	The number of buffers currently on the free list.
Min. Free Buffers	The lazy writer will attempt to maintain at least this number of buffers on the free list.
DBCC SQLPERF (LRUSTATS) statistics are useful in determining whether you have a large enough cache in your system. After running SQL Server for a day or two, check the Cache Flushes and Average Free Page Scan. For optimal performance, Average Free Page Scan should be less than 10 and Cache Flushes should be less than 100. If you get higher numbers, it means that the SQL Server cache is not big enough to hold your working set. You can improve your server performance by increasing its cache size (adding more memory). If these numbers are below the recommended limits, it means that adding more memory to your system will not make a large difference in performance and that you have a cache big enough to cover the server's working set.

NETSTATS

Statistic	Definition
Max. Worker Threads	The highest number of worker threads that serviced the command queue since the network application was started or since the statistics were cleared.
Network Reads	The total number of reads from the network.
Network Writes	The total number of writes to the network.
Worker Threads	The current number of worker threads servicing the command queue.
RASTATS

Statistic	Definition
RA Pages Found in Cache	How many pages the RA Manager found already in the cache when trying to perform scans.
RA Pages Placed in Cache	How many pages were brought into the cache by the RA Manager.
RA Physical IO	How many 16K reads were done by the RA Manager.
Used Slots	How many RA slots are being used by active queries. Note that a single query may use multiple RA slots.
SQLPERF (THREADS)

Provides a mechanism to map the Windows NT system thread ID to a SQL Server spid. This allows you to use Performance Monitor to monitor a specific user in SQL Server by monitoring the corresponding thread on the system. This statement also returns the login name, the number of I/Os, and CPU and MEMUSAGE totals.

SQLPERF (LOGSPACE)

Returns the percentage of log space used at the time the statement is executed. This statement can be used only on a log that is on a separate device from its database.

TEXTALL [({database_name | database_id}[, FULL | FAST])]

Selects tables in the database that have text or image columns and runs TEXTALLOC on them. To select the speed at which the report is generated, choose FULL (all allocation pages in the database will be checked by the report) or FAST (does not generate an allocation report, but checks the linkage of the text chains and verifies that the pages in the chain are allocated). The default is FULL.

TEXTALLOC [({table_name | table_id}[, FULL | FAST])]

Checks the allocation of text or image columns for one table. To select the speed at which the report is generated, choose FULL (all allocation pages in the database will be looked at by the report) or FAST (does not generate an allocation report, but checks the linkage of the text chains and verifies that the pages in the chain are allocated). The default is FULL.

TRACEOFF (trace#)

Turns off the specified trace flag trace#. For a list of trace flags, see the Trace Flags topic.

TRACEON (trace#)

Turns on the specified trace flag trace#.

TRACESTATUS (trace# [, trace#...])

Displays the status for the specified trace flag(s). Can be 1 (on) or 0 (off). You can specify more than one trace flag by separating the numbers with a comma. If you specify − 1 for trace#, status information about all trace flags currently turned on will be returned.

UNPINTABLE (database_id, table_id)

Marks the table as no longer being RAM resident; however, the table will remain in cache until it is aged out of cache (and flushed to disk). "Pinning" a table is not recommended for widespread use; see DBCC PINTABLE, earlier in this section.

UPDATEUSAGE ({0 | database_name} [, table_name [, index_id]])

Reports and corrects inaccuracies in the sysindexes table that may result in incorrect space usage reports by the sp_spaceused system stored procedure. This command corrects the rows, used, reserved, and dpages columns of the sysindexes table for any clustered indexes on objects of the type U (user-defined table) or S (system table). Size information is not maintained for nonclustered indexes. It can be used to synchronize space usage counters in sysindexes, which will result in accurate usage information being returned. When 0 is used instead of the database_name, the update is performed in the current database.

When processing, UPDATEUSAGE acquires a shared table lock on the table being processed, so updates to the sysindexes row for syslogs can be performed only if the database is in single user mode and when the syslogs table is specified. This prevents any logging during the update and ensures accurate changes. All other changes to sysindexes are fully logged.

If there are no inaccuracies in sysindexes, DBCC UPDATEUSAGE will return no data. Otherwise, data will be returned that shows you what rows and columns are being updated in sysindexes.

Note  This command may take some time to run if you run it on large tables or databases, so it should typically be used only when you suspect incorrect values returned by the sp_spaceused system stored procedure or via a timed operation to run during off hours.

USEROPTIONS

Returns the list of SET options that are active (or set) for the current connection. It takes no parameters. For details and a listing of the session options available, see the SET statement.

WITH NO_INFOMSGS

Prevent the printing of informational messages (severity 1 through 10). This helps to determine real problems when using verbose commands such as DBCC CHECKDB.

Permission

Permission to execute the DBCC statement varies for each of the DBCC options. Permission is not transferable. DBCC permissions are:

DBCC option	Permission defaults to
CHECKALLOC	SA or DBO
CHECKCATALOG	SA or DBO
CHECKDB	SA or DBO
CHECKTABLE	SA, DBO, or the table owner
DBREPAIR	SA only
dllname	SA only
INPUTBUFFER	SA only
MEMUSAGE	Any user
NEWALLOC	SA or DBO
OPENTRAN	SA or DBO
OUTPUTBUFFER	SA only
PERFMON	SA only
PINTABLE	SA only
SHOW_STATISTICS	SA, DBO, or the table owner
SHOWCONTIG	SA or DBO
SHRINKDB	SA or DBO
SQLPERF	Any user
TEXTALL	SA or DBO
TEXTALLOC	SA or DBO
TRACEOFF	SA only
TRACEON	SA only
TRACESTATUS	SA only
UNPINTABLE	SA only
UPDATEUSAGE	SA or DBO
USEROPTIONS	Any user
Examples

A.	Check the Allocation Units (CHECKALLOC)

This example runs the DBCC CHECKALLOC command against the pubs database.

DBCC CHECKALLOC(pubs)

go

Checking pubs
Alloc page 0 (# of extent=32 used pages=58 ref pages=58)
Alloc page 256 (# of extent=26 used pages=37 ref pages=37)
Alloc page 512 (# of extent=14 used pages=40 ref pages=40)
Alloc page 768 (# of extent=1 used pages=8 ref pages=2)
Alloc page 1024 (# of extent=1 used pages=0 ref pages=0)
Alloc page 1280 (# of extent=1 used pages=0 ref pages=0)
Total (# of extent=75 used pages=143 ref pages=137) in this database
DBCC execution completed. If DBCC printed error messages, see your System Administrator.

This database contains six allocation units of 256 2K pages (0.5 MB) each, giving 1536 2K pages in all (3 MB). Of that 3 MB, 88 extents (88 * 16K = 1408K), is reserved and 215 pages (or 215 * 2K = 430K) are used by data and indexes. The reserved 88 extents include objects that have been created but not yet completely populated with data. Used pages refer to those pages that do contain actual data or index pages.

B.	Check a Single Table (CHECKTABLE)

This example runs the DBCC CHECKTABLE command against all indexes and data on the employee table in the pubs database.

USE pubs

go

DBCC CHECKTABLE(employee)

go

Checking employee
The total number of data pages in this table is 2.
Table has 43 data rows.
DBCC execution completed. If DBCC printed error messages, see your System Administrator.

C.	Check a Table with NOINDEX (CHECKTABLE)

This example skips all of the nonclustered indexes.

USE pubs

go

DBCC CHECKTABLE(employee, NOINDEX)

go

Checking employee
WARNING: NOINDEX option of 'CHECKTABLE' being used, checks on non-system indexes will be skipped
The total number of data pages in this table is 2.
Table has 43 data rows.
DBCC execution completed. If DBCC printed error messages, see your System Administrator.

D.	Check the Transaction Log (CHECKTABLE)

This example runs the DBCC CHECKTABLE command against the syslogs table within the sales database.

USE sales

go

DBCC CHECKTABLE(syslogs)

go

Checking syslogs
The total number of data pages in this table is 145.
*** NOTICE:  Space used on the log segment is 0.29 Mbytes, 4.72.
*** NOTICE:  Space free on the log segment is 5.85 Mbytes, 95.28.
Table has 3194 data rows.
DBCC execution completed. If DBCC printed error messages, see your System Administrator.

E.	Report Memory Usage (MEMUSAGE)

The report given by DBCC MEMUSAGE is broken down into three parts. Only 3 of the 20 procedures are shown here.

DBCC MEMUSAGE

go

Memory Usage:

            Meg.         2K Blks           Bytes

      Configured Memory:  8.0000	    4096	 8388608
              Code size:  1.7166	     879	 1800000
      Static Structures:  0.2385	     123	  250064
                  Locks:  0.2480	     127	  260000
           Open Objects:  0.1068	      55	  112000
         Open Databases:  0.0031	       2	    3220
     User Context Areas:  0.8246	     423	  864688
             Page Cache:  3.3040	    1692	 3464544
           Proc Headers:  0.0796	      41	   83448
        Proc Cache Bufs:  1.3379	     685	 1402880

Buffer Cache, Top 20:

   DB Id	 Object Id	Index Id	2K Buffers

       4	         5	       0	      26
       1	        56	       0	      20
       1	         	1       0	      16
       1	 576005083	       0	      11
       4	         3	       0	      10
       4	        99	       0	       6
       1	         2	       0	       5
       1	         1	       2	      17
       1	         5	       2	       4
       1	       399	       0	       4
       4	         1	       0	       4
       4	         2	       0	       4
       1	         3	       0	       3
       4	         1	       0	       3
       4	         6	       0	       3
       4	 192003715	       0	       3
       1	         5	       0	       2
       1	        45	       1	       2
       2	         2	     255	       2
       2	        99	       0	       2

Procedure Cache, Top 5:

Procedure Name: sp_helpconstraint sp_server_info
Database Id: 1
Object Id: 1516532436
Version: 1
Uid: 1
Type: stored procedure
Number of trees: 0
Size of trees: 0.000000 Mb, 0.000000 bytes, 0 pages
Number of plans: 1
Size of plans: 0.002974 Mb, 3118.000000 bytes, 42 pages

Procedure Name: CA only
Database Id: 4
Object Id: 1104006964
Version: 0
Uid: 1
Type: stored view
Number of trees: 1
Size of trees: 0.001659 Mb, 1740.000 bytes, 1 pages
Number of plans: 0
Size of plans: 0.000000 Mb, 00000.000000 bytes, 0 pages

Procedure Name: categories
Database Id: 4
Object Id: 1168007192
Version: 0
Uid: 1
Type: stored view
Number of trees: 1
Size of trees: 0.001883 Mb, 1974.00000 bytes, 1 pages
Number of plans: 0
Size of plans: 0.000000 Mb, 0.000000 bytes, 0 pages
.
.
.

F.	View Index Statistics (SHOW_STATISTICS)

This table is a copy of the authors table created in the pubs database. The authors table includes a clustered index on the primary key (au_id) column and a nonclustered index on the composite key (au_lname, au_fname). This example shows the DBCC output for each index after 1500 rows are inserted and the statistics have been updated.

The first example shows statistics for the clustered primary key index on the au_id column. Because a PRIMARY KEY constraint enforces uniqueness, the selectivity of this index is highly selective (only 1 row will match). In this case, the Density * Rows is 1.0, showing that there is only 1 match. If a query were executed against the authors table using a WHERE clause specifying equality with an au_id, this index would be used.

DBCC SHOW_STATISTICS (authors, UPKCL_auidind)

go

 Updated                  Rows    Steps       Density
 -------------------- -------- -------- -------------
 Apr 17 1995  1:22PM      1520      109      0.000658

(1 row affected)

 All density          Columns
 -------------------- ------------------------------
             0.000658 au_id

(1 row affected)

 Steps
 -----------
 100-10-1000
.

.

.

 724-08-9931

(109 rows affected)

DBCC execution completed. If DBCC printed error messages, see your
System Administrator.

The second example shows statistics for the nonclustered index on the au_lname and au_fname columns. Because this index is not unique, the selectivity is based on the distribution of the data and the likelihood of duplicates. In this case, the Density * Rows is 20.8, showing that there are roughly 21 duplicates based on the au_lname, column alone, not counting any values in more than one step (values with an extremely high number of duplicates and low selectivity).

The All Density is more accurate and shows the selectivity of each column, including those that are more than two steps (lowering the selectivity further and emphasizing how a large number of duplicates can affect the effectiveness of an index). Looking at the au_lname column only, the selectivity is not very high (48 potential duplicates) and an index might be used; however, the selectivity of au_lname, au_fname is much higher (only 3 potential duplicates). If both the au_lname and au_fname are specified with a WHERE clause, it is likely that this index will be used.

DBCC SHOW_STATISTICS (authors, aunmind)

go

 Updated                  Rows    Steps       Density
 -------------------- -------- -------- -------------
 Apr 17 1995  1:22PM      1520       39      0.013674

(1 row affected)

 All density          Columns
 -------------------- ------------------------------
             0.031665 au_lname
             0.002028 au_lname, au_fname

(2 rows affected)

 Steps
 ----------------------------------------
 Abbott
.

.

.

 Xenon

(39 rows affected)

DBCC execution completed. If DBCC printed error messages, see your
System Administrator.
The inserts are performed and DBCC is executed again.

G.	Shrink a Database (SHRINKDB)

This example defines the steps to ensure a proper decrease in size of a database:

1.	Set the database to single-user mode using the sp_dboption system stored procedure.

2.	Change your current database to the database you want to shrink.

3.	Verify how small you can make the database. (Run DBCC SHRINKDB without specifying a new_size.)

4.	Shrink the database.

USE master

go

sp_dboption 'sales', 'single user', true

go

USE sales

go

DBCC SHRINKDB(sales)

go

Current size of database Size database can be shrunk to
------------------------ ------------------------------
1536                     1024

(1 row(s) affected)

DBCC execution completed. If DBCC printed error messages, see your System Administrator.

DBCC SHRINKDB reported a minimum size of 5376 pages. Because the absolute minimum is not always necessary, shrink the sales database down to a new size of 12 MB.

DBCC SHRINKDB(sales, 6144)

go

DBCC SHRINKDB running on database "sales"...
DBCC execution completed. If DBCC printed error messages, see your System Administrator.

See Also

DROP DATABASE	sp_configure
RECONFIGURE	sp_helpdb


DECLARE Statement

Defines the name and type of local variables for a batch or procedure and defines cursors.

Syntax

DECLARE @variable_name datatype
[, @variable_name datatype...]

where

@variable_name

Is the name of the variable. Variable names must conform to the rules for identifiers, except variable names use the "at" symbol (@) to signify a variable name.

datatype

Is a system or user-defined datatype. For information on available system datatypes, see the Datatypes topic. For information on creating user-defined datatypes, see the sp_addtype system stored procedure.

Example

This example is a stored procedure (reptq3) from the pubs database. This stored procedure uses three variables declared as input parameters.

CREATE PROCEDURE reptq3 @lolimit money, @hilimit money,

@type char(12)

AS

SELECT pub_id, type, title_id, price

FROM titles

WHERE price > @lolimit
AND price < @hilimit
AND type = @type OR type LIKE '%cook%'

ORDER BY pub_id, type

COMPUTE count(title_id) BY pub_id, type

See Also

Batches	PRINT
Control-of-Flow Language	RAISERROR
CREATE PROCEDURE	SELECT
Cursors	UPDATE
Datatypes	Variables
EXECUTE


DELETE Statement

Removes rows from a table.

Syntax

DELETE [FROM] {table_name | view_name}
[WHERE clause]

where

table_name | view_name =

[[database_name.]owner.]{table_name | view_name}

Specifies the table or view used in the DELETE statement. If the table or view exists in another database, use a fully qualified table_name or view_name (database_name.owner.object_name).

Because DELETE can affect only one base table at a time, you cannot use DELETE with a view that has a FROM clause naming more than one table.

WHERE clause =

WHERE {search_conditions | CURRENT OF cursor_name}

Is used to perform a searched delete (using search_conditions) or a positioned delete (using CURRENT OF cursor_name). When no WHERE clause is given in the DELETE statement, all rows in the table are removed. The table itself, along with its indexes, constraints, and so on, remains in the database.

search_conditions

Specifies the criteria for a searched delete. For details, see the Search Conditions topic.

The IDENTITYCOL keyword can be used in the place of a column_name that has the IDENTITY property. For more information, see the CREATE TABLE statement.

CURRENT OF cursor_name

Specifies the criteria for a positioned delete against the current row within the specified cursor. Cursor operations affect only the single row on which the cursor is positioned. For details, see the Cursors topic.

Remarks

The TRUNCATE TABLE statement and the DELETE statement without a WHERE clause are functionally equivalent, but TRUNCATE TABLE is faster. The DELETE statement removes rows one at a time and logs each row deletion; the TRUNCATE TABLE statement deletes all rows by logging only the page deallocations. Both DELETE and TRUNCATE TABLE reclaim the space occupied by the data and its associated indexes.

Transact-SQL Extension for the DELETE Statement

In addition to the syntax shown earlier, Transact-SQL includes a feature that allows you to select data from a table or tables and delete corresponding data from the first-named table. The functionality provided is similar to that of using a correlated subquery as a search_condition in the WHERE clause as a standard update.

Transact-SQL extension syntax:

DELETE [FROM] {table_name | view_name}
[FROM {table_name | view_name}
[, {table_name | view_name}]...]
[..., {table_name16 | view_name16}]]
[WHERE clause]

where

FROM

Lets you name more than one table or view to use with a WHERE clause to specify which rows to delete. The additional FROM clause allows you to delete rows from one table based on data stored in other tables, giving you similar functionality to a correlated subquery (SELECT statement in the WHERE clause).

For an example of the differences between correlated subqueries and this Transact-SQL extension, see the examples later in this section.

Permission

DELETE permission defaults to the table owner, who can transfer it to other users.

Examples

A.	DELETE with No Parameters

This example deletes all rows from the authors table.

DELETE authors

B.	DELETE a Set of Rows

Because au_lname may not be unique, this example deletes all rows where au_lname is McBadden.

DELETE FROM authors

WHERE au_lname = 'McBadden'

C.	DELETE 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 that is currently fetched from the cursor.

DELETE FROM authors

WHERE CURRENT OF complex_join_cursor

D.	DELETE Based on a Subquery or Using the Transact-SQL Extension

This example shows the Transact-SQL extension used to delete records from a base table based on a join or correlated subquery. The first DELETE shows the ANSI-compatible subquery solution, and the second DELETE shows the Transact-SQL extension.

/* ANSI-Standard subquery */
DELETE FROM titleauthor
WHERE au_id IN
(SELECT a.au_id
FROM authors a, titles t, titleauthor ta
WHERE a.au_id = ta.au_id
AND ta.title_id = t.title_id
AND t.title LIKE '%computers%')

/* Transact-SQL extension */
DELETE FROM titleauthor
FROM authors a, titles t
WHERE a.au_id = titleauthor.au_id
AND titleauthor.title_id = t.title_id
AND t.title LIKE '%computers%'

See Also

CREATE TABLE	INSERT
CREATE TRIGGER	SELECT
Cursors	TRUNCATE TABLE
DROP TABLE	UPDATE
DROP TRIGGER


DISK INIT Statement

Creates a device on which a database or multiple databases can be placed. A device is an operating-system file that SQL Server pre-allocates for database use.

Syntax

DISK INIT
NAME = 'logical_name',
PHYSNAME = 'physical_name',
VDEVNO = virtual_device_number,
SIZE = number_of_2K_blocks
[, VSTART = virtual_address]

where

NAME

Is the logical name of the database device. Logical names must correspond to the rules for identifiers and must be enclosed with single quotation marks ('). Identifiers exceeding 30 characters are accepted but truncated to 30 characters. This name is recorded in the name column of the master..sysdevices table, and is used in the CREATE DATABASE, ALTER DATABASE, DISK RESIZE, and many other SQL statements.

PHYSNAME

Is the drive letter, full path, and filename of the database device. Paths for database devices must follow the rules for the operating-system paths and filenames. They must be enclosed with single quotation marks (').

VDEVNO

Is the virtual device number. This number must be unique among the database devices associated with SQL Server. Values can be from 1 through 255; 0 is reserved for the MASTER database device.

SIZE

Specifies the size, in 2K blocks, of the database device.

If you are planning to use the new database device to create a new database, the minimum size is 1 MB.

VSTART

Is the starting virtual address or the starting offset in 2K blocks. The value for VSTART should be 0 (the default). Reset VSTART only if instructed to do so.

Remarks

The DISK INIT statement takes advantage of the fact that Windows NT creates a file either by zeroing out all bytes (FAT) or by presenting the application immediately with a zeroed image of the file (NTFS).

Execute DISK INIT once for each new database device. Each time DISK INIT is executed, a row is added to the master..sysdevices table. A new database device does not automatically become part of the pool of default database storage. Assign default status to a database device with the sp_diskdefault system stored procedure.

Because entries are made in the master..sysdevices table, it is important to back up the master database with the DUMP DATABASE statement after each use of DISK INIT.

User databases are assigned to specific database devices with the optional ON database_device clause of the CREATE DATABASE or ALTER DATABASE statement, or they are placed on a default device(s).

The LOG ON extension to CREATE DATABASE is the preferred method for putting a database's transaction log (that is, the sylogs system table) on a device different from the one on which the data is stored. Alternatively, you can name at least two database devices when you create the database and then execute the sp_logdevice system stored procedure. ALTER DATABASE can also be used at any point to add another database device and migrate the log to it with the sp_logdevice system stored procedure.

Note  The LOG ON extension in CREATE DATABASE immediately moves the entire log to a separate device. The sp_logdevice method retains part of the system log on the original database device until a transaction completes the transfer. Using the LOG ON extension is preferable to using the sp_logdevice system stored procedure.

For a report on all database devices and dump devices on your system, execute the sp_helpdevice system stored procedure.

Before removing a database device with the sp_dropdevice system stored procedure, you must first drop all existing databases on that database device.

Note  The sp_dropdevice system stored procedure does not remove the operating-system file. The physical file can be deleted by using the standard operating-system del command.

After dropping a database device, you can create a new one with the same information (using DISK INIT) as long as you delete the physical file first.

To successfully complete disk initialization, the SQL Server process must have the appropriate operating-system permissions to create the file as named by the PHYSNAME parameter. To see the account under which SQL Server is running, use the Control Panel Services icon for the MSSQLServer service.

Permission

DISK INIT permission defaults to the system administrator and is not transferable.

Examples

Define Database Devices

This example creates a 12 MB (6144 2K pages) device called DEVICE1. This device is created in the same directory as the default SQL Server 6.0 MASTER device.

DISK INIT

NAME = 'DEVICE1',

PHYSNAME = 'c:\sql60\data\device1.dat',

VDEVNO = 1,

SIZE = 6144

This example creates a 16 MB (8192 2K pages) device called DEVICE2. This device is created on a different logical drive from DEVICE1. The SQLDATA directory must exist prior to the execution of this statement.

DISK INIT

NAME = 'DEVICE2',

PHYSNAME = 'd:\sqldata\device2.dat',

VDEVNO = 2,

SIZE = 8192

This example creates a 125 MB (64,000 2K pages) device called DEVICE3. This device is created on a third logical drive. The SQLDATA directory must exist prior to the execution of this statement.

DISK INIT

NAME = 'DEVICE3',

PHYSNAME = 'e:\sqldata\device3.dat',

VDEVNO = 3,

SIZE = 64000

See Also

ALTER DATABASE	LOAD
CREATE DATABASE	sp_diskdefault
DISK REFIT	sp_dropdevice
DISK REINIT	sp_helpdevice
DISK RESIZE	sp_logdevice
DUMP


Disk Mirroring

Note  In the future, support for SQL Server device mirroring may be discontinued. It is recommended that you use either the mirroring functionality of the Microsoft Windows NT operating system, or hardware-based mirroring if your hardware supports it. For more information about Windows NT mirroring, see the Microsoft Windows NT operating system documentation.

Disk mirroring allows a software mirror of a user database device or the MASTER database device to add to the recoverability options available for the database or databases that reside on that device. When a database resides on multiple devices, mirror all the devices to ensure that the whole database is mirrored. If a database device fails, its mirror immediately takes over; database users are unaffected and can continue to access data without interruption.

You can mirror or unmirror database devices without shutting down SQL Server. Disk mirroring does not interfere with ongoing activities in the database.

For even greater protection, always put the log portion of the database on a separate device from the data portion (see the LOG ON clause of the CREATE DATABASE statement). Whenever possible, this device should also be on a separate physical device.

For a report on all the SQL Server devices on your system (user database devices and their mirrors, as well as dump devices), execute the sp_helpdevice system stored procedure.

SQL Server device mirroring for all user-defined devices consists of three statements (discussed in the following sections).

•	DISK MIRROR

•	DISK UNMIRROR

•	DISK REMIRROR

Software device mirroring can be set up by the system administrator.

Note  To mirror the MASTER device, use the -r option (with the sqlservr command-line executable) and the name of the mirror when you restart SQL Server. To add the -r option as a parameter, choose the Parameters button in the Set Server Options dialog box provided with the SQL Setup Utility. For more information, see Microsoft SQL Server Setup.

Other SQL Server fault-tolerance options include hardware fault tolerance and operating-system software fault tolerance. For more information, see the Microsoft SQL Server Administrator's Companion.


DISK MIRROR Statement

Note  In the future, support for SQL Server device mirroring may be discontinued. It is recommended that you use either the mirroring functionality of the Microsoft Windows NT operating system, or hardware-based mirroring if your hardware supports it. For more information about Windows NT mirroring, see the Microsoft Windows NT operating system documentation.

Creates a software image of the SQL Server device.

Syntax

DISK MIRROR
NAME = 'logical_name',
MIRROR = 'physical_name'
[, WRITES = {SERIAL | NOSERIAL}]

where

NAME

Is the logical name of the database device that you want to mirror.

MIRROR

Is the drive letter and full path of the database mirror image (file) that is to be your secondary device. The path must be enclosed with single quotation marks ('). The physical name of this device goes in the mirrorname column of the sysdevices table. A device and its mirror together constitute one logical device. It cannot be an existing file.

WRITES

Enforces serial writes to the devices. In the default case (SERIAL), the write to the primary database device is guaranteed to finish before the write to the secondary device begins. Assuming that the primary and secondary devices are on different physical devices, serial writes can ensure that at least one of the disks may be unaffected by a power failure. SQL Server always performs serial writes. The NOSERIAL parameter is retained for compatibility with SQL Server on other platforms.

Remarks

The system administrator must be using the master database to use the DISK MIRROR statement.

Permission

DISK MIRROR permission defaults to the system administrator and is not transferable.


DISK UNMIRROR Statement

Note  In the future, support for SQL Server device mirroring may be discontinued. It is recommended that you use either the mirroring functionality of the Microsoft Windows NT operating system, or hardware-based mirroring if your hardware supports it. For more information about Windows NT mirroring, see the Microsoft Windows NT operating system documentation.

Temporarily pauses software mirroring for the SQL Server device. Often this is useful when large nonlogged operations are occurring against the database and when a database backup (using the DUMP statement) will be performed after the nonlogged operations are completed.

Syntax

DISK UNMIRROR
NAME = 'logical_name'
[, SIDE = {PRIMARY | SECONDARY}]
[, MODE = {RETAIN | REMOVE}]

where

NAME

Is the logical name of the database device that you want to unmirror.

SIDE

Indicates which device of the mirrored pair you want to disable with DISK UNMIRROR. PRIMARY refers to the original device created by DISK INIT. SECONDARY refers to the mirror device created with DISK MIRROR. The default is SECONDARY. Use the sp_helpdevice system stored procedure to display a list of all devices.

MODE

Determines whether the unmirroring is temporary or permanent. If set to RETAIN, the following conditions are true:

•	I/O is directed only at the device not being unmirrored by this statement.

•	The status column of sysdevices is altered to indicate that mirroring has been deactivated.

•	The entries for primary and secondary disks in the phyname and mirrorname columns are not altered.

RETAIN is the default. RETAIN mimics what happens when failover is activated automatically. Failover occurs when the other device of the mirrored pair takes over. Set RETAIN when you plan to remirror the database device later in the same configuration.

If set to REMOVE, the following conditions are true:

•	The status column is altered to indicate that mirroring is to be ignored.

•	The name of the secondary device in the mirrorname column replaces the phyname column if the primary device is the one being deactivated.

•	The mirrorname column is set to NULL.

Note  REMOVE does not remove an operating-system file that had been used as a mirror device.

Permission

DISK UNMIRROR permission defaults to the system administrator and is not transferable.


DISK REMIRROR Statement

Note  In the future, support for SQL Server device mirroring may be discontinued. It is recommended that you use either the mirroring functionality of the Microsoft Windows NT operating system, or hardware-based mirroring if your hardware supports it. For more information about Windows NT mirroring, see the Microsoft Windows NT operating system documentation.

Resumes software mirroring for the SQL Server device.

DISK REMIRROR
NAME = 'logical_name'

where

NAME

Is the logical name of the database device that you want to discontinue.

Remarks

When a mirrored device is remirrored, it begins by copying all pages from the source device to the mirror device. For large devices, this may take quite some time to complete.

Permission

DISK REMIRROR permission defaults to the system administrator and is not transferable.

Disk Mirroring
Examples

A.	Mirror a Device

This example creates a software mirror for the database device DEVICE8.

In this example, the mirror is written to a file on different logical drive (for better data recoverability, this should also be a separate physical drive).

DISK MIRROR

NAME = 'DEVICE8',

MIRROR = 'g:\sqlimage\device8.mir'

B.	Unmirror a Device

This example suspends software mirroring for DEVICE8.

DISK UNMIRROR

NAME = 'DEVICE8'

C.	Remirror a Device

This example resumes software mirroring for DEVICE8.

DISK REMIRROR

NAME = 'DEVICE8'

See Also

CREATE DATABASE	sp_helpdevice
DISK INIT	sqlservr command-line Executable


DISK REFIT Statement

Restores usage information from the system tables when a device exists (the file is present) but the entries in the sysusages table no longer exist. This occurs after a damaged master database is restored and the master database is incomplete (databases and devices were added or altered since the last backup of the master database).

Syntax

DISK REFIT

Remarks

DISK REFIT is executed after DISK REINIT. DISK REFIT uses information in the sysdevices table to rebuild the sysusages and sysdatabases tables. To run DISK REFIT, SQL Server must be started in single-user mode and the system administrator must be using the master database. For information on starting the server in single-user mode, see the Utilities  and Executables topic.

After using DISK REFIT, stop and restart SQL Server.

Note  If this statement is not immediately run after the DISK INIT statement, DISK INIT will fail. To see the complete recovery steps (DISK REINIT and then DISK REFIT), see the DISK REINIT statement examples.

Permission

Execute permission defaults to the system administrator and is not transferable.

See Also

DISK INIT	sp_helpdevice
DISK REINIT


DISK REINIT Statement

Restores the device entries to the system tables when a device exists (the file is present) and the entry in the sysdevices table no longer exists. This occurs after a damaged master database is restored and the master database is incomplete (databases and devices were added or altered since the last backup of the master database). This is the first step for restoring access to user databases. The DISK REFIT statement completes the recovery.

Syntax

DISK REINIT
NAME = 'logical_name',
PHYSNAME = 'physical_name',
VDEVNO = virtual_device_number,
SIZE = number_of_2K_blocks
[, VSTART = virtual_address]

where

NAME

Specifies the logical name of the database device. Logical names must correspond to the rules for identifiers and must be enclosed with single quotation marks ('). This name is used in the CREATE DATABASE and ALTER DATABASE statements.

PHYSNAME

Specifies the drive letter, full path, and filename of the database device file that already exists. Physical name must follow the rules for your operating system's paths and filenames. It must be enclosed with quotation marks (').

VDEVNO

Specifies the virtual device number. It must be unique among database devices used by SQL Server. Values can be from 1 through 255; 0 is reserved for the MASTER database device.

Note  NAME, PHYSNAME, and VDEVNO do not have to be identical to the device as it was originally created; however, the SIZE parameter must match.

SIZE

Specifies the size, in 2K blocks, of the database device. The minimum usable size is 512 2K blocks (1 MB).

VSTART

Specifies the starting virtual address or the starting offset in 2K blocks. The value for VSTART should be 0 (the default). Reset it only if instructed to do so.

Remarks

DISK REINIT is very similar to DISK INIT but does not initialize the disk space.

Caution  If you give DISK REINIT incorrect information about sizes and attempt to run update operations, you can permanently corrupt your data. SQL Server warns you of potential problems if it can, but be sure to run the suggested checks after issuing DISK REINIT and DISK REFIT.

If problems occur, you probably did not run DISK REINIT or ran it with inaccurate information. If you recognize discrepancies in the sysusages table, correct them. Correct the sysdevices table by rerunning DISK REINIT and then reissuing DISK REFIT. The system administrator must be in the master database to use DISK REINIT.

For more information about using DISK REINIT, see the Microsoft SQL Server Administrator's Companion.

Permission

DISK REINIT permission defaults to the system administrator and is not transferable.

Example

DISK REINIT must be run for each device of the database prior to running DISK REFIT.

DISK REINIT

NAME = 'DEVICE5',

PHYSNAME = 'c:\sqldata\device5.dat',

VDEVNO = 5,

SIZE = 25600

DISK REINIT

NAME = 'DEVICE6',

PHYSNAME = 'd:\sqldata\device6.dat',

VDEVNO = 6,

SIZE = 25600

Once all devices have been created, run DISK REFIT.

DISK REFIT

See Also

ALTER DATABASE	DISK INIT
CREATE DATABASE	DISK REFIT
DBCC	sp_helpdevice


DISK RESIZE Statement

Allows you to expand a device. You can use DISK RESIZE on any database device, including the MASTER device.

Syntax

DISK RESIZE
NAME = logical_device_name,
SIZE = final_size

where

logical_device_name

Specifies the database device to resize.

final_size

Is the final size to which the device should be expanded, specified in 2K pages.

Remarks

The DISK RESIZE statement expands a device; it does not shrink devices or alter any databases that reside on that device. DISK RESIZE cannot be used for dump devices or the TEMPDB device when tempdb is in RAM.

Permission

DISK RESIZE permission defaults to the system administrator and is not transferable.

Examples

A.	Increase the Size of a Device

This example increases the size of DEVICE1 from it's initial size of 12 MB to 20 MB.

DISK RESIZE

NAME = 'DEVICE1',

SIZE = 10240

B.	Increase the Size of the MASTER Device

This example increases the MASTER device from its initial size of 25 MB to 32 MB.

DISK RESIZE

NAME = 'MASTER',

SIZE = 16384

See Also

ALTER DATABASE	DISK INIT
CREATE DATABASE	sp_addumpdevice
DBCC	sp_helpdevice


DROP DATABASE Statement

Removes one or more databases from SQL Server.

Syntax

DROP DATABASE database_name [, database_name...]

where

database_name

Specifies the database to be removed. Execute the sp_helpdb system stored procedure from the master database to see a list of databases.

Remarks

Removing a database deletes the database and all its objects, frees its storage allocation, and erases references to it in the master database. A database that has been dropped can only be re-created from database backups. You cannot drop a database that is in use (open for reading or writing by any user).

In earlier releases, the DROP DATABASE statement would not work on damaged databases. In SQL Server 6.0, the DROP DATABASE statement works on databases marked suspect, offline, or not recovered. To drop a database in recovery (sysdatabases..status = 128), use the sp_dbremove system stored procedure.

After any changes are made to the master database, use the DUMP DATABASE statement to back up the master database.

Permission

DROP DATABASE permission defaults to the database owner and cannot be transferred. The database owner must be in the master database to use DROP DATABASE.

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_helpdb
CREATE DATABASE	sp_renamedb
sp_dbremove	USE


DROP DEFAULT Statement

Removes a user-defined default from a database.

The DROP DEFAULT statement does not apply to DEFAULT constraints. For details about dropping DEFAULT constraints, see the ALTER TABLE statement.

Syntax

DROP DEFAULT [owner.]default_name [, [owner.]default_name...]

where

default_name

Specifies the name of an existing default. You can find out what defaults exist by executing the sp_help system stored procedure.

Remarks

To drop a default, you must first unbind it by using the sp_unbindefault system stored procedure if it is currently bound to a column or to a user-defined datatype.

When you drop a default from a column that allows null values, NULL is inserted in that position when rows are added and no value is explicitly supplied. When you drop a default from a NOT NULL column, you get an error message when rows are added and no value is explicitly supplied.

Permission

DROP DEFAULT permission defaults to the owner of the default and is not transferable. However, the database owner and system administrator can drop any object by specifying the owner in the DROP DEFAULT statement. The database owner can also use the SETUSER statement to impersonate another user.

Examples

A.	Drop a Default

If a default has not been bound to a column or to a user-defined datatype, it can simply be dropped using the DROP DEFAULT statement. This example removes the user-created default datedflt.

DROP DEFAULT datedflt

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 phonedflt default.

sp_unbindefault 'authors.phone'

go

DROP DEFAULT phonedflt

See Also

CREATE DEFAULT	sp_helptext
sp_help	sp_unbindefault


DROP INDEX Statement

Removes an index from a database.

The DROP INDEX statement does not apply to indexes created by PRIMARY KEY or UNIQUE constraints. For details about dropping constraints, see the ALTER TABLE statement.

Syntax

DROP INDEX [owner.]table_name.index_name
[, [owner.]table_name.index_name...]

where

table_name

Specifies the table where the indexed column is located. If DROP INDEX is used by the DBO or SA, then the owner name can be included to drop an index not owned by the DBO.

index_name

Specifies the index to be dropped.

Remarks

Once the DROP INDEX statement is executed, you regain all the space occupied by the index. This space can then be used for any database object.

You can't use DROP INDEX on an index on a system table.

To get information about what indexes exist on a table, use the sp_helpindex system stored procedure with the table name as a parameter.

Permission

DROP INDEX permission defaults to the table owner and is not transferable. However, the database owner and system administrator can drop any object by specifying the owner in the DROP INDEX statement. The system administrator and database owner can also use the SETUSER statement to impersonate another user.

Example

This example removes the index au_id_ind in the authors table.

DROP INDEX authors.au_id_ind

See Also

CREATE INDEX	sp_spaceused
sp_helpindex


DROP PROCEDURE Statement

Removes user-created stored procedures from the current database.

Syntax

DROP PROCedure [owner.]procedure_name [, [owner.]procedure_name...]

where

procedure_name

Specifies the stored procedure(s) to be removed.

Remarks

DROP PROCEDURE removes user-created procedures from the user's current database. User-defined system procedures (prefixed with sp_) are dropped from the master database whether or not it is the current database. If the procedure is not found in the current database, SQL Server tries to drop it from the master database. When you drop a stored procedure, information about the procedure is removed from the sysobjects, sysprocedures, and syscomments system tables.

To see a list of procedure names, use the sp_help system stored procedure. To display the procedure definition (which is stored in the syscomments system table), use the sp_helptext system stored procedure.

A procedure group (more than one procedure with the same name but with different ;number suffixes) can be dropped using a single DROP PROCEDURE statement. For example, if the procedures used with the application orders are named orderproc;1, orderproc;2, and so on, the "DROP PROC orderproc" statement drops the entire group. Once procedures have been grouped, individual procedures within the group cannot be dropped. For example, "DROP PROCEDURE orderproc;2" is not allowed.

Permission

DROP PROCEDURE permission defaults to the procedure owner and is not transferable. However, the database owner and system administrator can drop any object by specifying the owner in the DROP PROCEDURE statement.

Example

This example removes the stored procedure byroyalty.

DROP PROCEDURE byroyalty

See Also

CREATE PROCEDURE	sp_helptext
sp_depends	sp_rename


DROP RULE Statement

Removes a user-specified rule from a database.

The DROP RULE statement does not apply to CHECK constraints. For details about dropping CHECK constraints, see the ALTER TABLE statement.

Syntax

DROP RULE [owner.]rule_name [, [owner.]rule_name...]

where

rule_name

Specifies the rule to be removed.

Remarks

To drop a rule, you must first unbind it if it is currently bound to a column or to a user-defined datatype. Use the sp_unbindrule system stored procedure to unbind the rule. If the rule is bound when you try to drop it, an error message is displayed and the DROP RULE statement is canceled.

After you drop a rule, new data entered into the columns previously governed by the rule is entered without these constraints. Existing data is not affected in any way.

Permission

DROP RULE permission defaults to the rule owner and is not transferable. However, the database owner and system administrator can drop any object by specifying the owner in the DROP RULE statement. The system administrator and database owner can also use the SETUSER statement to impersonate another user.

Example

This example unbinds and then drops the pub_id rule.

sp_unbindrule 'publishers.pub_id'

go

DROP RULE pub_id_rule

See Also

CREATE RULE	sp_helptext
sp_bindrule	sp_unbindrule
sp_help


DROP TABLE Statement

Removes a table definition and all data, indexes, triggers, constraints, and permission specifications for that table from the database.

Syntax

DROP TABLE [[database.]owner.]table_name
[, [[database.]owner.]table_name...]

where

table_name

Specifies the table to be removed.

Remarks

The DROP TABLE statement cannot be used to drop a table that is being referenced by a FOREIGN KEY constraint. You must first drop the referencing FOREIGN KEY constraint or the referencing table.

If you are the table owner, you can drop a table in any database. When you drop a table, 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.

The sysobjects, syscolumns, sysindexes, sysprotects, and syscomments system tables are affected when a table is dropped.

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 still exists until you drop it.

Permission

DROP TABLE permission defaults to the table owner and is not transferable. However, the database owner and system administrator can drop any object by specifying the owner in the DROP TABLE statement. The system administrator and database owner can also use the SETUSER statement to impersonate another user.

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

The following example drops the authors2 table in the pubs database. This 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 Statement

Removes a trigger from a database.

Syntax

DROP TRIGGER [owner.]trigger_name [, [owner.]trigger_name...]

where

trigger_name

Specifies the trigger(s) to remove.

Remark

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.

If a new trigger will replace the previous trigger, use the CREATE TRIGGER statement instead. For details, see the CREATE TRIGGER statement.

When you drop a trigger, information about the trigger is removed from the sysprocedures, sysobjects, and syscomments system tables.

Permission

DROP TRIGGER permission defaults to the trigger table owner and is not transferable. However, the system administrator and database owner can drop any object by explicitly specifying the owner in the DROP TRIGGER statement.

Example

This example drops the employee_insupd trigger.

DROP TRIGGER employee_insupd

See Also

CREATE TRIGGER	sp_help
sp_depends	sp_helptext


DROP VIEW Statement

Removes a view from a database.

Syntax

DROP VIEW [owner.]view_name [, [owner.]view_name...]

where

view_name

Specifies the view(s) to be removed.

Remarks

When you use DROP VIEW, the definition of the view and other information about it are deleted from the sysobjects, syscolumns, syscomments, sysdepends, sysprocedures, and sysprotects system tables. All privileges for the view are also deleted.

To see a list of view names, use the sp_help system stored procedure.

Permission

DROP VIEW permission defaults to the view owner and is not transferable. However, the system administrator and database owner can drop any object by explicitly specifying the owner in the DROP VIEW statement.

Example

This example removes the titles_view view.

DROP VIEW titles_view

See Also

CREATE VIEW	sp_help
sp_depends	sp_helptext


DUMP Statement

For more updated SQL Server 6.5 syntax, see DUMP Statement.

Makes a backup copy of a database and its transaction log (DUMP DATABASE) or makes a copy of only the transaction log (DUMP TRANSACTION) in a form that can be read into SQL Server using the LOAD statement.

Syntax

Dumping a database:

DUMP DATABASE {dbname | @dbname_var}
TO dump_device [, dump_device2 [..., dump_device32]]
[WITH options
[[,] STATS [ = percentage]]]

Dumping a transaction log:

DUMP TRANSACTION {dbname | @dbname_var}
[TO dump_device [, dump_device2 [..., dump_device32]]]
[WITH {TRUNCATE_ONLY | NO_LOG | NO_TRUNCATE}
{options}]

where

dump_device =

{dump_device_name | @dump_device_namevar}
| {DISK | TAPE | FLOPPY | PIPE} =
{'temp_dump_device' | @temp_dump_device_var}}
[VOLUME = {volid | @volid_var}]

options =

[[,] {UNLOAD | NOUNLOAD}]
[[,] {INIT | NOINIT}]
[[,] {SKIP | NOSKIP}]
[[,] {{EXPIREDATE = {date | @date_var}}
| {RETAINDAYS = {days | @days_var}}]

Note  The UNLOAD and NOUNLOAD options are supported only by TAPE dump devices.

When you specify a PIPE dump device, multivolume dumps and dump device options (UNLOAD, NOUNLOAD, INIT, NOINIT, SKIP, NOSKIP, EXPIREDATE, and RETAINDAYS) are not supported.

DATABASE

Specifies that the complete database and transaction log are to be backed up.

If the transaction log is on the same device as the database, using DUMP DATABASE is the only way you can create a backup copy of both the database and its transaction log. However, because DUMP DATABASE does not remove the inactive portion of the log, you must use DUMP TRANSACTION WITH TRUNCATE_ONLY to purge the log of completed transactions. Generally, databases and transaction logs should be stored on different devices; this improves performance and enables unrestricted use of both the DUMP DATABASE and DUMP TRANSACTION statements.

TRANSACTION

Specifies that only the transaction log is to be backed up. DUMP TRANSACTION removes the inactive part of the transaction log and makes a backup copy of it in a form that can be read in with the LOAD statement. To retain a backup of only the transaction log (using DUMP TRANSACTION without the TRUNCATE_ONLY or NO_LOG options), the transaction log must be stored on a separate database device from the data portion of the database.

Note  If dumping the transaction log doesn't appear to truncate the majority of your transaction log, you may have an open transaction in the log. To determine whether a transaction has been left open, use DBCC OPENTRAN.

For databases that store the data portion of the database on a separate device from the log portion, log space can be monitored with various DBCC commands and the Performance Monitor. For details, see the DBCC statement.

TRUNCATE_ONLY

Removes the inactive part of the log without making a backup copy of it. This optional clause frees disk space used by the transaction log. Specifying a dump_device is unnecessary because the transaction log dump will not be saved.

Prior to backing up a database, it is useful to dump a transaction log using the TRUNCATE_ONLY option to clear out the log and decrease the total time required to back up the database.

Note  After dumping a transaction log using the TRUNCATE_ONLY option, you should immediately make a backup of the database using DUMP DATABASE. Dumping of the transaction log (using DUMP TRANSACTION) will not be allowed until a full database dump (using DUMP DATABASE) has been performed.

NO_LOG

Is used only when you have run out of space in the database and cannot use DUMP TRANSACTION WITH TRUNCATE_ONLY to purge the log. The NO_LOG option removes the inactive part of the log without making a backup copy of it, and it saves space by not logging the operation.

If the transaction 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 past the oldest distributed transaction.

After the transaction log has been dumped using NO_LOG, the changes recorded in the log are not recoverable. For recovery purposes, immediately execute the DUMP DATABASE statement.

Because both options clear the log without making a backup of it, it is unnecessary to use both the TRUNCATE_ONLY and NO_LOG option in the same statement.

NO_TRUNCATE

Makes it possible to dump a transaction log even if the database is inaccessible by using a pointer to the transaction log in the master database.

The NO_TRUNCATE option provides up-to-the-minute media recovery when the master database and the log portion of the user database reside on undamaged database devices and when only the data portion of the user database is damaged.

dbname | @dbname_var

Specifies the database from which the transaction log or complete database is being dumped. If supplied as a variable (@dbname_var), this name can be specified as a string, or as a char or varchar variable.

dump_device_name | @dump_device_namevar

Specifies the logical name of the dump device or devices (as created by the sp_addumpdevice system stored procedure) to which the database will be backed up. If supplied as a variable (@dump_device_namevar), the dump device name can be specified as a string or as a char or varchar variable.

DISK | TAPE | FLOPPY | PIPE =

'temp_dump_device' | @temp_dump_device_var

Allows backups directly to temporary dump devices. These devices are created (or accessed, if they already exist) when the dump occurs; they do not have entries in the sysdevices system table. With DISK, TAPE, and FLOPPY specify the complete path and filename of the device. With PIPE, specify the name of the named pipe that will be used by the client application. If supplied as a variable (@temp_dump_device_var), the temporary dump device name can be specified as a string or as a char or varchar variable. 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 a striped dump, logical device names (or variables) and temporary device names (or variables) can be mixed. PIPE devices have been added to allow third-party vendors a flexible and powerful way to connect their own software. For typical Transact-SQL use, the PIPE device will not be used.

VOLUME = volid | @volid_var

Specifies the volume ID, volid, a 6-byte character string. If dumping to a new tape, this value is the name of the ANSI VOL1 label. For SQL Server, the default is SQ0001. For subsequent dumps, this value is used to validate the volume name of the dump device. If supplied as a variable (@volid_var), the volume name can be specified as a string or as a char or varchar variable. It is not necessary, or recommended, to explicitly specify the volume ID.

UNLOAD

Specifies that the tape is automatically rewound and unloaded when the dump 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.

NOUNLOAD

Specifies that the tape will not be unloaded automatically from the tape drive after a dump. NOUNLOAD remains set until UNLOAD is specified. This option is used only for tape devices.

INIT

Specifies that the dump should be the first file on the DISK or TAPE device. If INIT is specified, any existing data on that device will be overwritten. If the first file on the device has an ANSI-standard label, the label will be evaluated to determine whether the previous dump(s) can be overwritten. For details, see the EXPIREDATE and RETAINDAYS options, later in this section.

NOINIT

Specifies that the dump should be appended to the current DISK or TAPE device. This is the default for both single dump devices and striped dumps. Dump devices used in a stripe set must always be used in a stripe set (unless reinitialized at some point with INIT). Once a device is defined as part of a stripe set, it cannot be used for a single device dump unless INIT is specified. Similarly, a device that contains nonstriped dumps cannot be used in a stripe set unless INIT is specified.

SKIP

Instructs the server not to read the ANSI TAPE device headers.

NOSKIP

Specifies that the server will read ANSI TAPE device headers. This is the default.

Note  When specified, SKIP and NOSKIP override the setting as defined with the dump device (when the sp_addumpdevice system stored procedure was executed).

EXPIREDATE = date | @date_var

Specifies the date when the dump media expires and can be overwritten. If supplied as a variable (@date_var), this date can be specified as a string or as a char or varchar 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 INIT.

RETAINDAYS = days | @days_var

Specifies the number of days that must elapse between the existing dump and when the dump media 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.

Important  EXPIREDATE and RETAINDAYS override the configuration value for media retention when specified with the DUMP DATABASE or DUMP TRANSACTION statements. These options are used with DISK and TAPE devices only. If an expiration date is needed for diskette devices, configure media retention with the sp_configure system stored procedure.

If EXPIREDATE or RETAINDAYS is specified, subsequent dumps can be appended to that device; however, EXPIREDATE and RETAINDAYS are valid only for dumps specified with INIT.

These options only prevent SQL Server from overwriting a device. Tapes can still be erased using other methods, and disk-device files can still be deleted through the operating system.

STATS = percentage

Returns the percentage of pages dumped in increments optionally set at the time of the dump. If the percentage is not specified, statistics will be shown for each 10 percent of the dump. This option is available only with DUMP DATABASE.

Remarks

In earlier releases of SQL Server, dumping a database or a transaction log to a single device always overwrote the previous dump unless (for tape devices only) NOINIT was specified. With SQL Server 6.0, database or transaction log dumps can be appended to any DISK or TAPE device, allowing you to keep a database and its transaction logs all within one physical location.

The SQL Server dump is a dynamic dump — it can take place while the database is active. The dump captures the state of the data as it is at the moment the statement is executed; no partial transactions are reflected. Any data changes made after the dump begins are not reflected in the dumped database. Performing a dump can slow the system down somewhat, so you may want to run it when the database or table is not being heavily updated.

Ownership and permissions problems on the physical file can interfere with a DUMP statement. The sp_addumpdevice system stored procedureadds the device to the system tables, but it does not check file access permission.

You cannot execute the DUMP TRANSACTION 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 or a bulk-copy operation. Use DUMP DATABASE instead.

Permission

DUMP DATABASE and DUMP TRANSACTION permission default to the database owner, who can transfer it to other users.


Database Design and Backup Strategy

With small databases, the transaction log is usually stored on the same database device as the rest of the database. DUMP DATABASE backs up both the database and the transaction log, after which you can use DUMP TRANSACTION WITH TRUNCATE_ONLY to remove committed transactions from the log.

With large databases, the transaction log (the log portion of the database) and the data portion of the database are usually stored on a separate devices. In these cases, you can use DUMP TRANSACTION to maintain a backup of only the transaction log. Dumping only the transaction log uses less storage and takes less time than DUMP DATABASE, which backs up both the transaction log and the database. Dumps of the transaction log are usually coordinated with DUMP DATABASE as part of an overall backup procedure. Typically, transaction log dumps are done more frequently than database dumps. To recover a database, load the most recent database dump and load all the transaction log dumps (in order) made since the database dump. The database is restored to its state at the time of the last transaction log dump.

Regardless of database setup, it is highly recommended that you always run DBCC CHECKDB, DBCC CHECKALLOC or DBCC NEWALLOC, and DBCC CHECKCATALOG on a database just prior to dumping it. DBCC will check the logical and physical consistency of the database. If a database or transaction log that contains errors is dumped, the errors will still exist when the data is reloaded. Under some conditions, this can even prevent successful reloading. If any of the DBCC commands report errors in the database, contact your system administrator or your primary technical support provider.


Dumping the master Database

The master database is backed up in the same way as a user database, and it should be dumped regularly and frequently. Make sure that you back up master after changes that update system tables have been made. (For example, back up the master database after these statements are used: ALTER DATABASE, CREATE DATABASE, DISK INIT, DISK RESIZE, various DBCC options such as SHRINKDB, the sp_configure system stored procedure).

The backups of the master database help in recovery if master fails; however, the recovery method for a damaged master database differs from that for user databases. For information about restoring the master database, see the Microsoft SQL Server Administrator's Companion.

Note  The master database contains the system catalog, which is the most important information about your SQL Server configuration. Because the master database cannot be separated from its transaction log, you can back up the master database only with the DATABASE option.


Dumping to a Tape Device

To dump to a tape, the tape dump device must be located on the computer where SQL Server is running. Information about a tape dump is recorded on the tape label. This information includes up to 17 characters of the database name, the time and date of the dump, and the type of dump (database, table, or log).

To add multiple dumps to a single tape, specify NOUNLOAD and INIT when issuing the first dump. Specify UNLOAD while issuing the last dump so that the tape will be unloaded when the dump ends. To add a single dump to the end of an existing multifile tape, specify NOINIT and UNLOAD.

If you are writing over a tape, be sure that you use the INIT option when you dump the first file to that tape. This allows the data on the tape to be overwritten, rather than adding the dump to the end of the tape.

If the tape contains data in a foreign format (not SQL Server backup files), you must specify INIT; otherwise, the tape will be rejected. The tape can be used for a SQL Server backup by issuing a DUMP WITH INIT statement, which treats the tape as blank.


Dumping to a Diskette Device

When a DUMP is executed for dumping to a floppy disk, the console command-line utility must be used to prompt the user and then waits for responses. If console is not running or if the user does not answer its questions, the dump cannot proceed. Dumping to a diskette device is not recommended. Dump to a disk device and copy (or use backup command) to a diskette instead.


Dumping to a Disk Device

Disk devices can be defined on shared network resources. If the dump is to be performed over the network, you must supply the UNC (universal naming convention) name in the form \\servername\sharename\path\filename or use a locally redirected drive letter. Make sure that you have appropriate permissions on the destination device. To ensure proper permissions, SQL Server may need to be started under a domain account (not the local system). To define the domain account under which SQL Server should be started, use the Services application in the Windows NT Control Panel.

To add multiple dumps to a single disk (file), specify INIT while issuing the first dump and NOINIT for subsequent dumps. If you are writing over a disk dump device, make sure that you use the INIT option when you perform the first dump. This allows the data on the disk dump device to be overwritten, rather than appending the dump to the end of the file.


Databases Dumping to Novell File Servers

A redirected drive can also include dump devices located on Novell file servers. The capability to define dump devices located on Novell file servers takes advantage of the Windows NT Workstation Client and Gateway Services for NetWare available from Microsoft.

Defining database dump devices with Microsoft SQL Server without setting up a Gateway Share is simple and does not require special mapping on the Novell file server, nor does it require that there be a shared device defined in File Manager.

It is important that the Client and Gateway Services for NetWare be appropriately set up so that files can be copied from the Novell file server to Windows NT without error. Routing and frame type issues must be resolved prior to implementing this procedure.

To set up the Client and Gateway Services, an NTGATEWAY group must already exist on the Novell file server. There are two ways to do this.

The first method depends on GUEST validation by the Novell file server. Begin the Windows NT setup by assigning the LocalSystem account to the SQL Server service. Use the Services application in the Control Panel to do this. For instructions, see your documentation for Windows NT.

When SQL Server starts, it will log in as a LocalSystem account on Windows NT, which means that the Novell file server will have no knowledge of this Windows NT user ID.

On the Novell file server, add the GUEST account to the NTGATEWAY Group and make sure that account has complete trustee rights to the directory where the SQL Server database dump will be written. When SQL Server attempts to dump the database to this directory, the Novell file server will validate the login and use the GUEST account with NTGATEWAY as the user group.

The second method to set up the Client and Gateway Services is to start the SQL Server service with a user account that is valid on the Novell file server and on Windows NT. This user must have appropriate access to stop and start Windows NT services. The user ID and password on Windows NT must exactly match the user ID and password on the Novell file server. In addition, the user account must also be a member of the NTGATEWAY Group and have complete Trustee rights to the directory where the SQL Server database dump will be written.

Unlike setting up a local disk dump device, a UNC path to a Novell file server consists of the file server name, volume, directory, and file.

For example, to define a database dump device on the Novell file server WHISTLE/SYS:USERS/TEST, the following would be entered as the physical filename:

Logical Name: pubsdump

Physical Name: \\WHISTLE\SYS\USERS\TEST\PUBS.DMP

Once the dump device has been defined, verify that the process works by dumping a database with a valid SQL Server login ID.


DUMP Examples
Examples

In both examples A and B, a time interval has been specified for dumping the transaction log. It is important to back up your transaction log frequently. For more information about appropriate frequency of backups, see the Microsoft SQL Server Administrator's Companion.

A.	Multiple Dumps to a Single Dump Device

This example shows how to back up a database and its transaction logs to the same disk device.

/* Dump database to a predefined (with sp_addumpdevice) DISK device. */

EXEC sp_addumpdevice 'disk', 'disk_dev1',
'c:\sql60\dumps\diskdev1.dmp', 2

DECLARE @two_weeks char(8)

SELECT @two_weeks = CONVERT(char(8), DATEADD(dd, 14, GETDATE()) , 1)

DUMP DATABASE corporate

TO	disk_dev1

WITH INIT, EXPIREDATE = @two_weeks, STATS

/* The next day. */

DUMP TRANSACTION corporate

TO	disk_dev1

WITH NOINIT

Msg 4035, Level 10, State 1

Database 'corporate' log(26 pages) dumped to file <2> on device 'disk_dev1'.

/* The third day. */

DUMP TRANSACTION corporate

TO	disk_dev1

WITH NOINIT

go

Msg 4035, Level 10, State 1

Database 'corporate' log(4 pages) dumped to file <3> on device 'disk_dev1'.

/* and so on. */

DUMP TRANSACTION...

B.	Multiple Dumps to a Single Dump Device

This example shows the database backup used in example A using a temporary dump device on the network.

/*

Dump database to a NETWORK DISK device using UNC name.

In this example, the UNC name should be

replaced with a 	specific server name, share name, and

directory\filename.ext from your network.

*/

DECLARE @two_weeks char(8)

SELECT @two_weeks = convert(char(8), dateadd(dd, 14, getdate()) , 1)

DUMP DATABASE corporate

TO	DISK = '\\servername\sharename\directory\filename.ext'

WITH INIT, EXPIREDATE = @two_weeks, STATS

go

/* The next day. */

DUMP TRANSACTION corporate

TO	DISK = '\\servername\sharename\directory\filename.ext'

WITH NOINIT

go

/* The third day. */

DUMP TRANSACTION corporate

TO	DISK = '\\servername\sharename\directory\filename.ext'

WITH NOINIT

go

/* And so on. */

DUMP TRANSACTION...

C.	Striped Dump Device Backups

Both of the following examples show how to back up a database to a group of devices. These devices can be a group of predefined devices (created with sp_addumpdevice), a group of ad hoc devices, or any combination of these.

DUMP DATABASE corporate

TO	tape_dev0,

tape_dev1,

tape_dev2

WITH INIT, UNLOAD, EXPIREDATE = @two_weeks, STATS

Or

/* Dump database to ad hoc TAPE devices. */

DUMP DATABASE corporate

TO	TAPE = '\\.\tape0',

TAPE = '\\.\tape1',

TAPE = '\\.\tape2'

WITH INIT, UNLOAD, EXPIREDATE = @two_weeks, STATS

See Also

LOAD	sp_helpdevice
sp_addumpdevice	sp_logdevice
sp_dropdevice	sp_spaceused
sp_helpdb


EXECUTE Statement

For more updated SQL Server 6.5 syntax, see EXECUTE Statement.

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. In earlier releases, Transact-SQL statements needed to include the actual name of an object at parse and compile time. With the EXECUTE statement, a string can be created with variables that are resolved at execution time.

Syntax

To execute a stored procedure:

EXEC[ute]
{[@return_status =]
{[[[server.]database.]owner.]procedure_name[;number] |
@procedure_name_var}
[[@parameter_name =] {value | @variable [OUTPUT]]
[, [@parameter_name =] {value | @variable [OUTPUT]}]...]
[WITH RECOMPILE]]

To execute a character string:

EXEC[ute] ({@str_var | 'tsql_string'} [+{@str_var | 'tsql_string'}...)}

where

@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

Specifies a stored procedure. You can execute a procedure that has been created in another database if you are its owner or have permission to execute it in that database. You can execute a procedure on another SQL Server if you have permission to use that server (remote access) and to execute the procedure in that database. If you specify a server name but do not specify a database name, SQL Server looks for the procedure in your default database.

@procedure_name_var

Is the name of a locally defined variable that represents a stored procedure name.

;number

Is an optional integer used to group procedures of the same name so that they can be dropped together with a single DROP PROCEDURE statement. Procedures used in the same application are often grouped this way. For example, the procedures used with the application orders might be named orderproc;1, orderproc;2, and so on. The statement DROP PROCEDURE orderproc drops the entire group. Once procedures have been grouped, individual procedures within the group cannot be dropped. For example, the statement DROP PROCEDURE orderproc;2 is not allowed. This parameter is not used for extended stored procedures.

@parameter_name

Specifies the parameter for a procedure, as defined in the CREATE PROCEDURE statement. Parameter names must be preceded by the "at" symbol (@). When used with the @parameter_name = value form, parameter names and constants need not be supplied in the order 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.

value

Is the value of the parameter to the procedure. If you do not use parameter names, 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. For details, see the CREATE PROCEDURE statement.

The default can also be NULL. Usually, the procedure definition specifies what action should be taken if a parameter value is NULL.

@variable

Specifies the variable that stores a return parameter.

OUTPUT

Indicates that the stored procedure returns a parameter. The matching parameter in the stored procedure must also have been created with the keyword OUTPUT.

WITH RECOMPILE

Forces a new plan to be compiled. Use this option if the parameter you're supplying is atypical or if the data has significantly changed. The changed plan is used in subsequent executions. This parameter is not used for extended stored procedures.

Note  If you use SELECT * in your CREATE PROCEDURE statement, the procedure (even with the WITH RECOMPILE option to EXECUTE) does not select any new columns added to the table. So that the procedure can select new columns, you must drop the procedure and re-create it.

@str_var

Is the name of a local string variable. In most cases, this variable will be composed of multiple strings that in total will represent a Transact-SQL statement. The @str_var variable can be a char, character, varchar, or text parameter.

tsql_string

Represents a portion or complete string of Transact-SQL statement(s). The total concatenated string passed to the EXECUTE statement must include the complete Transact-SQL command with appropriate spaces and syntax. The string must be enclosed with single quotation marks (').

Remarks

You don't need to use the EXECUTE keyword while executing stored procedures if the statement is the first one in a batch.

You can supply parameters by using value or by using @parameter_name = value. A parameter is not part of a transaction, so if a parameter is changed in a transaction that is later rolled back, the parameter's value does not revert to its previous value. The value returned to the caller is always the value at the time the procedure returns.

If you are using OUTPUT parameters and intend 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_name = @variable. It is an error to execute a procedure specifying OUTPUT for a parameter not defined as an OUTPUT parameter in the CREATE PROCEDURE statement. You cannot pass constants to stored procedures using OUTPUT; the return parameter requires a variable name. You must declare the variable's datatype and assign it a value before executing the procedure. Return parameters can be of any datatype except text or image.

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 16 nesting levels causes the whole calling procedure chain to fail. The current nesting level is stored in the @@NESTLEVEL global variable.

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 a list of values, see the RETURN statement in the Control-of-flow Language topic.

Remote stored procedures and extended stored procedures are not within the scope of a transaction, so commands executed through calls to them cannot be rolled back. For more information, see the Stored Procedures—Extended Stored Procedures topic.

Permission

EXECUTE permission for a stored procedure defaults to the owner of the stored procedure, who can transfer it to other users. Permission to use the statement(s) within the EXECUTE string is 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, the user running the procedure is checked for permissions. In other words, the procedure is checked in the context of the user executing the procedure, not in the context of the user who created the procedure.


Using EXECUTE with a Character String

All items within the EXECUTE string must consist of character data; all numeric data must be converted prior to using EXECUTE. Functions cannot be used to build the string to be executed; however, any valid Transact-SQL statements, including functions, are available to be passed within the tsql_string, and nested EXECUTE statements are permitted.

Statement(s) inside the EXECUTE statement are not parsed, normalized, or compiled until the EXECUTE statement is executed. All table names (referenced within the same batch) are resolved when the batch is compiled. Combining statements that change database context (for example, USE dbname) and table references within the same batch will cause object resolution errors (the objects will not be found).

Incorrect:

EXEC ("USE pubs")

SELECT * FROM authors

Correct:

USE pubs

SELECT * FROM authors

OR

EXEC("USE pubs")

EXEC("SELECT * FROM authors")


EXECUTE Examples
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.

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.	Multiple Parameters and an Output Parameter

This example executes the roy_check stored procedure, passing 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.

DECLARE @@percent int

EXECUTE roy_check 'BU1032', 1050, @@pc = @@percent OUTPUT

SELECT Percent = @@percent

C.	EXECUTE 'tsql_string' with a Variable

This example shows how EXECUTE handles dynamically built strings with variables. This example creates a cursor (tables_cursor) to hold a list of all user-defined tables (type = 'U').

DECLARE tables_cursor CURSOR

FOR

SELECT name FROM sysobjects WHERE type = 'U'

OPEN tables_cursor

DECLARE @@tablename varchar(30)

FETCH NEXT FROM tables_cursor INTO @@tablename

WHILE (@@fetch_status <> -1)

BEGIN

/*

A @@fetch_status of -2 means that the row has been deleted.

No need to test for this as the result of this loop is to

drop 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 ending in EXE:

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)

SELECT @@proc_name = 'sp_who'

EXEC @@proc_name

See Also

CREATE PROCEDURE	sp_helptext
DROP PROCEDURE	Variables
sp_depends	Wildcard Characters


Expressions

Used with variables, constants, and column names in many SQL statements, functions, and expressions. An expression returns values and can be nested.

Syntax

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

where

constant

Is a literal value, such as numeric or character data, or a variable identifier (in the form @@variable_name). Character data must be enclosed with single quotation marks (').

column_name

Specifies a column.

function

Is a built-in function. For details, see the Functions topic.

subquery

Is a nested SELECT statement with some restrictions. A subquery can be used in an expression if the subquery returns a single value. For details, see the Subqueries topic.

operator

Is an arithmetic, bitwise, comparison, or string operator. For details, see the Operators topic.

AND

Used in Boolean expressions to connect two expressions. Returns results when both expressions are true.

When more than one logical operator is used in a statement, AND is processed first. You can change the order of execution by using parentheses.

OR

Use in Boolean expressions to connect two or more conditions. Returns results when either condition is true.

When more than one logical operator is used in a statement, OR is evaluated after AND. You can change the order of execution by using parentheses.

NOT

Negates any Boolean expression (which can include keywords, such as LIKE, NULL, BETWEEN, IN, and EXISTS).

Remarks

Character-constant expressions are treated as varchar. If they are compared with non-varchar variables or column data, the datatype precedence rules are used in the comparison (that is, the lower datatype is converted to the higher). If implicit conversion of the lower to the higher is not allowed, use CONVERT. For details, see the Functions topic.

Comparing a char expression to a varchar expression follows the datatype precedence rule (the lower datatype is converted to the higher). All varchar expressions are converted to char (that is, trailing blanks are added) for the comparison.

See Also

Functions	SELECT
Operators	Subqueries
Search Conditions	Wildcard Characters


Functions

Functions return special information from the system about users, expressions, a database or database objects, and so on. Aggregate functions return summary values. Other built-in functions perform various operations and are often used on their own or as part of a stored procedure or program. When used in SQL statements, functions can be used in the select list, in the WHERE clause, and anywhere an expression is allowed.

The built-in functions detailed below are Transact-SQL extensions to SQL. They can be divided into the following specific categories. For more information, see the Expressions topic and the Text and Image Manipulation topic.

Aggregate Functions

Aggregate functions return summary values. These are the aggregate functions:

AVG	COUNT(*)	MIN
COUNT	MAX	SUM
Date Functions

Date functions compute datetime values and their components, dataparts. These are the date functions:

DATEADD	DATENAME	GETDATE
DATEDIFF	DATEPART
Mathematical Functions

Mathematical functions perform operations on numeric data. These are the mathematical functions:

ABS	DEGREES	RAND
ACOS	EXP	ROUND
ASIN	FLOOR	SIGN
ATAN	LOG	SIN
ATN2	LOG10	SQRT
CEILING	PI	TAN
COS	POWER
COT	RADIANS
Niladic Functions

Niladic functions allow a system-supplied value to be inserted into a table when no value is specified. ANSI-standard niladic functions are used in DEFAULT constraints. These niladic functions are supported:

CURRENT_TIMESTAMP	SYSTEM_USER
CURRENT_USER	USER
SESSION_USER
For details about these functions, see the CREATE TABLE and ALTER TABLE statements.

String Functions

String functions perform operations on binary data, character strings, or expressions. These are the string functions:

+	LTRIM	SOUNDEX
ASCII	PATINDEX	SPACE
CHAR	REPLICATE	STR
CHARINDEX	REVERSE	STUFF
DIFFERENCE	RIGHT	SUBSTRING
LOWER	RTRIM	UPPER
System Functions

System functions return special information from the database. These are the system functions:

COALESCE	HOST_NAME	OBJECT_NAME
COL_LENGTH	IDENT_INCR	STATS_DATE
COL_NAME	IDENT_SEED	SUSER_ID
DATALENGTH	INDEX_COL	SUSER_NAME
DB_ID	ISNULL	USER_ID
DB_NAME	NULLIF	USER_NAME
GETANSINULL	HOST_ID	OBJECT_ID
For details about the COALESCE and NULLIF functions, see the CASE statement.

Text and Image Functions

Text and image functions perform operations on text and image data. These are the text and image functions:

PATINDEX	TEXTPTR
SET TEXTSIZE	TEXTVALID
For details about these functions, see the text and image Manipulation topic.

Type-conversion Function

The type-conversion function transforms expressions from one datatype into another. This is the type-conversion function:

CONVERT


Aggregate Functions

Return summary values. Aggregate functions calculate summary values, such as averages and sums, from the values in a particular column, and they return a single value for each set of rows to which the function applies.

Aggregate functions often appear with GROUP BY, which partitions a table into groups. These functions calculate a single value for each group. Without GROUP BY, an aggregate function in the select list produces a single value as a result, whether it is operating on all the rows in a table or on a subset of rows defined by a WHERE clause.

Syntax

aggregate_ function ([ALL | DISTINCT] expression)

where

aggregate_ function

Specifies an aggregate function.

The aggregate functions are:

Aggregate function	Description
AVG	Returns the average of all the values, or only the DISTINCT values, in the expression. AVG can be used with numeric columns only. Null values are ignored.
COUNT	Returns the number of non-null values in the expression. When DISTINCT is specified, COUNT finds the number of unique non-null values. COUNT can be used with both numeric and character columns. Null values are ignored.
COUNT(*)	Returns the number of rows. COUNT(*) takes no parameters and cannot be used with DISTINCT. All rows are counted, even those with null values.
MAX	Returns the maximum value in the expression. MAX can be used with numeric, character, and datetime columns, but not with bit columns. With character columns, MAX finds the highest value in the collating sequence. MAX ignores any null values. DISTINCT is available for ANSI compatibility; but, it is not meaningful with MAX.
MIN	Returns the minimum value in the expression. MIN can be used with numeric, character, and datetime columns, but not with bit columns. With character columns, MIN finds the value that is lowest in the sort sequence. MIN ignores any null values. DISTINCT is available for ANSI compatibility; but, it is not meaningful with MIN.
SUM	Returns the sum of all the values, or only the DISTINCT values, in the expression. SUM can be used with numeric columns only. Null values are ignored.
Numeric columns refer to decimal, float, int, money, numeric, real, smallint, smallmoney, and tinyint datatypes.
ALL

Applies the aggregate function to all values. ALL is the default.

DISTINCT

Eliminates duplicate values before an aggregate function is applied. DISTINCT is optional with SUM, AVG, COUNT, MIN, MAX and cannot be used with COUNT(*). Although available for ANSI compatibility, DISTINCT is meaningless with MIN and MAX.

expression

Is a column name, constant, function, any combination of column names, constants, and functions connected by arithmetic or bitwise operators. For more information, see the Expressions topic.

Remarks

Aggregate functions, which calculate summary values from the non-null values in a particular column, can be applied to all rows in a table. In this case, they produce a single value called a scalar aggregate function. Or they can be applied to all rows that have the same value in a column or columns or expression (with the GROUP BY and, optionally, the HAVING clause). In this case, they produce a value for each group, called a vector aggregate function. The results of the aggregate functions are shown as new columns.

When you sum or average numeric data, Transact-SQL promotes the resulting datatype to the minimum precision and scale necessary to hold the result. To avoid overflow errors, declare all variables that will hold the result of a sum or average with the most precise datatype of the values supplied. For example, when summing tinyint and int values, use a resulting variable of type int. When working with datatypes of varying precision and scale, use the maximum precision and the maximum scale.

Examples

A.	SUM and AVG Functions

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.

SELECT AVG(advance), SUM(ytd_sales)

FROM titles

WHERE type = 'business'

B.	SUM and AVG Function with a GROUP BY Clause

When used with a GROUP BY clause, aggregate functions produce single values for each group, rather than for the whole table. This example produces summary values for each type of book.

SELECT type, AVG(advance), SUM(ytd_sales)

FROM titles

GROUP BY type

C.	COUNT of DISTINCT

This example finds the number of different cities in which authors live.

SELECT COUNT(DISTINCT city)

FROM authors

D.	GROUP BY HAVING COUNT(*)

This example lists the types in the titles table but eliminates the types that include more than one book.

SELECT type

FROM titles

GROUP BY type

HAVING COUNT(*) > 1

E.	HAVING 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.

SELECT pub_id, SUM(advance), AVG(price)

FROM titles

GROUP BY pub_id

HAVING SUM(advance) > $25000

AND AVG(price) > $15


CONVERT Function

The CONVERT function converts an expression of one datatype to another datatype. Also obtains a variety of special date formats.

Syntax

CONVERT (datatype[(length)], expression [, style])

where

datatype

Is any system datatype (for example, char(10), varbinary, int) into which the expression is to be converted. User-defined datatypes cannot be used.

length

Is an optional parameter with char, varchar, binary, and varbinary datatypes.

Note  For datatypes where specifying length (n) is optional — (binary[(n)], char[(n)], varbinary[(n)], and varchar[(n)]) — SQL Server uses 30 for the length.

The maximum allowable length is 255.

expression

Follows the rules for expressions. For more information, see the Expressions topic.

style

Is the style of date representation you want when converting datetime or smalldatetime data to character data. In the following table, the two columns on the left represent the style values. Add 100 to a style value to get a four-place year that includes the century (yyyy).

Without  century  (yy)	With  century  (yyyy)	Standard	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)
* The default values (style 0 or 100, 9 or 109, and 13 or 113) always return the century (yyyy).
When converting 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 datatype length.

Remarks

SQL Server automatically handles certain datatype conversions. For example, if you compare a character expression and a datetime expression, or a smallint expression and an int expression, or character expressions of different lengths, SQL Server makes the conversion automatically for the comparison. You are not required to use CONVERT; however, it is never wrong to use the CONVERT function even when you are comparing two expressions of exactly the same datatype. CONVERT can be used in a select list or in a WHERE clause.

When concatenating noncharacter, nonbinary expressions, always use the CONVERT function. For example:

SELECT 'The date is ' + CONVERT(varchar(12), getdate())

Automatic conversion is not supported for the text and image datatypes. You can explicitly convert text data to character data, and image data to binary or varbinary, but the maximum length you can specify is 255. If you attempt a conversion that is not possible (for example, if you try to convert a character expression that includes letters to an int), SQL Server generates an error message.

When converting between types with a different number of decimal places, the value is rounded to the most precise digit. The result of the following is 10:

SELECT CONVERT(int, 10.6496)

This table shows the possible datatype conversions.

Key:	I Implicit conversion
	E Explicit conversion, CONVERT function must be used
	N Conversion not allowed
	* Converting from decimal or numeric to decimal or numeric requires CONVERT when a loss of  precision or scale will occur.
	− Conversion of a datatype to itself; allowed but meaningless
binary and varbinary

Convert to binary to display the internal representation of a value. If lengths differ, the binary value is padded with zeros on the left.

You can convert int, smallint, and tinyint to binary or varbinary, but if you convert the binary value back to an integer value, it may be different from the original integer value. In addition, if the integer is longer than the specified binary length, it is truncated. For example, a conversion from a long binary to an int value uses only the 4 rightmost bytes of the binary value. The following example shows why binary and varbinary datatypes should be used only for hexadecimal numbers that are interpreted as type streams, and should not be used in calculations.

SELECT CONVERT(int,0x0001000008ae36f0)

SELECT CONVERT(int,0x00010000)

------

145635056

(1 row affected)

------

65536

(1 row affected)

bit

Converting to bit promotes any nonzero value to 1.

Character data

When character expressions are converted to a character datatype of a different size, values too long for the new datatype are truncated.

Character expressions being converted to an approximate numeric datatype can include optional exponential notation (a lowercase e or uppercase E followed by an optional plus (+) or minus (−) sign and then a number).

Character expressions being converted to an exact numeric datatype must consist of digits, a decimal point, and an optional plus (+) or minus (−) sign. Leading blanks are ignored.

Character expressions being converted to money datatypes can also include an optional decimal point and dollar sign ($).

datetime and smalldatetime

When converting to datetime, SQL Server rejects all values it cannot recognize as dates (including dates earlier than January 1, 1753). You can convert datetime values to smalldatetime when the date is in the proper range (January 1, 1900 to June 6, 2079). The time value is rounded up to the nearest minute.

float

Values of float are truncated when converted to any integer type.

When you are converting from float or real to character data, the string function STR( ) is usually a better choice than CONVERT( ), because STR( ) gives you more control over formatting. For more information, see the String Functions topic.

money

When converting to money from integer datatypes, units are assumed to be dollars. For example, the integer value of 4 is converted to the money equivalent of 4 dollars.

decimal and numeric

For the decimal and numeric datatypes, SQL Server considers each specific combination of precision and scale as a different datatype. For example, decimal(5,5) and decimal(5,0) are considered different datatypes.

In Transact-SQL statements, a constant with a decimal point is automatically converted into a numeric data value, using the minimum precision and scale necessary. For example, the constant 12.345 is converted into a numeric value with a precision of 5 and a scale of 3. This behavior is different from earlier versions of SQL Server, which converted constants with a decimal point to float. Therefore, calculations can return slightly different (but more precise) results.

Converting from decimal or numeric to float or real can result in some loss of precision. Converting from int, smallint, tinyint, float, real, money, or smallmoney to either decimal or numeric can result in overflow.

If you perform arithmetic on two exact numeric values, v1 and v2, where v1 has a precision of p1 and a scale of s1, and where v2 has a precision of p2 and s2, the precision and scale of the result depends on the operator (with an absolute maximum of @@MAX_PRECISION) and is determined as follows:

Operation	Precision	Scale
v1 + v2	max(s1,s2) + max(p1−s1,p2−s2)	max(s1,s2)
v1 − v2	max(s1,s2) + max(p1−s1,p2−s2)	max(s2,s2)
v1 * v2	s1 + s2 + (p1−s1) + (p2−s2) + 1	s1 + s2
v1 / v2	max(s1+p2−s2+1,6) + p1 + p2 + 1	max(s1+p2−s2+1,6)
By default, SQL Server uses rounding when converting a number to a decimal or numeric value with a lower precision and scale. However, if the ARITHABORT option is enabled (using the SET statement), SQL Server cancels a query and raises a precision error when an exact numeric operation would result in a loss of precision and scale.

Examples

A.	Convert to Character Data with SELECT

This example shows how to convert data for display.

SELECT title, CONVERT(char(12), ytd_sales)

FROM titles

B.	Convert to Character Data in WHERE Clause

This example converts sales data to character data prior to performing a string comparison.

SELECT title, ytd_sales

FROM titles

WHERE CONVERT(char(20), ytd_sales) LIKE '1%'

C.	Convert to Character Data from the Date Function GETDATE( )

This example converts the current date to style 3, dd/mm/yy.

SELECT CONVERT(char(12), GETDATE(), 3)


Date Functions

Date functions manipulate datetime values. Date functions can be summarized as follows:

Syntax

date_ function (parameters)

where

date_ function

Specifies a date function.

The date functions are:

Date function	Description
DATEADD (datepart, number, date)	Produces a date by adding an interval to a specified date. The result is a datetime value equal to the date plus the number of date parts.  If the date parameter is a smalldatetime value, the result is also a smalldatetime. You can use DATEADD to add seconds or milliseconds to a smalldatetime value, but the addition is meaningful only where the resulting date changes by at least 1 minute.
DATEDIFF (datepart, date1, date2)	Returns the number of datepart "boundaries" crossed between two specified dates. The method of counting crossed boundaries makes the result given by DATEDIFF consistent across all datatypes such as minutes, seconds, and milliseconds.  DATEDIFF takes three parameters. The first is a datepart; the second and third are dates, either datetime or smalldatetime values. The result is a signed integer value equal to the number of datepart boundaries crossed between date2 minus date1. For example, the number of weeks between Sunday, January 4 and Sunday, January 11, is 1.  DATEDIFF produces an error if the result is out 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. If smalldatetime values are used, they are converted to datetime values internally for the calculation. Seconds and milliseconds in smalldatetime values are set to 0 for calculating the difference.
DATENAME (datepart, date)	Returns a character string representing the specified date part (datepart) of the specified date (date).
DATEPART (datepart, date)	Returns an integer representing the specified date part (datepart) of the specified date (date).
GETDATE()	Returns the current system date and time in the SQL Server standard internal format for datetime values. GETDATE does not take any parameters.
date

Can be either the GETDATE function, a character string in date format, or the name of a datetime column.

datepart

Is a parameter used with DATEADD, DATEDIFF, DATENAME, and DATEPART. The following table lists the date parts, the abbreviations recognized by SQL Server, and the acceptable values:

Date part	Abbreviation	Values
year	yy	1753−9999
quarter	qq	1−4
month	mm	1−12
day of year	dy	1−366
day	dd	1−31
week	wk	1−53
weekday	dw	1−7 (Sun.−Sat.)
hour	hh	0−23
minute	mi	0−59
second	ss	0−59
millisecond	ms	0−999
If the year is given with two digits, <50 is the next century and >=50 is this century. So "25" is "2025," and "50" is "1950."

Milliseconds can be preceded by either a colon or a period. If preceded by a colon, the number means thousandths of a second. If preceded by a period, a single digit means tenths of a second, two digits mean hundredths of a second, and three digits mean thousandths of a second. For example, "12:30:20:1" means 20 and one-thousandth seconds past 12:30; "12:30:20.1" means 20 and one-tenth seconds past 12:30.

Use the datetime datatype for dates after January 1, 1753. When entering datetime values, always enclose them in quotation marks. Use char or varchar for earlier dates.

SQL Server automatically converts between character and datetime values when necessary — for example, when you compare a character value with a datetime value.

The date part weekday or dw returns the day of the week (Sunday, Monday, and so on) when used with datename. It returns a corresponding number (Sunday = 1, Saturday = 7) when used with datepart. Using weekday or dw with DATEADD and DATEDIFF is not logical and produces spurious results. Use day or dd instead.

Because smalldatetime is accurate only to the minute, when a smalldatetime value is used with either datename or datepart seconds and milliseconds are always 0.

Remarks

Date functions can be used in the select list or in the WHERE clause of a query.

Use the datetime datatype only for dates after January 1, 1753. When entering datetime values, always enclose them in quotation marks. Store as character data for earlier dates. SQL Server recognizes a wide variety of date styles. For more information about date and time data, see the Datatypes topic and CONVERT Function.

Examples

A.	DATEADD Function

This example prints a listing of a "timeframe." This timeframe represents the existing publication date plus 21 days.

SELECT timeframe = DATEADD(day, 21, pubdate)

FROM titles

B.	DATEDIFF Function

This example determines the difference in days between the current date and the publication date.

SELECT newdate = DATEDIFF(day, pubdate, getdate())

FROM titles

C.	DATEDIFF Function Changes in SQL Server 6.0

This example shows the difference in results of the new DATEDIFF function in SQL Server 6.0.

In earlier releases:

SELECT "Number of Minutes" = DATEDIFF(minute, 'jan 1 1995 22:30:16', 'jan 1 1995 23:30:15')

go

Number of Minutes
------------------------
59

In SQL Server 6.0

SELECT "Number of Minutes" = DATEDIFF(minute, 'jan 1 1995 22:30:16', 'jan 1 1995 23:30:15')

go

Number of Minutes
------------------------
60

The difference is minor; however, it accurately reflects that 60 "minute boundaries" were crossed.

D.	DATENAME and DATEPART Functions

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 some other date functions.

SELECT "Current Date" = getdate()

go

Current Date
---------------------------
Feb 18 1995 11:46PM

SELECT "Month Name" = DATENAME(month, getdate())

go

Month Name
------------------------------
February

SELECT "Month Number" = DATEPART(month, getdate())

go

Month Number
------------
2


Mathematical Functions

Mathematical functions return values commonly needed for operations on mathematical data. Mathematical function names are not keywords.

Syntax

function_name(parameters)

where

function_name

Specifies a mathematical function.

These are the mathematical functions:

Function	Parameters	Result
ABS	(numeric_expr)	Absolute value of the numeric expression. Results returned are of the same type as numeric_expr.
ACOS	(float_expr)	Angle (in radians) whose cosine is the specified approximate numeric (float) expression.
ASIN	(float_expr)	Angle (in radians) whose sine is the specified approximate numeric (float) expression.
ATAN	(float_expr)	Angle (in radians) whose tangent is the specified approximate numeric (float) expression.
ATN2	(float_expr1,  float_expr2)	Angle (in radians) whose tangent is (float_expr1/float_expr2) between two approximate numeric (float) expressions.
CEILING	(numeric_expr)	Smallest integer greater than or equal to the numeric expression. Result returned is the integer portion of the same type as numeric_expr.
COS	(float_expr)	Trigonometric cosine of the specified angle (in radians) in an approximate numeric (float) expression.
COT	(float_expr)	Trigonometric cotangent of the specified angle (in radians) in an approximate numeric (float) expression.
DEGREES	(numeric_expr)	Degrees converted from radians of the numeric expression. Results are of the same type as numeric_expr.
EXP	(float_expr)	Exponential value of the specified approximate numeric (float) expression.
FLOOR	(numeric_expr)	Largest integer less than or equal to the specified numeric expression. Result returned is the integer portion of the same type as numeric_expr.
LOG	(float_expr)	Natural logarithm of the specified approximate numeric (float) expression.
LOG10	(float_expr)	Base-10 logarithm of the specified approximate numeric (float) expression.
PI	( )	Constant value of 3.141592653589793.
POWER	(numeric_expr, y)	Value of numeric expression to the power of y, where y is a numeric datatype (decimal, float, int, money, numeric, real, smallint, smallmoney, or tinyint). Result is of the same type as numeric_expr.
RADIANS	(numeric_expr)	Radians converted from degrees of the numeric expression. Result is of the same type as numeric_expr.
RAND	([seed])	Random approximate numeric (float) value between 0 and 1, optionally specifying an integer expression (tinyint, smallint, or int) as the seed.
ROUND	(numeric_expr, length)	Numeric expression rounded off to the length (or precision) specified as an integer expression (tinyint, smallint, or int). Result is of the same type as numeric_expr. The ROUND function always returns a value even if the length is illegal. If the specified length is positive and longer than the digits after the decimal point, 0 is added after the fraction digits. If the length is negative and larger than or equal to the digits before the decimal point, ROUND returns 0.00.
SIGN	(numeric_expr)	Returns the positive (+1), zero (0), or negative (−1) sign of the numeric expression. Result is of the same type as numeric_expr.
SIN	(float_expr)	Trigonometric sine of the specified angle (measured in radians) in an approximate numeric (float) expression.
SQRT	(float_expr)	Square root of the specified approximate numeric (float) expression.
TAN	(float_expr)	Trigonometric tangent of the specified angle (measured in radians) in an approximate numeric (float) expression.
where

numeric_expr

Is an expression of the decimal, float, int, money, numeric, real, smallint, smallmoney, or tinyint datatype.

float_expr

Is an expression of the float datatype.

Remarks

Internal conversion to float can cause loss of precision if the money datatype is used.

Error traps are provided to handle domain or range errors of these functions. A user can set the options ARITHABORT, which terminates the query, or ARITHIGNORE, which returns NULL, when a domain error occurs. No warning message is displayed. If neither of these options is set, SQL Server returns NULL and returns a warning message after the query is executed.

Examples

A.	FLOOR Function

This example shows positive numeric, negative numeric, and money values with the FLOOR function. The result returned is the integer portion of the same datatype as the expression. Note that the money datatype always returns a two-place decimal value but no dollar sign ($).

Statement	Result
SELECT FLOOR(123.45)	123
SELECT FLOOR(-123.45)	-124
SELECT FLOOR($123.45)	123.00
B.	CEILING Function

This example shows positive numeric, negative numeric, and money values with the CEILING function. The result returned is the integer portion of the same datatype as the expression. Note that the money datatype always returns a two-place decimal value but no dollar sign ($).

Statement	Result
SELECT CEILING(123.45)	124
SELECT CEILING(-123.45)	-123
SELECT CEILING($123.45)	124.00
C.	The ROUND Function

This example shows rounding and approximations. The result returned is always the same datatype as the expression. Note that the money datatype always returns a two-place decimal value but no dollar sign ($).

Statement	Result
SELECT ROUND(123.4545, 2)	123.4500
SELECT ROUND(123.45, -2)	100.00
With the ROUND function, the last digit is always an estimate:

ROUND(123.9994, 3) = 123.9990

and

ROUND(123.9995, 3) = 124.0000


Row Aggregate Functions

Row aggregate functions generate summary values that appear as additional rows in the query results (unlike the aggregate function results, which appear as new columns). They allow you to see detail and summary rows in one set of results. Row aggregate functions (SUM, AVG, MIN, MAX, and COUNT) are used in a SELECT statement with the COMPUTE clause. You can calculate summary values for subgroups, and you can calculate more than one aggregate function for the same group. COMPUTE and the row aggregate functions are Transact-SQL enhancements to standard SQL.

Syntax

COMPUTE row_aggregate [, row_aggregate...]
[BY expression [, expression]...]

where

row_aggregate

Specifies the row aggregate function.

These are the row aggregate functions:

Aggregate function	Result
SUM(expression)	Returns the total of the values in the numeric column.
AVG(expression)	Returns the average of the values in the numeric column.
COUNT(expression)	Returns the number of non-null values in the column.
MAX(expression)	Returns the highest value in the column.
MIN(expression)	Returns the lowest value in the column.
BY

Indicates that row aggregate function values are to be calculated for subgroups. Whenever the value of the BY item changes, row aggregate function values are generated. If you use BY, you must use ORDER BY. Listing more than one item after BY breaks a group into subgroups and applies a function at each group level.

expression

Follows the rules for expressions as defined in the Expressions topic; however, when used as a row aggregate function, an expression is usually the name of a column. The expression must be enclosed in parentheses. Only numeric expressions (expressions that result in a decimal, float, int, money, numeric, real, smallint, smallmoney, or tinyint datatype) can be used with SUM and AVG. One COMPUTE clause can apply the same function to several columns or several functions to one column. When using more than one function, use more than one COMPUTE clause.

Remarks

The row aggregate functions make it possible to retrieve detail rows and summary rows with one statement. The aggregate functions, in contrast, ordinarily produce a single value for all selected rows in the table or for each group, and these summary values are shown as new columns.

The columns in the COMPUTE clause must appear in the select list.

You can't use SELECT INTO in the same statement as a COMPUTE clause because statements that include COMPUTE generate tables that include the summary results, which are not stored in the database.

If you use COMPUTE BY, you must also use an ORDER BY clause. The columns listed after COMPUTE BY must be identical to or a subset of those listed after ORDER BY, and they must be in the same left-to-right order, start with the same expression, and not skip any expressions. For example, if the ORDER BY clause is:

ORDER BY a, b, c

The COMPUTE BY clause can be any or all of these:

COMPUTE BY a, b, c

COMPUTE BY a, b

COMPUTE BY a

You must use a column name or an expression in the ORDER BY clause.

The COMPUTE keyword can be used without BY to generate grand totals, grand counts, and so on. ORDER BY is optional if you use the COMPUTE keyword without BY.

When you sum or average integer data, SQL Server treats the result as an int value, even if the datatype of the column is smallint or tinyint.

Note  To reduce the possibility of overflow errors in DB-Library programs, make all variable declarations for the results of averages or sums type int.

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. DB-Library programmers must be aware of this order requirement to put the aggregate function results in the correct place. For example:

SELECT a, b, c
FROM test
COMPUTE SUM(c), MAX(b), MIN(a)
a	b	c
---------	----------	----------
1	2	3
3	2	1
		sum
		=======
		4
	max
	=======
	2
min
=========
1
(3 rows affected)
Examples

A.	Aggregates and Row Aggregates

The following two examples illustrate 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.

Aggregate Functions

SELECT type, SUM(price), SUM(advance)

FROM titles

WHERE type LIKE '%cook'

GROUP BY type

type
----------	----------	------------
mod_cook	22.98	15,000.00
trad_cook	47.89	19,000.00
(2 rows affected)
Row Aggregates

SELECT type, price, advance

FROM titles

WHERE type LIKE '%cook'

ORDER BY type

COMPUTE SUM(price), SUM(advance) BY type

type	price	advance
----------	------------	------------
mod_cook	2.99	15,000.00
mod_cook	19.99	0.00
	sum	sum
	------------	------------
	22.98	15,000.00
type	price	advance
----------	------------	------------
trad_cook	20.95	7,000.00
trad_cook	14.99	8,000.00
trad_cook	11.95	4,000.00
	sum	sum
	------------	------------
	47.89	19,000.00
(7 rows affected)
B.	Group Totals with COMPUTE BY

This example calculates the sum of the all prices (for prices over $10) for each type of cookbook, in order first by type of book and then by price of book.

SELECT type, price

FROM titles

WHERE price > $10

AND type LIKE '%cook'

ORDER BY type, price

COMPUTE SUM(price) BY type

type	price
-----------	---------
mod_cook	19.99
	sum
	---------
	19.99
type	price
------------	---------
trad_cook	11.95
trad_cook	14.99
trad_cook	20.95
	sum
	---------
	47.89
(6 rows affected)


String Functions

String functions perform various operations on binary data, character data, and expressions. String functions can be used anywhere an expression is allowed to return values commonly needed for operations on character data and string concatenation. Various system functions, such as COL_LENGTH and DATALENGTH, can also prove useful. For details, see System Functions, later in this topic.

With the exception of the PATINDEX function, string functions can be used only on char, varchar, binary, and varbinary datatypes, plus those datatypes that convert implicitly to char or varchar. The PATINDEX function can be used on char, varchar, and text datatypes. For functions specifically designed to manipulate text and image data, see the text and image Manipulation topic.

Syntax

function_name(parameters)

where

function_name

Specifies a string function.

These are the string functions:

Function	Parameters	Result
+	(expression + expression)	Concatenates two character strings, binary strings, column names, or a combination of them. Enclose character strings in quotation marks. When concatenating non-character, non-binary expressions, always use the CONVERT function.
ASCII	(char_expr)	Indicates the ASCII code value of the leftmost character of a character expression.
CHAR	(integer_expr)	Converts a character from an ASCII code. The ASCII code should be a value from 0 through 255; otherwise, NULL is returned.
CHARINDEX	('pattern',  expression)	Returns the starting position of the specified pattern. A pattern is a char_expr. The second parameter is an expression, usually a column name, in which SQL Server searches for the pattern.
DIFFERENCE	(char_expr1, char_expr2)	Shows the difference between the values of two character expressions as returned by the SOUNDEX function. The DIFFERENCE function compares two strings and evaluates the similarity between them, returning a value from 0 through 4. The value 4 is the best match.
LOWER	(char_expr)	Converts uppercase character data to lowercase.
LTRIM	(char_expr)	Removes leading blanks.
PATINDEX	('%pattern%', expression)	Returns the starting position of the first occurrence of pattern in the specified expression, or zeros if the pattern is not found. You can use wildcard characters in pattern, as long as the wildcard character % precedes and follows pattern (except when searching for first or last characters). The expression is usually a column name. You can use this function on text, char, and varchar data.
REPLICATE	(char_expr, integer_expr)	Repeats a character expression a specified number of times. If integer_expr is negative, a null string is returned.
REVERSE	(char_expr)	Returns the reverse of char_expr. This function takes a constant, variable, or column as its parameter.
RIGHT	(char_expr, integer_expr)	Part of a character string starting integer_expr characters from the right. If integer_expr is negative, a null string is returned.
RTRIM	(char_expr)	Removes trailing blanks.
SOUNDEX	(char_expr)	Returns a four-digit (SOUNDEX) code to evaluate the similarity of two strings. The SOUNDEX function converts an alpha string to a four-digit code to find similar-sounding words or names. Vowels are ignored unless they are the first letter of the string.
SPACE	(integer_expr)	Returns a string of repeated spaces. The number of spaces is equal to integer_expr. If integer_expr is negative, a null string is returned.
STR	(float_expr [, length  [, decimal]])	Returns character data converted from numeric data. The length is the total length, including decimal point, sign, digits, and spaces. The decimal value is the number of spaces to the right of the decimal point. Both length and decimal are optional. The default for length is 10. Do not use a function or subquery as the float_expr in the STR function. A short float_expr is right-justified in the specified length, and a long float_expr is truncated to the specified number of decimal places.
STUFF	(char_expr1, start, length, char_expr2)	Deletes length characters from char_expr1 at start and then inserts char_expr2 into char_expr1 at start.  If the start position or the length is negative, a null string is returned. If the start position is longer than char_expr1, a null string is returned. If the length to delete is longer than char_expr1, it is deleted to the first character in char_expr1.
SUBSTRING	(expression, start, length)	Returns part of a character or binary string. The first parameter can be a character or binary string, a column name, or an expression that includes a column name. (Do not use expressions that include functions.) The second parameter specifies where the substring begins. The third parameter specifies the number of characters in the substring.
UPPER	(char_expr)	Converts lowercase character data to uppercase.
where

char_expr

Is an alphanumeric expression of character data.

integer_expr

Is a positive whole number.

float_expr

Is an approximate numeric (float) datatype with a decimal point.

Remarks

String functions can be nested.

Examples

A.	String Concatenation

Creating one result from multiple character columns can be achieved through string concatenation. This example creates a single column (under the column heading Name) in order of last name followed by first name with a comma after the last name in the authors table:

SELECT Name = (au_lname + ', ' + au_fname)

FROM authors

B.	SUBSTRING Function

This example shows how to return only a portion of a character string. From the authors table, this query will return the last name in one column with only the first initial in the second column.

SELECT au_lname, SUBSTRING(au_fname, 1, 1)

FROM authors

C.	Combining Functions and String Concatenation

This example creates a single column (under the column heading Name) in order of last name, first initial with a comma after the last name in the authors table.

SELECT Name = (au_lname + ', ' + SUBSTRING(au_fname, 1, 1) + '.')

FROM authors

D.	Combining Functions and Concatenation in Any Order

This example displays the first six characters of the concatenation of each pub_id and title_id. It displays all four characters of the pub_id and the first two characters of the title_id.

SELECT SUBSTRING ((pub_id + title_id), 1, 6)

FROM titles

E.	CHARINDEX Function

This example returns the position at which the pattern 'wonderful' begins in the notes column of titles:

SELECT CHARINDEX('wonderful', notes)

FROM titles

WHERE title_id = 'TC3218'

F.	STUFF Function

This example returns a character string created by deleting three characters from the first string ('abcdef') starting at position 2 (at 'b') and inserts the second string at the deletion point. The resulting string is 'aijklmnef':

SELECT STUFF('abcdef', 2, 3, 'ijklmn')

G.	SOUNDEX and DIFFERENCE Functions

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' will return the same SOUNDEX result because all vowels (and y) are not included.

SELECT SOUNDEX ('Smith'), SOUNDEX ('Smythe')

-----	-----
S530	S530
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 will be 4 (lowest possible difference).

SELECT DIFFERENCE('Smithers', 'Smothers')

In this example, the strings differ in consonants, so the difference returned will be 2 (higher difference).

SELECT DIFFERENCE('Smothers', 'Brothers')


System Functions

System functions return special information from the server or database.

Syntax

function_name(parameters)

where

function_name

Specifies a system function.

These are the system functions:

System function	Parameters	Result
COALESCE	(expression1, expression2, ... expressionN)	Returns the first non-null expression. For details, see the CASE statement.
COL_LENGTH	('table_name',  'column_name')	The defined length of a column.
COL_NAME	(table_id,  column_id)	The name of the column.
DATALENGTH	('expression')	The actual length of an expression of any datatype. Because varchar, varbinary, text, and image datatypes can store variable-length data, DATALENGTH is especially useful with those datatypes. The DATALENGTH of any null data returns NULL. For all other datatypes, DATALENGTH reports their defined length (because NON NULL fixed-width character data is always right-padded with spaces).
DB_ID	(['database_name'])	The database identification number.
DB_NAME	([database_id])	The database name.
GETANSINULL	(['database_name'])	The default nullability for the database. This function returns 1 when the nullability is the ANSI NULL default. A column or datatype whose nullability is not explicitly defined will be set to allow null values.
HOST_ID	( )	The workstation identification number.
HOST_NAME	( )	The workstation name.
IDENT_INCR	('table_name')	The increment value (returned as numeric(@@MAXPRECISION,0)) specified during creation of an identity column.
IDENT_SEED	('table_name')	The seed value (returned as numeric(@@MAXPRECISION,0)) specified during creation of an identity column.
INDEX_COL	('table_name',  index_id, key_id)	The indexed column name.
ISNULL	(expression, value)	Replaces NULL entries with the specified value.
NULLIF	(expression1, expression2)	The resulting expression is NULL when expression1 is equivalent to expression2. For details, see the CASE statement.
OBJECT_ID	('object_name')	The database object identification number.
OBJECT_NAME	(object_id)	The database object name.
STATS_DATE	(table_id, index_id)	The date that the statistics for the specified index (index_id) were last updated.
SUSER_ID	(['login_name'])	The user's login identification number.
SUSER_NAME	([server_user_id])	The user's login identification name.
USER_ID	(['user_name'])	The user's database identification number.
USER_NAME	([user_id])	The user's database username.
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 the Expressions topic.

The system administrator's server user identification number is always 1. Server user identification number −1 is always reserved for a guest account. The user identification number of the database owner is always 1.

Examples

A.	USER_ID Function

This example returns Harold's identification number, 13.

SELECT USER_ID('Harold')

B.	USER_NAME Function

This example returns the username for user number 13, Harold.

SELECT USER_NAME(13)

C.	ISNULL Function

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.

SELECT AVG(ISNULL(price, $10.00))

FROM titles

D.	COL_LENGTH Function

This example finds the length of the title column in the titles table. The x gives a column heading to the result.

SELECT x = COL_LENGTH('titles', 'title')

E.	DATALENGTH Function

This example finds the length of the pub_name column in the publishers table.

SELECT length = DATALENGTH(pub_name), pub_name

FROM publishers

F.	USER_NAME Function in 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)

G.	STATS_DATE Function

This example returns the date of the last time that the statistics were updated for the specified object (the distribution information was updated).

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


Text and Image Functions

Text and image functions return values commonly needed for operations on text and image data only. Text and image built-in function names are not keywords.

Syntax

function_name(parameters)

where

function_name

Specifies a text or image function.

These are the text and image functions:

Function	Parameters	Result
TEXTPTR	(column_name)	The text-pointer value in varbinary format. The text pointer is checked to ensure that it points to the first text page.
TEXTVALID	('table_name.column_name', text_ ptr)	Checks whether a given text pointer is valid. 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.
Remarks

If a text 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.

In addition to these specific text and image functions, the following functions and statement are also useful with text and image data:

Function or statement	Description
PATINDEX('%pattern%',  expression)	The character position of a given character string in text columns. For details, see "String Functions" earlier in this topic.
DATALENGTH(expression)	The length of data in text and image columns. For details, see "System Functions," earlier in this topic.
SET TEXTSIZE	The limit, in bytes, of the text or image data to be returned with a SELECT statement. For details, see the SET statement.
Examples

A.	TEXTPTR Function

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.

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'

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.

SELECT pub_id, TEXTPTR(pr_info) FROM pub_info

To return the first 255 bytes of text:

SELECT pub_id, pr_info FROM pub_info

C.	TEXTVALID Function

This example reports whether a valid text pointer exists for each value in the logo column of the pub_info table.

SELECT pub_id, 'Valid (if 1) Text data'
= TEXTVALID ('pub_info.logo', TEXTPTR(logo))

FROM pub_info


GRANT Statement

For more updated SQL Server 6.5 syntax, see GRANT Statement.

Assigns permissions to users.

Syntax

Statement permissions:

GRANT {ALL | statement_list}
TO {PUBLIC | name_list}

Object permissions:

GRANT {ALL | permission_list}
ON {table_name [(column_list)] | view_name [(column_list)] |
stored_procedure_name | extended_stored_procedure_name}
TO {PUBLIC | name_list}

where

ALL

When used to assign object permissions, specifies that all permissions applicable to the specified object are granted or revoked. When used to assign statement permissions, only the system administrator can use ALL, since only the system administrator can grant or revoke CREATE DATABASE permission.

statement_list

Lists statements granted. The statement list can include CREATE DATABASE (if the user executing the statement is the system administrator), CREATE DEFAULT, CREATE PROCEDURE, CREATE RULE, CREATE TABLE, CREATE VIEW, DUMP DATABASE, and DUMP TRANSACTION.

If more than one statement is listed, separate them with commas.

PUBLIC

Specifies all users, including those who are a member of another group in addition to public.

name_list

Lists users' database names and/or group names, separated by commas. These names are stored in the database's sysusers table.

permission_list

Lists permissions granted. When permissions are granted on a table or a view, the permission list can include one or more of the following items: SELECT, INSERT, DELETE, and UPDATE.

Permissions granted on a table can also include REFERENCES. REFERENCES allows a user to create FOREIGN KEY constraints that reference another table without having SELECT permission on that table. REFERENCES permission needs to be granted only to the person creating the FOREIGN KEY.

When permissions are granted on columns, the permission list can include SELECT and/or UPDATE.

When permissions are granted on stored procedures, the permission list can include EXECUTE only.

If multiple permissions are listed, separate them with commas.

table_name

Specifies a table in the current database. Only one table can be listed for each GRANT statement.

column_list

Lists names of columns, separated by commas, to which the permissions apply. If columns are specified, only SELECT and UPDATE permissions can be granted.

view_name

Specifies a view in the current database. Only one view can be listed for each GRANT statement.

stored_procedure_name

Is the name of a stored procedure in the current database. Only one stored procedure can be listed for each GRANT statement.

extended_stored_procedure_name

Is the name of an extended stored procedure in the current database. Only one extended stored procedure can be listed for each GRANT statement.

Remarks

Permission to use a statement or object defaults to the system administrator, the database owner, the object owner, or the default group public. Some permissions are transferable. When possible, the user to whom the permissions default can transfer permission to other users. Users at higher levels (the database owner and system administrator) are either automatically granted the permission or (in the case of database owners) can temporarily obtain permissions.

By default, the system administrator has all permissions. The system administrator can assign a database owner by using the sp_changedbowner system stored procedure. Once assigned, a database owner (or the system administrator) can GRANT "statement" permissions to users within that database. Once a user has been given "statement" permissions, he or she can create an object. That user becomes the object owner of the object(s) he or she has created. Object owners always retain rights to their object(s). "Object" permissions must be granted to other users before they can access that object.

Database users can belong to only one group in addition to the group public. Users are always a member of the group public. For permissions that default to public, no permission is required — that is, no explicit GRANT or REVOKE statement must be executed.

When permissions are given, information is stored within the sysprotects table. The sysprotects table manages permissions by updating rows based on each GRANT and REVOKE statement. You can grant or revoke permissions only on objects in the current database.

If permissions are granted to the group public, they will override any previous permissions given to any other user or group of that database. When permissions are given (or revoked) the permissions are order-sensitive. (The statement executed most recently is the one that takes effect.) This can produce undesired results if care is not taken in granting/revoking permissions. For best results, grant/revoke permissions to the least-selective group first (usually public), then grant/revoke permissions on a group-by-group basis, on an individual-by-individual basis, and then to/from the guest user.

A guest user can be added by using the sp_adduser system stored procedure to allow users with login IDs on SQL Server to use the database without a specific database username (and usually with limited permissions).

The sp_helprotect system stored procedure reports permissions on a database object or on a user. For details, see the sp_helprotect system stored procedure.

Permission

GRANT and REVOKE permission defaults to particular users and cannot be transferred.

The following table details permissions for Transact-SQL statements:

	Defaults to					Can be  granted /revoked
Statement	System admin	DB  owner	Object owner	Public		Yes	No	N/A
ALTER DATABASE	—	X	—	—		(1)	—	—
ALTER TABLE	—	—	X	—		—	X	—
BEGIN TRANSACTION	—	—	—	X		—	—	X
CHECKPOINT	—	X	—	—		—	X	—
COMMIT TRANSACTION	—	—	—	X		—	—	X
CREATE DATABASE	X	—	—	—		X	—	—
CREATE DEFAULT	—	X	—	—		X	—	—
CREATE INDEX	—	—	X (3)	—		—	X	—
CREATE PROCEDURE	—	X	—	—		X	—	—
CREATE RULE	—	X	—	—		X	—	—
CREATE TABLE	—	X	—	(2)		X (2)	—	—
CREATE TRIGGER	—	—	X (3)	—		—	X	—
CREATE VIEW	—	X	—	—		X	—	—
DBCC (4)	—	X	—	—		—	X	—
DELETE	—	—	X	—		X	—	—
DISK INIT	X	—	—	—		—	X	—
DISK MIRROR	X	—	—	—		—	X	—
DISK REFIT	X	—	—	—		—	X	—
DISK REINIT	X	—	—	—		—	X	—
DISK REMIRROR	X	—	—	—		—	X	—
DISK UNMIRROR	X	—	—	—		—	X	—
DROP any object	—	—	X	—		—	X	—
DUMP DATABASE	—	X	—	—		X	—	—
DUMP TRANSACTION	—	X	—	—		X	—	—
EXECUTE  (5)	—	—	X	—		X	—	—
GRANT	—	X	—	—		—	X	—
GRANT on object	—	—	X	—		—	X	—
INSERT	—	—	X	—		X	—	—
KILL	X	—	—	—		—	X	—
LOAD DATABASE	—	X	—	—		—	X	—
LOAD TRANSACTION	—	X	—	—		—	X	—
PRINT	—	—	—	X		—	—	X
RAISERROR	—	—	—	X		—	—	X
READTEXT	—	—	X	—		(6)	—	—
RECONFIGURE	X	—	—	—		—	X	—
REFERENCES	—	—	X	—		X	—	—
REVOKE	—	X	—	—		—	X	—
REVOKE on object	—	—	X	—		—	X	—
ROLLBACK TRANSACTION	—	—	—	X		—	—	X
SAVE TRANSACTION	—	—	—	X		—	—	X
SELECT	—	—	X	—		X	—	—
SET	—	—	—	X		—	—	X
SETUSER	—	X	—	—		—	X	—
SHUTDOWN	X	—	—	—		—	X	—
TRUNCATE TABLE	—	—	X	—		—	X	—
UPDATE	—	—	X	—		X	—	—
UPDATE STATISTICS	—	—	X	—		—	X	—
UPDATETEXT	—	—	X	—		(7)	—	—
WRITETEXT	—	—	X	—		(7)	—	—
(1) Transferred with CREATE DATABASE permission.
(2) Public can create temporary tables; no permission required.
(3) Defaults to the table owner.
(4) For the list of all DBCC statement permissions see the DBCC statement.
(5) Defaults to stored-procedure owner.
(6) Transferred with SELECT permission.
(7) Transferred with UPDATE permission.
Examples

A.	Grant "Statement" Permissions

This example shows how to grant multiple statement permissions to multiple users.

GRANT CREATE DATABASE, CREATE TABLE

TO Mary, John

B.	Grant "Object" Permissions/Permission Hierarchy

This example shows preferred ordering of permissions. First, SELECT permissions are given to the group public. After this, specific permissions are given to a few users. These users (Mary, John, and Tom) then have all permissions to the authors table.

GRANT SELECT

ON authors

TO public

go

GRANT INSERT, UPDATE, DELETE

ON authors

TO Mary, John, Tom

See Also

REVOKE	sp_changegroup
SETUSER	sp_dropgroup
sp_addgroup	sp_dropuser
sp_addlogin	sp_helpgroup
sp_adduser	sp_helprotect
sp_changedbowner	sp_helpuser


Identifiers

Identifiers define the naming convention used by SQL Server for server names; database names; and database objects such as tables, views, columns, indexes, triggers, procedures, defaults, rules, and so on.

Rules for Identifiers

Identifiers can contain from 1 to 30 characters, including letters, symbols, and numbers. Identifiers have the following requirements:

•	The first character of the identifier must be a letter or the symbols _ ,@ , #. The symbols @ and # have special meaning:

•	An identifier beginning with @ signifies a local variable.

•	An identifier beginning with # signifies a temporary object name. For a table or stored procedure, a single pound sign (#) signifies a local temporary object; a double pound sign (##) signifies a global temporary object. Names for temporary objects should not exceed 13 characters, including the # or ##, because SQL Server gives them an internal numeric suffix. For more information on creating these temporary objects, see the CREATE PROCEDURE and CREATE TABLE statements.

•	Characters following the first character can include letters, digits, or the symbols #, $, or _.

•	By default, no embedded spaces are allowed in identifiers; however, by using quoted identifiers, spaces and other special identifiers can be defined. For the rules and restrictions on quoted identifiers, see "Quoted Identifiers," later in this topic.

Identifiers as Object Names

Object names need not be unique in a database. However, column names and index names must be unique within a table or a view, and other object names must be unique for each owner within a database. Database names must be unique on SQL Server. You can uniquely identify a table or column by fully qualifying it—the database name, the owner's name, and (for a column) the table or view name. Each of these qualifiers is separated from the next by a period:

[[database.]owner.]table_name
[[database.]owner.]view_name

The database and owner names are optional. The default value for owner is the current user; the default value for database is the current database.

Intermediate elements in a name can be omitted and their positions indicated by periods, as long as the system is given enough information to identify the object:

database..table_name
database..view_name

In the case of remote stored procedures, a procedure is qualified as follows:

server.database.owner.procedure

For example:

remotesvr.pubs.dbo.sp_who

Object Visibility (and Qualification) Rules

If you reference an object without qualifying it with the database name and owner name, SQL Server tries to find the object in the current database among the objects you own. If you don't own an object by that name, SQL Server looks for objects of that name owned by the database owner (qualified by database..obj_name). You need not use the database name to reference your objects in the current database. You must qualify objects owned by the database owner only if you own an object by the same name but want to use the object owned by the database owner. You must qualify objects owned by other users with the user's name.

The visibility for a stored procedure that begins with sp_ differ from regular procedures. For information, see the CREATE PROCEDURE statement.


Quoted Identifiers

Support for quoted identifiers has been added to SQL Server 6.0. According to ANSI syntax, use double quotation marks (") to delimit keywords (quoted identifiers), and use single quotation marks (') to delimit string constants. This resolves the conflict with quoted identifiers and string constants during expression evaluation at the parser level. This is included to provide ANSI compatibility for delimited identifiers. Additionally, although not recommended, keywords specified within double quotation marks can now be used as object names. If object names are desired using keywords, reserved words, database technology terms, or names that could cause conflict with future keywords, first attempt to resolve possible conflicts by choosing another word for the object name. When this is not possible, use quoted identifiers.

Quoted identifiers contain as many as 30 characters. The delimited string can contain any combination of characters represented by the current code page, except double quotation marks.

To enforce or remove quoted identifier and string constant resolution at the session level, use the SET statement. This causes the current session to differentiate between single and double quotation marks when evaluating an expression. When QUOTED_IDENTIFIER is turned ON, strings in double quotation marks (") will not be evaluated or checked against keywords.

When you use keywords for object names or portions of object names, the QUOTED_IDENTIFIER option must be set when creating that object, as well as when accessing that object.

Note  If an object name or part of an object name (for example, a column) is created using a keyword when the SET QUOTED_IDENTIFIER option is turned ON, then all subsequent references to that object must be made with the SET QUOTED_IDENTIFIER option ON. In general, it is best to avoid using keywords as object names.

When qualifying a column name and a table name in the same statement, be sure to use the same qualifying expressions for each; they are evaluated as strings and must match or an error is returned.

Examples

A.	Object Names

The following examples show a variety of acceptable table names.

CREATE TABLE thisisatesttablenameof_30_chars

CREATE TABLE Tablenametest

CREATE TABLE Yearly$Sales

CREATE TABLE #T

CREATE TABLE This_is_a_more_clear_table_name

B.	Use Quoted Identifiers

This example shows how quoted identifiers can be used to surround any word(s).

CREATE TABLE "Employee"

	("FName"	varchar(25) not null,
	"LName"	varchar(25) not null,
	"Dept_ID"	int)
Only the table has been created, it can be accessed in a variety of ways:

SELECT * FROM Employee

Or

SELECT * FROM "Employee"

C.	Quoted Identifiers with Keywords

This example shows the required steps to create and access a table created with keywords. In the table named table with columns of names tablename, user, select, insert, and so on, the words table, select, insert, update, and delete are keywords. Every time these objects are accessed, the names must be surrounded with double quotation marks (") and the session option QUOTED_IDENTIFIER must be turned on.

SET QUOTED_IDENTIFIER ON

go

CREATE TABLE "table"

	(tablename	char(30) not null,
	USER	char(30) not null,
	"select"	char(30) not null,
	"insert"	char(30) not null,
	"update"	char(30) not null,
	"delete"	char(30) not null)
go

SET QUOTED_IDENTIFIER OFF

In another session, the QUOTED_IDENTIFIER option must be set again. When quoted identifiers are used to handle keywords, the SET option must be turned on for every session that needs access to that object.

SET QUOTED_IDENTIFIER ON

go

INSERT "table" values ('authors', 'guest', 'all columns', 'all columns',

'all columns', 'all columns')

INSERT "table" values ('authors', 'public', 'all columns',

'not allowed', 'not allowed', 'not allowed')

go

SELECT 'Table Name' = convert(char(10), TABLENAME),

'Permissions' = convert(char(10), USER),

'For SELECT' = convert(char(10), "SELECT")

FROM "table"

go

Table Name Permissions For SELECT

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

authors    guest       all column

authors    public      all column

If the QUOTED_IDENTIFIER session option is not turned on, the keyword names cannot be accessed.

SET QUOTED_IDENTIFIER OFF

go

SELECT * FROM "table"

Msg 170, Level 15, State 1

Line 1: Incorrect syntax near 'table'.

See Also

CREATE DATABASE	CREATE VIEW
CREATE DEFAULT	Datatypes
CREATE PROCEDURE	EXECUTE
CREATE RULE	SELECT
CREATE TABLE	sp_rename
CREATE TRIGGER


INSERT Statement

For more updated SQL Server 6.5 syntax, see INSERT Statement.

Adds a new row to a table or a view.

Syntax

INSERT [INTO]
{table_name | view_name} [(column_list)]
{DEFAULT VALUES | values_list | select_statement}

where

INTO

Is an optional keyword.

table_name | view_name =

[[database_name.]owner.]{table_name | view_name}

Specifies the name of the table or view used in the INSERT statement. If the table or view is not in the current database, use a fully qualified table_name or view_name (database_name.owner.object_name).

column_list

Lists one or more columns to which data is to be added. The columns can be listed in any order, but the incoming data (whether in a values_clause or a select_statement) must be in the same order as the columns.

The column_list is necessary only when some, but not all, columns in the table are to receive data. You can leave out items in the column_list and values_clause as long as the omitted columns are defined to allow null values or the columns have an associated default (a default or a DEFAULT constraint).

Enclose the column_list in parentheses. If column_list is not specified, all columns in the receiving table (in CREATE TABLE order) are assumed to be included.

DEFAULT VALUES

Inserts the default values for all columns. If the column has the IDENTITY property or the timestamp datatype, the next appropriate value will be inserted. If a default for the column does not exist and the column allows NULLs, NULL will be inserted. If any column of the table does not have a default or does not allow NULL, an error will be returned and the INSERT statement rejected.

values_list =

VALUES (DEFAULT | constant_expression
[, DEFAULT | constant_expression]...)

VALUES

Is a required keyword used to introduce the list of values for each column in the column_list or table.

DEFAULT

Inserts the default value for that column. For a column defined with the timestamp datatype, the next value will be inserted. If a default does not exist for the column and the column allows NULLs, NULL will be inserted.

DEFAULT is not valid for an identity column. Columns with the IDENTITY property should not be explicitly listed in the column_list or values_clause; the value for an identity column should not be explicitly entered. For more information, see the CREATE TABLE statement.

constant_expression

Contains an expression that will evaluate to a constant. The list of values must be enclosed in parentheses and must match the explicit or implicit columns list. Enclose non-numeric constants in quotation marks.

select_statement

Is a standard SELECT statement used to retrieve the values to be inserted from an existing table. For details, see the SELECT statement.

Remarks

INSERT adds new rows only. To modify column values in existing rows, use UPDATE.

When inserting rows, these rules apply:

•	Inserting an empty string (' ') into a varchar or text column inserts a single space. All char columns are right-padded to the defined length.

All trailing spaces are removed from data inserted into varchar columns, except in strings that contain only spaces. These strings are truncated to a single space.

•	If an INSERT statement violates a constraint, default, or rule, or if it is the wrong datatype, the statement fails and SQL Server displays an error message.

Constraints are defined with either the CREATE TABLE or ALTER TABLE statement. Defaults are created with the CREATE DEFAULT statement and rules are created with the CREATE RULE statement.

•	Inserting a null value into a text or image column does not create a valid text pointer, nor does it preallocate a 2K text page. For details on inserting text and image data, see the text and image Manipulation topic.

•	An INSERT statement must follow the rules for a batch. For details, see the Batches topic.

When you specify values for only some of the columns in the column_list, one of three things can happen to the columns that have no values:

•	A default value is entered if the column has a DEFAULT constraint, if a default is bound to the column, or a default is bound to the underlying user-defined datatype.

•	NULL is entered if the column allows NULLs and no default value exists for the column.

•	An error message is displayed and the row is rejected if the column is defined as NOT NULL and no default exists.

Permission

INSERT permission defaults to the table owner, who can transfer it to other users.

Examples

A.	INSERT Specifying All Column Values

This example shows an INSERT into the titles table in the pubs database. All column values are specified in the values_clause.

INSERT titles

VALUES('BU2222', 'Faster!', 'business', '1389',

NULL, NULL, NULL, NULL, 'ok', '06/17/87')

B.	INSERT with Column Titles

This example shows an insert into the titles table in the pubs database. Only the values for the columns listed in the column_list are shown in the values_list.

INSERT titles(title_id, title, type, pub_id, notes, pubdate)

VALUES ('BU1237', 'Get Going!', 'business', '1389',

'great', '06/18/86')

C.	INSERT with Nested SELECT

This example inserts all rows from the authors table (for authors only in San Francisco) into the newauthors table.

INSERT INTO newauthors

SELECT *

FROM authors

WHERE city = 'San Francisco'

D.	INSERT with DEFAULT VALUES

This example shows the use (and failure) of the DEFAULT VALUES option for the INSERT statement.

INSERT publishers DEFAULT VALUES

go

Msg 233, Level 16, State 2
The column pub_id in table publishers may not be null.

E.	INSERT with the DEFAULT Keyword

This example shows the use of DEFAULT as a placeholder to insert the DEFAULT value for a column(s).

INSERT employee
VALUES ('KLT91469F', 'Katrina', 'L', 'Thompson', DEFAULT, DEFAULT,
 DEFAULT, '01/14/95')

See Also

CREATE TABLE statement	sp_bindefault system stored procedure
CREATE TRIGGER statement	sp_bindrule system stored procedure
Datatypes	sp_unbindefault system stored procedure
DELETE statement	sp_unbindrule system stored procedure
SELECT statement	UPDATE statement


Keywords

Keywords consist of words reserved by the server to be used to define, manipulate, and access database objects. Keywords can be used for the names of local variables and for stored procedure parameter names. However, until the addition of quoted identifiers, keywords could not be used for the names of databases or database objects, such as tables, rules, defaults, and so on. Quoted identifiers (also known as double quote delimited strings) enable keywords to be used for the names of databases or database objects.

Even though it is syntactically possible, using keywords as object names (with quoted identifiers), it is not recommended. For details, see the Identifiers topic.

Keywords new for SQL Server 6.0 appear in bold type.

ADD	ALL	ALTER
AND	ANY	AS
ASC	AVG	BEGIN
BETWEEN	BREAK	BROWSE
BULK	BY	CASE
CHECK	CHECKPOINT	CLOSE
CLUSTERED	COALESCE	COMMIT
COMMITTED	COMPUTE	CONFIRM
CONSTRAINT	CONTINUE	CONTROLROW
CONVERT	COUNT	CREATE
CURRENT	CURRENT_DATE	CURRENT_TIME
CURRENT_TIMESTAMP	CURRENT_USER	CURSOR
DATABASE	DBCC	DEALLOCATE
DECLARE	DEFAULT	DELETE
DESC	DISK	DISTINCT
DOUBLE	DROP	DUMMY
DUMP	ELSE	END
ERRLVL	ERROREXIT	EXCEPT
EXEC	EXECUTE	EXISTS
EXIT	FETCH	FILLFACTOR
FLOPPY	FOR	FOREIGN
FROM	GOTO	GRANT
GROUP	HAVING	HOLDLOCK
IDENTITY	IDENTITY_INSERT	IDENTITYCOL
IF	IN	INDEX
INSENSITIVE	INSERT	INTERSECT
INTO	IS	ISOLATION
KEY	KILL	LEVEL
LIKE	LINENO	LOAD
MAX	MIN	MIRROREXIT
NOCHECK	NONCLUSTERED	NOT
NULL	NULLIF	OF
OFF	OFFSETS	ON
ONCE	ONLY	OPEN
OPTION	OR	ORDER
OVER	PERM	PERMANENT
PIPE	PLAN	PRECISION
PREPARE	PRIMARY	PRINT
PROC	PROCEDURE	PROCESSEXIT
PUBLIC	RAISERROR	READ
RECONFIGURE	REFERENCES	REPEATABLE
REPLICATION	RETURN	REVOKE
ROLLBACK	ROWCOUNT	RULE
SAVE	SCROLL	SELECT
SERIALIZABLE	SESSION_USER	SET
SETUSER	SHUTDOWN	SOME
STATISTICS	SUM	SYSTEM_USER
TABLE	TAPE	TEMP
TEMPORARY	TEXTSIZE	THEN
TO	TRAN	TRANSACTION
TRIGGER	TRUNCATE	TSEQUAL
UNCOMMITTED	UNION	UNIQUE
UPDATE	UPDATETEXT	USE
USER	VALUES	VARYING
VIEW	WAITFOR	WHEN
WHERE	WHILE	WITH
WRITETEXT


Reserved Words

Reserved words define possible future keywords that may be added for ANSI compliance and/or new features. Because these words may become keywords, they should not be used for object names. These words are reserved for future use:

ABSOLUTE	ACTION	ALLOCATE
ARE	ASSERTION	AT
AUTHORIZATION	BOTH	CASCADE
CASCADED	CAST	CATALOG
CHAR_LENGTH	CHARACTER	CHARACTER_LENGTH
COLLATE	COLLATION	COLUMN
CONNECT	CONNECTION	CONSTRAINTS
CORRESPONDING	DATE	DAY
DEFERRABLE	DEFERRED	DESCRIBE
DESCRIPTOR	DIAGNOSTICS	DISCONNECT
DOMAIN	END_EXEC	ESCAPE
EXCEPTION	EXPIREDATE	EXTERNAL
EXTRACT	FALSE	FILE
FIRST	FULL	GET
GLOBAL	HOUR	IMMEDIATE
INITIALLY	INNER	INPUT
INTERVAL	JOIN	LAST
LEADING	LEFT	LOCAL
MATCH	MINUTE	MONTH
NAMES	NATIONAL	NATURAL
NCHAR	NEXT	NO
OCTET_LENGTH	OUTER	OUTPUT
OVERLAPS	PAD	PARTIAL
POSITION	PRESERVE	PRIOR
PRIVILEGES	RELATIVE	RESTRICT
RETAINDAYS	RIGHT	ROWS
SCHEMA	SECOND	SESSION
SIZE	SPACE	SQLSTATE
TIME	TIMESTAMP	TIMEZONE_HOUR
TIMEZONE_MINUTE	TRAILING	TRANSLATE
TRANSLATION	TRUE	UNKNOWN
USAGE	USING	VALUE
VOLUME	WORK	WRITE
YEAR	ZONE
See Also

Identifiers


KILL Statement

Terminates a user's process based on the system process ID.

Syntax

KILL spid

where

spid

Specifies the system process ID (spid) of the process you want to terminate. The spid is a unique integer (smallint) assigned to processes as they occur; no user is permanently assign a spid. When a process is active, it is stored in the sysprocesses system table.

In addition to storing the ID of the process, the sysprocesses table also stores other process information, such as status (runnable, waiting for a lock, sleeping, and so on), the suid (the server login ID of the user who executed the statement), program_name (the "host_name" of the application program — if not explicitly assigned, usually returns the computer name), and so on.

Remarks

Because an spid is assigned only to active processes, you can get a report on the current processes by executing the sp_who system stored procedure.

This is a typical example:

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   Mary     WKSTA1    0     pubs       AWAITING COMMAND

11     runnable   Joe      WKSTA5    10    pubs       SELECT

The blk column contains the system process ID of a blocking process; if there is one, this value will reference the spid column of this table (self-referencing). A blocking process is one that is holding resources that another process needs. In this example, process 11 (a SELECT on a table) is blocked by process 10 (an uncommitted transaction). Although well-designed transactions should complete quickly and rarely block others, a transaction that does block another transaction can be terminated with the KILL statement.

System processes (MIRROR HANDLER, LAZY WRITER, CHECKPOINT SLEEP, and RA MANAGER) and processes running an extended stored procedure cannot be terminated.

You can get a report on the current locks and each spid of the process holding them by using the sp_lock system stored procedure. The following information is returned when the SA executes sp_lock:

spid   locktype             table_id    page        dbname

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

15     Sh_intent            313052151   0           master

10     Ex_table-blk         16003088    0           pubs

In this example, process 10 has a blocking, exclusive table-lock. Process 15 (the process running sp_lock has a shared intent lock on sysprocesses (the table from which this output is retrieved).

Permission

KILL permission defaults to the system administrator and is not transferable.

Example

This example shows how to terminate the system process ID 10.

KILL 10

See Also

SHUTDOWN	sp_who
sp_lock


LOAD Statement

For more information about how SQL Server 6.5 affects existing database systems and for updated SQL Server 6.5 syntax, see LOAD Statement.

Restores a backup copy of a user database and its transaction log (LOAD DATABASE) or only the transaction log (LOAD TRANSACTION) from a dump that was created using the DUMP statement. The LOAD statement can also be used to retrieve header information from a database dump (LOAD HEADERONLY).

Syntax

Loading a database:

LOAD DATABASE {dbname | @dbname_var}
FROM dump_device [, dump_device2 [..., dump_device32]]
[WITH options
[[,] STATS [ = percentage]]]

Loading a transaction log:

LOAD TRANSACTION {dbname | @dbname_var}
FROM dump_device [, dump_device2 [..., dump_device32]]
[WITH options]

Loading header information:

LOAD HEADERONLY
FROM dump_device

where

dump_device =

{ dump_device_name | @dump_device_namevar}
| {DISK | TAPE | FLOPPY | PIPE} =
{'temp_dump_device' | @temp_dump_device_var}}
[VOLUME = {volid | @volid_var}]

options =

[[,] {UNLOAD | NOUNLOAD}]
[[,] {SKIP | NOSKIP}]
[[,] {FILE = fileno}]

DATABASE

Specifies that the complete database and transaction log are to be restored.

TRANSACTION

Specifies that only the transaction log is to be applied to this database. Transaction logs must be applied in sequential order. SQL Server checks the timestamps on the dumped transaction log to make sure that the transactions are being loaded into the correct database and in the correct sequence.

HEADERONLY

Retrieves all the volume and dump header information for all dumps on a particular dump device. For details about the header information returned, see "Volume and Header Information," later in this topic.

dbname | @dbname_var

Specifies the database from which the transaction log or complete database is being dumped. This name can be specified as a string or as a char or varchar variable.

dump_device_name | @dump_device_namevar

Is the logical name of the dump device as created by sp_addumpdevice. The dump device name can be specified as a string or as a char or varchar variable.

fileno

Is the specific file number to be loaded from the tape or disk device that contains multiple database dumps. The default is 1; load the first dump on the device.

{DISK | TAPE | FLOPPY | PIPE} =

'temp_dump_device' | @temp_dump_device_var

Allows backups to be loaded directly from temporary dump devices. These devices must already exist when the load occurs; they do not have entries in sysdevices. The device types of DISK, TAPE, and FLOPPY should be specified with the actual address (for example, complete path and filename) of the device. A device type of PIPE should specify the name of the named pipe that will be used by the client application. If specified as a variable (@temp_dump_dev_var), the device name can be specified as a string or as a char or varchar variable. If you are using either a network server with a UNC name or a redirected drive letter, specify a device type of DISK.

Important  When specifying a striped dump, you can use both logical device names (or variables) and temporary device names (or variables). PIPE devices have been added to allow third-party vendors a flexible and powerful way to connect their own software. For typical Transact-SQL use, the PIPE device will not be used.

VOLUME = volid | @volid_var

Specifies the volume ID, volid, a 6-byte character string. If dumping to a new tape, this value is the name of the ANSI VOL1 label. For SQL Server, the default is SQ0001. For subsequent dumps, this value is used to validate the volume name of the dump device. If specified as a variable (@volid_var), the volume name can be specified as a string or as a char or varchar variable. It is not necessary, or recommended, to explicitly specify the volume ID.

UNLOAD

Specifies that the tape is automatically rewound and unloaded when the dump 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.

NOUNLOAD

Specifies that the tape will not be unloaded automatically from the tape drive after a dump. NOUNLOAD remains set until UNLOAD is specified. This option is used only for tape devices.

SKIP

Instructs the server not to read the ANSI TAPE device headers.

NOSKIP

Specifies that the server will read ANSI TAPE device headers. This is the default.

STATS = percentage

Returns the percentage of pages loaded in increments optionally set at the time of the load. If the percentage is not specified the statistics will be shown for each 10 percent of the load. This option is available only for database loads.

Remarks

During the load, the specified database must not be in use. Any data in the specified database is replaced by the loaded data.

You can use LOAD DATABASE to move a database to another device or another server as long as the same code page and sort order are running on both servers. If the code page or sort order differs, use the SQL Transfer Manager to move the data. If the sort order and code page are the same, the recipient database must be as large as, or larger than, the database to be loaded. If the recipient database is too small, SQL Server displays an error message that gives the required size. The device fragments that the new database uses for data and for the log must appear in the same order and have the same amount of space as the fragments in the original database. For example, if the original database had 10 MB of data (on any number of fragments), followed by 3 MB of log, followed by 6 more MB of space for data, the new database must have the same order by space and usage: that is, 10 MB for data, 3 for log, and 6 (or more) for data. The total size of the destination database must be at least as large and have at least as many fragments (assigned in the same order and have the same uses) as the load.

If the dumped database uses segments to store particular tables or indexes, the new database must include devices of the same size and page order for these segments and their related data in order for LOAD statement to work correctly. Execute the sp_helpdb system stored procedure with the database name to see the size and fragments. Select from the sysusages system table to determine the order of the device fragments. Then re-execute the CREATE DATABASE statement and the ALTER DATABASE statement to re-establish the fragments. For details on using the LOAD statement to restore or move databases, see the Microsoft SQL Server Administrator's Companion.

If a database will be loaded into a newly created database, use CREATE DATABASE FOR LOAD when creating the new database. The FOR LOAD option specifies that the data pages will not be zero-initialized because the only operations allowed against that database are ALTER DATABASE FOR LOAD or LOAD DATABASE. Any unused data pages will be initialized by the database load. For more information, see the CREATE DATABASE statement.

For compatibility, user database dumps from SQL Server 4.2x can be loaded into SQL Server 6.0, as long as the same sort order is running on both SQL Servers. The user database dump (the master database is not allowed to be loaded or upgraded from SQL Server 4.2x dumps) must be a full database dump, not a transaction log dump, and the dump must occur when there is no update activity taking place in the database. For this reason, it is recommended that the dump occur when SQL Server is started in single-user mode. After the database is successfully loaded, the database will be upgraded. For more information about database upgrades and potential compatibility issues, see Microsoft SQL Server Setup.

Important  Cross-platform dumping and loading is not supported. For example, a database dumped on a MIPS-based computer cannot be loaded into an Intel-based computer. If you need to move data from one platform to another, use the Microsoft SQL Transfer Manager.

Permission

LOAD DATABASE and LOAD TRANSACTION permission default to the database owner and are not transferable.


Loading the master database

Loading the master database because it has been damaged is performed using a special procedure. For details about restoring the master database, see the Microsoft SQL Server Administrator's Companion.


Loading from a Diskette Device

When you execute LOAD statement to restore from diskette, the console command-line utility must be used to prompt the user and then waits for responses. If console is not running or if the user does not answer its questions, the load cannot proceed.


Volume and Header Information

Using LOAD HEADERONLY, any client can retrieve all the volume and dump header information for all dumps on a particular dump device. The header information is sent as a row by the server for each dump on a given dump device in a table with following columns:

Option	Datatype	Possible information
Dumptype	smallint	Database(1) or Transaction(2)
Database	varchar(30)	Database name
Striped	smallint	Striped dump(1), non-striped dump(0)
Sequence	varchar(6)	Position of the dump in the volume
Volume	varchar(6)	Volume ID
Devicetype	smallint	Disk(2), Floppy(3), Tape(5) or Pipe(6)
Dumpsize	varchar(15)	Size of dump, in pages
Stripeset	varchar(2)	Number of devices in the stripeset
Stripesetname	varchar(30)	Stripeset ID, for future use
Curseq	char(13)	Current/old sequence number
Newseq	char(13)	New sequence number
CreationDate	char(15)	Creation date (Shortmonth DD, YY)
CreationTime	char(15)	Creation time (HH:MM)
ExpireDate	char(15)	Expiration date for the volume  (Shortmonth DD, YY)
Note  For any dump, only the appropriate columns will contain a value. All other columns will be NULL.


LOAD Examples
Examples

A.	Load from a Striped Dump

A database dump that has been made to more than one tape device can be restored from fewer devices than used for the original dump.

This first example shows a database load from only one tape drive, which is useful if the site performing the load doesn't have the same equipment as the dump site. The second example shows a load from three tape drives.

/* Loading from a predefined device. */

LOAD DATABASE corporate

FROM tape_dev1

Or

/* Loading from an ad hoc device. */

LOAD DATABASE corporate

FROM TAPE = '\\.\tape0'

To load the corporate database from all three tape devices:

LOAD DATABASE corporate

FROM tape_dev0, tape_dev1, tape_dev2

B.	Load a Specific File

The pubs database, which is the third file on the tape, is reloaded from the TAPEDUMP1 device.

LOAD DATABASE pubs

FROM tapedump1

WITH FILE = 3

See Also

CREATE Database	DUMP
DBCC	sp_helpdevice


Null Values

A null value, or NULL, is not the same as 0 or blank. NULL means no entry has been made and usually implies that the value is either unknown or undefined. NULL allows you to distinguish between a deliberate entry of 0 (for numerical columns) or a blank (for character columns) and an unknown or inapplicable entry (NULL for both numerical and character columns). NULL indicates that the user did not explicitly make an entry or has explicitly entered NULL. For example, a null value in the price column of the titles table of the pubs sample database does not mean that the book is being given away free, it means that the price is not known or has not been set.

Syntax

In CREATE TABLE statements:
column_name datatype [NULL | NOT NULL]

In SELECT statements:
WHERE column_name IS [NOT] NULL

In INSERT statements:
VALUES({constant | DEFAULT | NULL}
[, {constant | DEFAULT | NULL}]...)

In UPDATE statements:
SET column_name = {expression | NULL}
[, column_name = {expression | NULL}...]

The ISNULL built-in function:
ISNULL(expression, value)

where

NULL

Indicates no entry has been made. The value is unknown (not blank or 0). In CREATE TABLE statements, specifying NULL after a column name means that if there is no default for this column, SQL Server assigns a null value whenever the user does not enter data for this column.

A user can enter NULL explicitly in an INSERT or UPDATE statement.

In SELECT statements, use IS [NOT] NULL to retrieve null values.

NOT NULL

Can also be used in a WHERE clause in any statement to retrieve all values except those that are NULL.

Remarks

If the user fails to make an entry in a column that allows null values, SQL Server supplies the value NULL (unless a default exists). A column defined with the keyword NULL also accepts an explicit entry of NULL from the user, no matter what datatype it is or if it has a default associated with it. Be careful when you enter NULL in character columns. If you put the value NULL inside single quotation marks ('NULL'), SQL Server interprets the entry as a character string rather than as the null value.

If an attempt to insert NULL is made against a column defined as NOT NULL, only the statement (INSERT or UPDATE) will be terminated. Any other statements within the batch will continue. In earlier releases of SQL Server, the entire batch was rejected at compile time. Although not recommended, the previous behavior of SQL Server (stopping the processing of the entire batch and rolling back any transactions) can be turned on with trace flag 243. For details, see the Trace Flags topic.

Defining columns as NULL provides a place holder for data you might not yet know. For example, in the titles table, price, advance, royalty, and ytd_sales are set up to allow null values. However, title_id and title do not allow null values because the lack of an entry in these columns would make the row meaningless and confusing. A price without a title makes no sense, but a title without a price simply means that the price is not available. When you create a table, define columns as NOT NULL when the information in the column is critical to the meaning of the other columns. When inserting data, the DEFAULT keyword can be used (for columns defined as allowing null values without a default) to insert NULL into a column. For details and examples, see the INSERT statement.

DEFAULT constraints defined on the table or user-defined defaults can be connected with either NULL or NOT NULL columns. For more information, see the CREATE TABLE statement, the ALTER TABLE statement, and the CREATE DEFAULT statement.

When you create NULL columns with certain datatypes, SQL Server automatically converts them to a different internal datatype to allow the storage of null values. SQL Server does not inform the user of the datatype change, and the user should be concerned about it only if querying the system tables.

Datatype	Converted to datatype
binary	varbinary
char	varchar
datetime	datetimn
decimal	decimaln
float	floatn
int	intn
money	moneyn
numeric	numericn
real	floatn
smalldatetime	datetimn
smallint	intn
smallmoney	moneyn
tinyint	intn
A column definition that allows null values inserts NULL even when the rule does not explicitly specify NULL. For example, a rule defined on a column that allows null values and that states the values should be greater than 2 (@variable > 2) will insert NULL when no value is entered for the column.

An expression with an arithmetic or bitwise operator evaluates to NULL if any of the operands is null. For example, 1 + column1 evaluates to NULL if column1 is NULL.

An expression with a comparison operator evaluates to false if any of the operands is NULL. This means that null values never match another value (not even another NULL) when used with a comparison operator. Use IS NULL to find null values in queries (when the columns being searched are defined as allowing null values). Use the ISNULL system function to replace null values in an expression with another value (if desired). If you try to find null values in columns defined as NOT NULL, SQL Server generates an error message.

The result of an expression with a nested subquery that returns no rows is NULL. For more information on null values in a subquery, see the Subqueries topic. The default result of a divide-by-zero action is to return NULL, return a message, and continue processing the batch. To change how the session handles divide-by-zero, see the SET statement.

Aggregate functions ignore null values, except COUNT(*), which includes them. For example, in the calculation AVG(advance), null values in the advance column are not counted, either in calculating the total amount or the number of values.

The aggregate functions MIN, MAX, SUM, and AVG return NULL if the parameter specified for them is an empty set (that is, no rows satisfy the WHERE clause).

NULLs are considered to be duplicates only in the case of a GROUP BY clause, ORDER BY clause, or when using the DISTINCT keyword and come first in the ORDER BY clause.

Null values are never joined or referenced (in the case of a FOREIGN KEY constraint), not even to other null values.

The empty string (' ') or (" ") is always stored as a single space in variables and column data. 'abc' + ' ' + 'def' is equivalent to 'abc def', but not to 'abcdef'. The empty string is never evaluated as NULL.

If you have two tables identical in structure except that one has NULL fields and some null values, and the other has NOT NULL fields, this difference makes it impossible to use SELECT to insert the data from the table with columns that allow null values into the table with columns that do not allow null values. If any of the data is NULL, you cannot update a field that does not allow NULLs by selecting from a field that allows NULLs.

If you specify NOT NULL when you create a column and do not create a default for it, an error message occurs whenever a user fails to make an entry in that column. In addition, the user cannot insert or update such a column with NULL as a value. The following table illustrates the relationship between the existence of a default (created as a default constraint or as a default) and the definition of a column as NULL or NOT NULL:

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
The sp_help system stored procedure reports on a column's nullability (whether or not the column accepts null values).

A column of the text or image datatype, when inserted with a null value, does not initialize a text pointer or contain a value. When a null value is written in a text or image column with the UPDATE statement, the column is initialized, a valid text pointer to the column is inserted into the table, and a 2K data page is allocated to the column. Once the column is initialized, it can be accessed by the READTEXT statement and the WRITETEXT statement. For more information, see the Datatypes topic and the text and image Manipulation topic.

Examples

A.	NULL Values with INSERT

The table created in this example shows two columns. The first will allow null values and the second will not. Because column t1 of table test is defined as accepting NULL in the CREATE TABLE statement, the three INSERT statements that follow are equivalent. The user can explicitly insert NULL, use the DEFAULT keyword, or allow the system to insert NULL. NULL is inserted in the t1 column whenever the user inserts rows but does not specify a value for the column.

CREATE TABLE test

(

t1 char(10) NULL,

t2 char(10) NOT NULL

)

INSERT test VALUES(NULL, 'Stuff')

INSERT test VALUES(DEFAULT, 'Stuff')

INSERT test(t2) VALUES ('Stuff')

B.	NULL Values with SELECT

The SELECT statement retrieves all rows from test and displays null values in column t1 with the value unknown.

SELECT Col1 = ISNULL(t1, 'unknown'), Col2 = t2

FROM test

go

Col1       Col2
---------- ----------
unknown    Stuff
unknown    Stuff

(2 row(s) affected)

C.	NULL Values with UPDATE

This update uses NULL to define the value for the advance column in the titles table. Notice that quotation marks are not used when specifying NULL.

UPDATE titles

SET advance = NULL

WHERE title_id = 'TC3218'

D.	NULL Values in a WHERE Clause

SELECT title_id, advance

FROM titles

WHERE advance < $5000 OR advance IS NULL

go

title_id advance
-------- --------------------------
MC2222   0.00
MC3026   NULL
PC9999   NULL
PS2091   2,275.00
PS3333   2,000.00
PS7777   4,000.00
TC3218   NULL
TC4203   4,000.00

(8 row(s) affected)

See Also

Aggregate Functions	SELECT statement
CREATE PROCEDURE statement	sp_help
CREATE TABLE	Subqueries
Expressions	Text and Image Functions
INSERT	UPDATE
Search Conditions


Operators

Operators are symbols used to perform mathematical computations and/or comparisons between columns or variables. Comparisons can be made between like datatypes without any conversion, implicit conversion, or if necessary, explicit conversion. When comparisons are made between implicitly converted datatypes, the result will have the greater precision, the larger scale, and/or the larger/longer datatype. Operators can be combined and used in search conditions (within a WHERE clause or a HAVING clause). For more information, see the Search Conditions topic.

This section explains Arithmetic Operators, Bitwise Operators, Comparison Operators, Join Operators and concludes with an overview of Operator Precedence.


Arithmetic Operators

Arithmetic operators perform mathematical operations within Transact-SQL statements.

These are the arithmetic operators:

Symbol	Meaning	Can be used with
+	Addition	int, smallint, tinyint, numeric, decimal, float, real, money, and smallmoney
−	Subtraction	int, smallint, tinyint, numeric, decimal, float, real, money, and smallmoney
*	Multiplication	int, smallint, tinyint, numeric, decimal, float, real, money, and smallmoney
/	Division	int, smallint, tinyint, numeric, decimal, float, real, money, and smallmoney
%	Modulo*	int, smallint, and tinyint
* A modulo is the integer remainder after a division involving two integers. For example,  21 % 9 = 3 because 21 divided by 9 equals 2 with a remainder of 3.


Bitwise Operators

Bitwise operators perform mathematical operations between integer values as translated to binary expressions within Transact-SQL statements. All the bitwise operators translate the integer parameters into binary representation before evaluating them.

These are the bitwise operators:

Symbol	Meaning	Can be used on
&	Bitwise AND (two operands)	int, smallint, or tinyint columns only
|	Bitwise OR (two operands)	int, smallint, or tinyint columns only
^	Bitwise exclusive OR (two operands)	int, smallint, or tinyint columns only
~	Bitwise NOT (one operand)	int, smallint, tinyint, or bit columns only
The bitwise operators that require two operands (&, |, and ^) can be used on columns with these datatypes:

Left operand	Right operand
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
bit	int, smallint, tinyint, or bit
float (and real)	none
binary	int, smallint, or tinyint


Comparison Operators

Comparison operators contrast a specific difference between two expressions. Comparisons must only be made between variables, columns, and so on, of similar type.

These are the comparison operators:

Symbol	Meaning
=	Equal to
>	Greater than
<	Less than
>=	Greater than or equal to
<=	Less than or equal to
< >	Not equal to
In comparing char and varchar data, < means closer to the beginning of the alphabet and > means closer to the end of the alphabet. In the ASCII collating sequence, lowercase letters are greater than uppercase letters, and uppercase letters are greater than numbers. However, case and special-character evaluations depend on the sorting sequence chosen when SQL Server was installed. For details about sorting sequence, see the Microsoft SQL Server Setup.

In comparing dates, < means earlier and > means later. Place quotation marks around all character and datetime data used with a comparison operator.


Join Operators
Outer Join Operators

New join operators are available in SQL Server 6.5. Because future versions of SQL Server may discontinue support for the "*=" and "=*" outer join operators, it is recommended that you use the ANSI-standard join clauses (LEFT OUTER JOIN, RIGHT OUTER JOIN, and FULL OUTER JOIN) instead. For more information, see Joins and Select Statement.

Join operators compare two or more tables (or views) by specifying a column from each, comparing the values in those columns row by row, and concatenating rows in which the comparison is true. Comparisons must only be made between variables, columns, and so on, of similar type.

These are the join operators:

Symbol	Meaning
*=	Include in the results all rows from the first table that meet the statement's restrictions. The second table returns values if there is a match on the join condition. Otherwise, the second table generates null values.
=*	Include in the results all rows from the second table that meet the statement's restrictions. The first table returns values if there is a match on the join condition. Otherwise, the first table generates null values.
Remarks

Joins that preserve all rows from a table in the results set, regardless of whether there is a matching row in the table to which they're being joined (*= and =*), are called outer joins.

Since bit columns do not permit null values, a value of 0 appears in an outer join when there is no match for a bit column in the inner table. Joins cannot be used for columns containing text or image values.

Null values in tables or views being joined will never match each other.

Joins can also be stated as subqueries. For details, see the Subqueries topic.


String Operator

The string operator allows string concatenation with the + symbol. All other string manipulation is handled through String functions. For details, see the Functions topic.

By default, the empty string (' ') is interpreted as a single blank in INSERT or assignment statements on varchar data. In concatenating varchar, char, or text data, the empty string is interpreted as a single space. For example, 'abc' + ' ' + 'def' is stored as 'abc def'. The empty string is never evaluated as NULL.


Operator Precedence

When multiple operators are combined, operator precedence becomes an issue. Operator precedence determines which computations or comparisons are performed first. Often, the order can make a significant difference in the resulting value.

Operators have the following precedence levels:

•	Primary grouping: ( )

•	Bitwise: ~

•	Multiplicative: * / %

•	Additive: + −

•	Bitwise: ^

•	Bitwise: &

•	Bitwise: |

•	NOT

•	AND

•	OR

When all operators in an expression are of the same level, the precedence order is left to right. You can change the order of execution with parentheses (primary grouping); the most deeply nested expression is evaluated first.

Examples

A.	Arithmetic Operators

Arithmetic operators allow mathematical functions to perform computations on data within multiple columns of a table. If summary data is required, use aggregate or row aggregate functions. For more information, see the Functions topic. This example shows a single column computation (titled Copies) of the total year-to-date sales (ytd_sales) divided by the individual book price (price) from the titles table in pubs.

SELECT 'Copies' = CONVERT(int, ROUND(ytd_sales/price, 0))

FROM titles

B.	Bitwise Operators

All the bitwise operators translate integer parameters into binary representations before evaluating them. In the following examples, A = 10101010 and B = 01001011:

(A & B)	10101010

01001011

--------

00001010

The result is 1 when both A and B are 1.

(A | B)	10101010

01001011

--------

11101011

The result is 1 when A, B, or A and B are 1.

(A ^ B)	10101010

01001011

--------

11100001

The result is 1 when A or B, but not both, is 1.

(~A)	10101010

--------

01010101

All 1s are changed to 0s and all 0s to 1s.

C.	Comparison Operators

This example shows all information in the titles table where the price of a title is greater than $15.

SELECT *

FROM titles

WHERE price > $15

D.	Join Operators

This example compares a column from the inner table to a constant and then uses it in the outer join. It shows which titles have sold more than 30 copies from any store, as well as those that have not.

SELECT DISTINCT stor_id, title

FROM sales, titles

WHERE qty > 30

AND sales.title_id =* titles.title_id

See Also

Expressions	SELECT
Search Conditions	Wildcard Characters


PRINT Statement

Returns a user-defined message to the client's message handler.

Syntax

PRINT {'any ASCII text' | @local_variable | @@global_variable}

Remarks

The message can have as many as 255 characters.

The local variable must be of type char or varchar and must be declared within the batch or procedure in which it is used.

The global variable must be of type char or varchar or automatically convertible to those types, such as @@VERSION. Currently, @@VERSION is the only character-type global variable.

You can generate a "formatted" message with more than one parameter by using the concatenation operator.

To print a user-defined error message and have the error number stored in @@ERROR, use RAISERROR instead of PRINT.

Examples

A.	Conditionally Executed Print (IF EXISTS)

IF EXISTS (SELECT zip

FROM authors

WHERE zip = '94705')

PRINT 'Berkeley author'

B.	Build and Display a String

This example defines a local variable (@@returnmessage) and then builds the string (combining functions and strings) for display.

DECLARE @@returnmessage	varchar(255)

SELECT @@returnmessage = 'This record was updated on ' +

RTRIM(CONVERT(char(30), GETDATE())) + '.'

PRINT @@returnmessage

See Also

DECLARE	Variables
RAISERROR


RAISERROR Statement

For more information about how SQL Server 6.5 affects existing database systems and for updated SQL Server 6.5 syntax, see RAISERROR Statement.

Returns a user-defined error message and sets a system flag to record that an error has occurred. RAISERROR lets the client retrieve an entry from the sysmessages table or build a message dynamically with user-specified severity and state information. Once defined, this message is sent back to the client as a server error message.

The RAISERROR statement has been updated in SQL Server 6.0. The earlier syntax structure is supported for compatibility.

Syntax

RAISERROR ({msg_id | msg_str}, severity, state
[, argument1 [, argument2]] )
[WITH LOG]

where

msg_id

Is a user-defined error message stored in the sysmessages table. To add user-defined error messages, use sp_addmessage system stored procedure. To delete user-defined error messages, use sp_dropmessage system stored procedure. If a sysmessages error is used and the message was created using the format shown for msg_str, then supplied arguments (argument1, argument2, and so on) will be passed to the message of the supplied msg_id. Error numbers for user-defined error messages should be greater than 50,000. Ad hoc messages will raise an error of 50,000. The maximum value is 2,147,483,647 (2 (31)  − 1).

When an error is raised, the error number is placed in the global variable @@ERROR, which stores the error number most recently generated by the system.

msg_str

Is an ad hoc message with formatting similar to the C PRINTF format style. The error message can have as many as 255 characters. All ad hoc messages will have one standard message ID of 14000.

The following format is supported for msg_str:

% [[flag] [width] [precision] [{h | l}]] type

where

flag

Determines the spacing and justification.

Code	Prefix or Justification	Meaning
− (minus)	Left-justified	Left-justify the result within the given field width.
+ (plus)	+ (plus) or − (minus) prefix	Preface the output value with a sign (+ or −) 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. If 0 and − appear, 0 is ignored. If 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 will be ignored if included with the + flag.
width

Defines the minimum width. An asterisk (*) allows the following argument to determine the width.

precision

Specifies the maximum number of characters printed for the output field or the minimum number of digits printed for integer values. An asterisk (*) allows the argument to determine the precision.

{h | 1} type

Used with types d, i, o, x, X, or u, creates short int (h) or long int values (l).

Type	Represents
d or i	Signed integer
o	Unsigned octal
p	Pointer
s	String
u	Unsigned integer
x or X	Unsigned hexadecimal
Note that float, double-, and single-character types are not supported.

severity

Represents the user-defined severity level associated with this message. Severity levels from 0 through 18 can be used by any user. For severity levels 19 through 25, the WITH LOG option is required. Only the system administrator can issue RAISERROR with a severity level of 19 through 25. For a list of SQL Server error severity levels, see the Microsoft SQL Server Administrator's Companion

Caution  For a severity of 19 through 25, which are considered "fatal," the client connection will be terminated after receiving the message and the error will be logged in the error log and the event log.

state

Is an integer value from 1 through 127 that represents information about the invocation state of the error. A negative value for state will default to 1.

argument

Defines the parameters used in the substitution for variables defined in the msg_str or the message corresponding to the msg_id. There can be zero 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 datatypes: int1, int2, int4, char, varchar, binary, or varbinary. No other datatypes are supported.

WITH LOG

Logs the error in the server error log and the event log. This option is required for messages with a severity of 19 through 25, and it can be issued only by the system administrator. The xp_logevent extended stored procedure provides similar functionality.

Examples

A.	Ad Hoc Messages

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_lvl = 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.	Messages Raised from sysmessages

This example shows how the employee_insupd trigger could achieve the same results using parameters passed to a message stored in the sysmessages table. The message was added to the sysmessages table with the sp_addmessage system stored procedure as message number 50005.

RAISERROR (50005, 16, -1, @@job_id, @@min_lvl, @@max_lvl)

See Also

DECLARE	sp_dropmessage
PRINT	Variables
sp_addmessage	xp_logevent


RECONFIGURE Statement

Installs a changed configuration option used only with the sp_configure system stored procedure.

Syntax

RECONFIGURE [WITH OVERRIDE]

where

WITH OVERRIDE

Instructs SQL Server to accept the values for system variables supplied by the user (with the sp_configure stored procedure). If the user supplies values that SQL Server cannot accept, an error message telling the user to re-execute sp_configure is displayed.

The WITH OVERRIDE clause must always be used when the system administrator sets the allow updates option to 1.

Note  Never use the RECONFIGURE statement to change the default sort order of SQL Server.

See Also

sp_configure System Stored Procedure


REVOKE Statement

For more updated SQL Server 6.5 syntax, see REVOKE Statement.

Revokes object and statement permissions from users.

Syntax

Statement permissions:

REVOKE {ALL | statement_list}
FROM {PUBLIC | name_list}

Object permissions:

REVOKE {ALL | permission_list}
ON {table_name [(column_list)] | view_name [(column_list)] |
stored_procedure_name | extended_stored_procedure_name}
FROM {PUBLIC | name_list}

where

ALL

Specifies that all permissions applicable to the specified object are revoked when used to revoke object permissions. When used to revoke statement permissions specifies that all statement permissions are revoked. (CREATE DATABASE permission can be granted only by the system administrator.)

statement_list

Lists granted statements. The statement list can include CREATE DATABASE (which can be granted only by the system administrator), CREATE DEFAULT, CREATE PROCEDURE, CREATE RULE, CREATE TABLE, CREATE VIEW, DUMP DATABASE, and DUMP TRANSACTION. If more than one statement is listed, separate them with commas.

PUBLIC

Represents all users, including those who are members of other groups.

name_list

Lists usernames and/or group names, separated by commas.

permission_list

Lists granted permissions. When permissions are revoked on a table or a view, the permission list can include SELECT, INSERT, DELETE, UPDATE, and/or REFERENCES. When permissions are revoked on columns, the permission list can include SELECT and/or UPDATE. When permissions are revoked on stored procedures, the permission list can include only EXECUTE. If more than one permission is listed, separate them with commas.

table_name

Is the name of the table in the current database to which the permissions apply.

column_list

Lists names of columns, separated by commas, to which the permissions apply. If columns are specified, only SELECT and UPDATE permissions can be granted.

view_name

Is the name of the view in the current database to which the permissions apply.

stored_procedure_name

Is the name of the stored procedure in the current database to which the permissions apply.

extended_stored_procedure_name

Is the name of an extended stored procedure in the current database to which the permissions apply.

Remarks

When permissions are given, information is stored within the sysprotects database table. The sysprotects table manages permissions by updating rows based on each GRANT and REVOKE statement. You can grant or revoke permissions only on objects in the current database.

If permissions are granted to the group public, those permissions will override any previous permissions given to any other user or group of that database. When permissions are given (or revoked), the permissions are order-sensitive. (The statement executed most recently is the one that takes effect.) This can produce undesired results if care is not taken when granting/revoking permissions. For best results, grant/revoke permissions to the least-selective group first (usually public), and then grant/revoke permissions on a group-by-group basis, and then on an individual-by-individual basis, and then to/from the guest user.

The sp_helprotect system stored procedure reports permissions on a database object or on a user. For details, see the sp_helprotect system stored procedure.

Example

This example shows how to revoke multiple statement permissions from multiple users.

REVOKE CREATE TABLE, CREATE DEFAULT

FROM Mary, John

See Also

GRANT	sp_dropgroup
SETUSER	sp_dropuser
sp_addgroup	sp_helpgroup
sp_adduser	sp_helprotect
sp_changedbowner	sp_helpuser
sp_changegroup


Search Conditions

Set the conditions for data retrieval or modification. Search conditions immediately follow the keyword WHERE in a SELECT, INSERT, UPDATE, or DELETE statement or follow the keyword HAVING in a SELECT statement. If you use more than one of the search conditions in a single statement, connect the conditions with AND or OR. Joins and subqueries can be specified in the search conditions.

Syntax

{WHERE | HAVING} [NOT] Boolean_expression
{WHERE | HAVING} [NOT] Boolean_expression {AND | OR} 	Boolean_expression
{WHERE | HAVING} [NOT] column_name IS [NOT] NULL
{WHERE | HAVING} [NOT] column_name join_operator column_name
{WHERE | HAVING} [NOT] column_name [NOT] LIKE 'match_string'
{WHERE | HAVING} [NOT] EXISTS (subquery)
{WHERE | HAVING} [NOT] expression comparison_operator expression
{WHERE | HAVING} [NOT] expression [NOT] BETWEEN expression AND expression
{WHERE | HAVING} [NOT] expression [NOT] IN (value_list | subquery)
{WHERE | HAVING} [NOT] expression comparison_operator {ANY | ALL} (subquery)
{WHERE CURRENT OF cursor_name}

where

Boolean_expression

Is an expression that returns TRUE or FALSE. Boolean_expressions have the following format:

expression comparison_operator [ANY | ALL] (subquery)
expression [NOT] IN expression
[NOT] EXISTS expression
expression [NOT] BETWEEN expression AND expression
expression [NOT] LIKE expression
NOT expression LIKE expression
expression IS [NOT] NULL
Boolean_expression {AND | OR} Boolean_expression
[NOT] Boolean_function

where

Boolean_function

Is a function that returns TRUE or FALSE.

expression

Is a column name, a constant, a function, a variable, a subquery, any combination of column names, constants, and functions connected by an operator(s) or a subquery. The expression may also contain the CASE expression. For details, see the CASE Expression, Operators, and the Subqueries topics.

column_name

Is the name of a column used in the comparison. If there is any ambiguity, qualify the column name with its table or view name.

match_string

Is a string of characters and wildcard characters enclosed in quotation marks. For details, see the Wildcard Characters topic.

comparison_operator

Is a symbol used to contrast two expressions. For details, see the Operators topics.

value_list

Is a list of values. Place quotation marks around char, varchar, and datetime values, and separate values with commas.

subquery

Is a restricted SELECT statement (the ORDER BY clause, the COMPUTE clause, and the INTO keyword are not allowed). For more information, see the Subqueries topic.

cursor_name

Specifies the name of the cursor that points to the row where the statement should be applied. The WHERE CURRENT OF clause is available with the DELETE and UPDATE statements. For details, see the Cursors topic.

AND

Joins two conditions and returns results when both of the conditions 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.

ALL

Is used with <, >, <>, >=, or <= and a subquery. It evaluates to TRUE or FALSE when all values retrieved in the subquery match the value in the WHERE or HAVING clause or when the subquery returns no rows of the outer statement. For details, see the Subqueries topic.

ANY

Is used with <, >, <>, >=, <=, or = and a subquery. It evaluates to TRUE when any value retrieved in the subquery satisfies the comparison predicate in the WHERE or HAVING clause of the outer statement. For details, see the Subqueries topic.

BETWEEN

Is the range-start keyword. Use AND for the range-end value. A range of expression BETWEEN x AND y, unlike a range of expression > x and expression < y, is inclusive.

EXISTS

Is used with a subquery to test for the existence of rows returned by the subquery. For details, see the Subqueries topic.

IN

Allows you to select values that match any one of a list of values. The 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.

If there are 16 or more values in an IN predicate, the values are sorted and binary search is used to evaluate the predicate. This can result in limiting the overall number of comparisons performed. For information about using IN with a subquery, see the Subqueries topic.

IS [NOT] NULL

Are keywords that search for null values (or all values except null values). An expression with a bitwise or arithmetic operator evaluates to NULL if any of the operands is NULL.

LIKE

Indicates that the following character string (enclosed by quotation marks) is to be used with pattern matching. You can use the LIKE keyword and wildcard characters with datetime data as well as with char and varchar. When you use LIKE with datetime values, SQL Server converts the dates to the standard datetime format and then to varchar. Since the standard storage format doesn't include seconds or milliseconds, you cannot search for seconds or milliseconds with LIKE and a pattern.

It is a good idea to use LIKE when you search for datetime values, since datetime entries can contain a variety of date parts. For example, if you insert the value 9:20 into a column named arrival_time, the clause WHERE arrival_time = '9:20' can't find it because SQL Server converts the entry into 'Jan 1, 1900 9:20AM'. However, the clause WHERE arrival_time LIKE '%9:20%' does find it.

Note  When performing string comparisons with LIKE, all characters in the pattern string are significant, including every leading and/or trailing blank (space). If a comparison to return all rows with a string LIKE 'abc' (abc followed by a single space) is requested, a row where the value of that column is 'abc' (abc without a space) will not be returned. The reverse, however, is not true. Trailing blanks in the expression to which the pattern is matched are ignored. If a comparison to return all rows with a string LIKE 'abc' (abc without a space) is requested, all rows with zero or more blanks would be returned.

NOT

Negates any Boolean expression (which can include keywords, such as LIKE, NULL, BETWEEN, IN, and EXISTS).

OR

Joins two conditions and evaluates to TRUE when either of the conditions is true. When more than one logical operator is used in a statement, OR operators are normally evaluated after AND operators. However, you can change the order of evaluation by using parentheses.

Examples

A.	Arithmetic Operators

In this example, the WHERE clause affects only those titles that have year-to-date sales more than twice the advance given:

WHERE advance * 2 > ytd_sales

B.	Wildcard with the NOT LIKE Condition

In this example, only phone numbers that do not begin with the 415 prefix are affected in the results set:

WHERE phone NOT LIKE '415%'

C.	Specific Character Wildcards with the LIKE Condition

This example finds the rows for authors named Carson, Carsen, Karsen, and Karson:

WHERE au_lname LIKE '[CK]ars[eo]n'

D.	Boolean (OR) and Comparison Operators (< and IS NULL)

This example finds titles that have an advance less than $5000 and includes those titles that have no specific advance entered (NULL values):

WHERE advance < $5000 OR advance IS NULL

E.	Grouping Boolean Expressions

Using parentheses always takes precedence over other operators. Without the parentheses, the following WHERE clause would have totally different meaning because AND takes a higher precedence than OR.

This example affects only books with an advance greater than $5500 and are either business or psychology books. If the parentheses were not included, the WHERE clause would affect all business books OR psychology books that have an advance greater than $5500.

WHERE (type = 'business' OR type = 'psychology') AND

advance > $5500

F.	Between Condition

This example returns all titles with year-to-date sales between and including 4095 through 12000.

WHERE ytd_sales BETWEEN 4095 AND 12000

G.	IN Condition

This example finds the rows in which the state is California (CA), Indiana (IN), or Maryland (MD).

WHERE state IN ('CA', 'IN', 'MD')

See Also

DELETE	Operators
EXECUTE	SELECT
Expressions	UPDATE
Functions	Wildcard Characters
INSERT


SELECT Statement

For updated SQL Server 6.5 syntax including the CUBE and ROLLUP operators, see SELECT Statement, CUBE Operator, and ROLLUP Operator.

Retrieves rows from the database.

Syntax

SELECT [ALL | DISTINCT] select_list
[INTO [new_table_name]]
[FROM {table_name | view_name}[(optimizer_hints)]
[[, {table_name2 | view_name2}[(optimizer_hints)]
[..., {table_name16 | view_name16}[(optimizer_hints)]]]
[WHERE clause]
[GROUP BY clause]
[HAVING clause]
[ORDER BY clause]
[COMPUTE clause]
[FOR BROWSE]

where

ALL

Retrieves all rows in the results. ALL is the default.

DISTINCT

Includes only unique rows in the results. Null values are considered equal for the purposes of the DISTINCT keyword; only one NULL is selected no matter how many are encountered.

select_list

Specifies the columns to select. Can be one or more of the following:

•	Asterisk (*), representing all columns listed in the order in which they were specified in the CREATE TABLE statement for all tables in the FROM clause, in the order they appear.

•	A list of column names, specified in the order in which you want to see them. If the select_list contains multiple column names, separate the names with commas.

•	A column name and column heading that will replace the default column heading (the column name), in the following form:

column_heading = column_name

or

column_name column_heading

The column_heading must be in quotation marks if spaces are used. For example:

SELECT 'Author Last Name' = au_lname

FROM authors

•	An expression (a column name, constant, function, or any combination of column names, constants, and functions connected by an operator(s), or a subquery). For details, see the Expressions topic.

•	The IDENTITYCOL keyword instead of the name of a column that has the IDENTITY property. For details, see the CREATE TABLE statement.

•	A local or global variable. For details, see the Variables topic.

•	A local variable assignment, in the form:

@variable = expression

Note  When the select_list includes a variable assignment(s), it cannot be combined with data-retrieval operations.

INTO new_table_name

Creates a new table based on the columns specified in the select_list and the rows chosen in the WHERE clause. To select into a permanent table, the select into/bulkcopy option must be on (by executing the sp_dboption system stored procedure). By default, the select into/bulkcopy option is off in newly created databases. The new table name (new_table_name) must follow the same rules as table_name (described later in this section) with these exceptions:

•	If select into/bulkcopy is on in the database where the table is to be created, a permanent table is created. The table name must be unique in the database and conform to the rules for Identifiers.

•	If select into/bulkcopy is not on in the database where 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 pound sign (#). For details on temporary tables, see the CREATE TABLE statement.

SELECT INTO is a two-step operation. The first step creates the table. The user executing the statement must have CREATE TABLE permission in the destination database. The second step inserts the specified rows into the new table. If the second step fails for any reason (hardware failure, exceeding a system resource, and so on), the new table will exist but have no rows.

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.

You cannot use SELECT INTO with the COMPUTE clause or inside a user-defined transaction. For details about user-defined transactions, see the Transactions topic.

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. If none of the conditions is true, the new table will inherit the identity column. All rules, restrictions, and so on, for the identity columns apply to the new table.

FROM

Indicates the specific table(s) and view(s) that are used in the SELECT statement. FROM is required except when the select_list contains only constants, variables, and arithmetic expressions (no column names). The FROM clause allows a maximum of 16 tables and views. Tables in subqueries are counted as part of this total.

table_name | view_name =

[[database.]owner.]{table_name. | view_name.}

Specifies the name(s) of the table(s) and view(s) used in the SELECT statement. If the list contains more than one table or view, separate the names with commas. If the table(s) or view(s) exist in another database(s), use a fully qualified table or view name (database_name.owner.object_name).

Each table_name or view_name can be given an alias, either for convenience or to distinguish the different roles that a table or view plays in a self-join or subquery. Aliases (when defined) must be used for any ambiguous column references and must always match the alias reference (the full table name cannot be used if an alias has been defined). To use an alias, specify the object name, and then a space, and then the alias name, like this:

SELECT au_lname, au_fname, title

FROM titles t, authors a, titleauthor ta

WHERE ta.title_id = t.title_id

AND ta.au_id = a.au_id

ORDER BY title, au_lname, au_fname

The order of the tables and views after the FROM keyword does not affect the results set returned.

(optimizer_hints)

Indicate that a specific locking method, a specific index, or no index (table scan) should be used (by the optimizer) with this table for this SELECT. Although this is an allowable option, in most cases you should allow the optimizer to pick the best optimization method.

Important  You can use the optimizer_hints in any combination, but some of them do not make sense to use together—for example, TABLOCK and PAGLOCK. When multiple options are specified, separate them with a space; the more restrictive option will take precedence.

An optimizer_hint can be one (or more) of the following:

INDEX = {index_name | index_id}

Specifies the index name or ID to use for that table. An index_id of 0 forces a table scan, 1 forces the use of a clustered index (if one exists).

NOLOCK

Allows "dirty reads," which means that no shared locks are issued and no exclusive locks are honored. This can result in higher concurrency, but at the cost of lower consistency. If this option is specified, it is possible to read an uncommitted transaction or to read a set of pages that are rolled back in the middle of the read, so error messages might result. If you receive error messages 605, 606, 624, or 625 when NOLOCK is specified, resolve them as you would a deadlock error (1205) and retry your statement.

HOLDLOCK

Makes a shared lock more restrictive by holding it 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 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. You cannot use HOLDLOCK in a SELECT statement that includes the FOR BROWSE option.

UPDLOCK

Takes update locks instead of shared locks while reading the table and holds them until the end-of-command or end-of-transaction.

TABLOCK

Takes a shared lock on the table that is held until the end-of-command. If HOLDLOCK is also specified, the shared lock is held until the end of the transaction.

PAGLOCK

Takes shared page locks where a single shared table lock would normally be taken.

TABLOCKX

Takes an exclusive lock on the table that is held until the end-of-command or end-of-transaction.

FASTFIRSTROW

Causes the optimizer to use the nonclustered index if one matches the ORDER BY clause. With sorting enhanced by the new asynchronous read ahead capability, the optimizer picks table scan and sort over using a nonclustered index in many cases because the total throughput for the sort is faster. If there is a sort, the first row cannot be sent until totally sorted. With this method, if the sort is large, there may be a considerable delay before the first row appears. FASTFIRSTROW causes the optimizer to use the nonclustered index; the first row will appear quickly, but the total return time for this option may be slower.

WHERE clause =

WHERE search_conditions

Specifies the restricting conditions for the rows returned in the results set. There is no limit to the number of search_conditions that can be included in an SQL statement. For more information, see the Search Conditions topic.

GROUP BY clause =

GROUP BY [ALL] aggregate_free_expression
[, aggregate_free_expression]...

GROUP BY

Specifies the groups into which the table will be partitioned and, if aggregate functions are included in the select_list, finds a summary value for each group. You can refer to these new summary columns in the HAVING clause. The text and image datatypes cannot be used in a GROUP BY clause.

When a GROUP BY clause is used, each item in the select_list must produce a single value for each group. A table can be grouped by any combination of columns; however, you cannot group by a column heading—you must use a column name or an expression. In Transact-SQL, any expression is valid (although not with column headings). With standard SQL, you can group only by a column.

You can use GROUP BY for a column or expression that does not appear in the select_list. Null values in the GROUP BY column are put into a single group.

The aggregate functions, which calculate summary values from the non-null values in a column, can be divided into two groups:

Scalar	Aggregate functions are applied to all the rows in a table (producing a single value per function). An aggregate function in the select_list with no GROUP BY clause applies to the whole table and is one example of a scalar.
Vector	Aggregate functions are applied to all rows that have the same value in a specified column or expression with the GROUP BY clause and, optionally, the HAVING clause (producing a value for each group per function).
For the details about aggregate functions, see the Functions topic.

ALL

Includes all groups in the results, even those that don't have any rows that meet the search_conditions.

aggregate_free_expression

Is an expression that includes no aggregate functions. Aggregate functions can be used in the select_list preceding the GROUP BY clause.

For the details about aggregate functions, see the Functions topic.

HAVING clause =

HAVING search_conditions

Specifies a different type of restriction for aggregate functions in the select_list; the search_conditions restrict the rows returned by the query but do not affect the calculation(s) of the aggregate function(s). When a WHERE clause is used, the search_conditions restrict the rows that are included in the calculation of the aggregate function but do not restrict the rows returned by the query. The text and image datatypes cannot be used in a HAVING clause.

There is no limit on the number of conditions that can be included in search_conditions. You can use a HAVING clause without a GROUP BY clause. When the HAVING clause is used with GROUP BY ALL, the HAVING clause negates the meaning of ALL.

ORDER BY clause =

ORDER BY {{table_name. | view_name.}column_name
| select_list_number | expression} [ASC | DESC]
 [...{{table_name16. | view_name16.}column_name
| select_list_number | expression} [ASC | DESC]]

Sorts the results by columns. You can sort as many as 16 columns. In Transact-SQL, the ORDER BY clause can include items that do not appear in the select_list. You can sort by a column name, a column heading (or alias), an expression, or a number representing the position of the item in the select_list (the select_list_number). If you sort by select_list_number, the columns to which the ORDER BY clause refers must be included in the select_list. The select_list can be a single asterisk (*). If you use COMPUTE BY, you must also specify an ORDER BY clause.

Null values are sorted before all others, and text or image columns cannot be used in an ORDER BY clause. Subqueries and view definitions cannot include an ORDER BY clause, a COMPUTE clause, or the INTO keyword. However, through Transact-SQL extensions, you can sort by expressions and aggregates if you use their select_list_number in the ORDER BY clause.

COMPUTE clause =

COMPUTE row_aggregate(column_name)
[, row_aggregate(column_name)...]
[BY column_name [, column_name]...]

COMPUTE

Used with row aggregate functions (SUM, AVG, MIN, MAX, and COUNT) to generate control-break summary values. The summary values appear as additional rows in the query results, allowing you to see detail rows and summary rows within one results set. You can calculate summary values for subgroups, and you can calculate more than one aggregate function for the same group.

The COMPUTE clause cannot be used with INTO and cannot contain aliases for column names, although aliases can be used in the select_list.

The COMPUTE keyword can be used without BY to generate grand totals, grand counts, and so on. The ORDER BY clause is optional only if you use the COMPUTE keyword without BY.

BY

Indicates that values for row aggregate functions are to be calculated for subgroups. Whenever the value of BY changes, row aggregate function values are generated. If you use BY, you must also use an ORDER BY clause. Listing more than one item after BY breaks a group into subgroups and applies a function at each level of grouping. The columns listed after COMPUTE clause must be identical to or a subset of those listed after ORDER BY clause, and must be in the same left-to-right order, start with the same expression, and not skip any expression.

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

FOR BROWSE

Allows you to perform updates while viewing data in client application programs using DB-Library.

A table can be browsed in an application under the following conditions:

•	The table includes a time-stamped column (defined with the timestamp datatype).

•	The table has a unique index.

•	The FOR BROWSE option is at the end of the SELECT statement(s) sent to SQL Server.

For details, see Microsoft SQL Server Programming DB-Library for C.

Do not use the optimizer_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.

Remarks

The length returned for text columns included in the select_list defaults to whichever is the smallest — the actual size of the text, the default TEXTSIZE session setting, or the hardcoded 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 4K.

To retrieve data from remote SQL Servers, you can call remote stored procedures. For more information, see the CREATE PROCEDURE and EXECUTE statements.

Using the GROUP BY clause and the HAVING clause

The following list shows the requirements for processing a SELECT with the GROUP BY clause and the HAVING clause, and it shows how the rows returned in the results set are derived:

1.	The WHERE clause excludes rows that do not meet its search_conditions.

2.	The GROUP BY clause collects the surviving rows into one group for each unique value in the GROUP BY clause. Omitting the GROUP BY clause creates a single group for the whole table.

3.	The HAVING clause excludes rows that do not meet its search_conditions. The HAVING clause tests only rows, but the presence or absence of a GROUP BY clause can make the behavior of a HAVING clause appear contradictory. For example:

•	When the query includes a GROUP BY clause, the HAVING clause excludes groups from the results.

•	By default, the HAVING clause can refer to aggregates only when the query contains no GROUP BY clause.

•	To allow queries that contain aggregates or a GROUP BY clause with items in the select_list that are not in the GROUP BY clause and are not aggregate functions, set trace flag 204. For details, see the Trace Flags topic.

4.	Aggregate functions specified in the select_list calculate summary values for each surviving group.

For the GROUP BY clause, the HAVING clause, and aggregate functions to accomplish the goal of one row and one summary value per group, ANSI-standard SQL requires:

•	Columns in a select_list must also be in the GROUP BY clause or be parameters of aggregate functions.

•	Columns in a HAVING clause must have only one value.

•	A query with a HAVING clause should have a GROUP BY clause. But if it doesn't, all the rows not excluded by the WHERE clause are considered to be a single group.

Transact-SQL extensions to standard SQL make displaying data more flexible by allowing references to columns and expressions that are not used for creating groups or summary calculations. For example:

•	The GROUP BY clause can include expressions.

•	GROUP BY ALL displays all groups, even those excluded from calculations by a WHERE clause.

Permission

SELECT permission defaults to the owner of the table or view, who can grant it to other users using the GRANT statement. If the INTO clause is used to create a permanent table, then the user must have CREATE TABLE permission in the destination database.

Examples

A.	Simple SELECT: All Rows, All Columns

This example returns all rows (no WHERE clause) and all columns (*) from the publishers table in the pubs database.

SELECT * FROM publishers

B.	Simple SELECT: Subset of Columns, All Rows

This example returns all rows (no WHERE clause) and only a subset of the columns (pub_id, pub_name, city, state) from the publishers table in the pubs database.

SELECT pub_id, pub_name, city, state

FROM publishers

C.	Simple SELECT: Subset of Rows, Subset of Columns

This examples returns only the rows where the advance given is less than $10,000 and there are current year-to-date sales.

SELECT pub_id, total = sum (ytd_sales)

FROM titles

WHERE advance < $10000

AND ytd_sales IS NOT NULL

D.	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. Notice that all computed columns appear within the select_list.

SELECT title = CONVERT(char(20), 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)

go

title	type	price	advance
------------------------ -------------------- --------- ----------
Fifty Years in Bucki	trad_cook	11.95	4,000.00
Onions, Leeks, and G	trad_cook	20.95	7,000
Sushi, Anyone?	trad_cook	14.99	8,000.00

avg
=========
15.96
sum
=========
19,000.00

title	type	price	advance
------------------------ -------------------- --------- ----------
Computer Phobic AND	psychology	21.59	7,000.00
Emotional Security:	psychology	7.99	4,000.00
Is Anger the Enemy?	psychology	10.95	2,275.00
Life Without Fear	psychology	7.00	6,000.00
Prolonged Data Depri	psychology	19.99	2,000.00

avg
=========
13.50
sum
=========
21,275.00

title	type	price	advance
------------------------ -------------------- --------- ----------
But Is It User Frien	popular_comp	22.95	7,000.00
Secrets of Silicon V	popular_comp	20.00	8,000.00

avg
=========
21.48
sum
=========
15,000.00

title	type	price	advance
------------------------ -------------------- --------- ----------
Silicon Valley Gastr	mod_cook	19.99	0.00
The Gourmet Microwav	mod_cook	2.99	15,000.00

avg
=========
11.49
sum
=========
15,000.00

title	type	price	advance
------------------------ -------------------- --------- ----------
Cooking with Compute	business	11.95	5,000.00
Straight Talk About	business	19.99	5,000.00
The Busy Executive's	business	19.99	5,000.00
You Can Combat Compu	business	2.99	10,125.00

avg
=========
13.73
sum
=========
25,125.00

sum
=========
236.26
sum
=========
88,400.00
(22 row(s) affected)

E.	All Rows with Computed Sums

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.

SELECT type, price, advance

FROM titles

COMPUTE SUM(price), SUM(advance)

go

type         price                      advance
------------ -------------------------- --------------------------
business     19.99                      5,000.00
business     11.95                      5,000.00
business     2.99                       10,125.00
business     19.99                      5,000.00
mod_cook     19.99                      0.00
mod_cook     2.99                       15,000.00
UNDECIDED    (null)                     (null)
popular_comp 22.95                      7,000.00
popular_comp 20.00                      8,000.00
popular_comp (null)                     (null)
psychology   21.59                      7,000.00
psychology   10.95                      2,275.00
psychology   7.00                       6,000.00
psychology   19.99                      2,000.00
psychology   7.99                       4,000.00
trad_cook    20.95                      7,000.00
trad_cook    11.95                      4,000.00
trad_cook    14.99                      8,000.00

             sum
             ==========================
             236.26
                                        sum
                                        ==========================
                                        95,400.00

(19 row(s) affected)

F.	Create a Temporary Table with SELECT INTO

This example causes a temporary table to be created in tempdb. To use this table, always refer to it with the exact name shown, including the pound sign (#).

SELECT *

INTO #coffeetabletitles

FROM titles

WHERE price < $20

go

SELECT name FROM sysobjects WHERE name LIKE '#c%'

go

name
------------------------------

(0 row(s) affected)

SELECT name FROM tempdb..sysobjects WHERE name LIKE '#c%'

go

name
------------------------------
#coffeetabletitles__0000EC153E

(1 row(s) affected)

G.	Create a Permanent Table with SELECT INTO

This example shows the steps needed to create a permanent table.

USE master

go

sp_dboption 'pubs', 'select into', TRUE

go

CHECKPOINTing database that was changed.

USE pubs

go

SELECT *

INTO newtitles

FROM titles

WHERE price > $25

OR price < $20

go

(12 row(s) affected)

SELECT name FROM sysobjects WHERE name LIKE 'new%'

go

name
------------------------------
newtitles

(1 row(s) affected)

H.	Optimizer Hints: TABLOCK and HOLDLOCK

The following partial transaction shows how to place an explicit shared table lock on t1 without the overhead of reading any records from it.

BEGIN TRAN

SELECT count(*) FROM t1 (TABLOCK HOLDLOCK)

I.	Optimizer Hints: Using the Name of an Index

This example shows how to force the optimizer to use a nonclustered index to retrieve rows from a table.

SELECT au_lname, au_fname, phone

FROM authors (INDEX = aunmind)

WHERE au_1name = 'Smith'

J.	Optimizer Hints: Forcing a Table Scan

This example shows that using an index of 0 will force a table scan.

SELECT emp_id, fname, lname, hire_date
FROM employee (index = 0)
WHERE hire_date > '10/1/1994'

See Also

CREATE TABLE statement	Search Conditions
CREATE TRIGGER statement	sp_dboption
CREATE VIEW statement	Subqueries
DELETE statement	UNION operator
Expressions	UPDATE statement
Functions	Variables
INSERT statement	Wildcard Characters


SET Statement

For more information about how SQL Server 6.5 affects existing database systems and for updated SQL Server 6.5 syntax, see SET Statement.

Sets SQL Server query-processing options for the duration of the user's work session, or for the duration of a running trigger or a stored procedure.

Syntax

SET {
{{{ANSI_NULL_DFLT_OFF | ANSI_NULL_DFLT_ON}
| ARITHABORT
| ARITHIGNORE
| FMTONLY
| FORCEPLAN
| IDENTITY_INSERT [database.[owner.]]tablename
| NOCOUNT
| NOEXEC
| OFFSETS {keyword_list}
| PARSEONLY
| PROCID
| QUOTED_IDENTIFIER
| SHOWPLAN
| STATISTICS IO
| STATISTICS TIME}
{ON | OFF}}
| DATEFIRST number
| DATEFORMAT format
| DEADLOCKPRIORITY {LOW | NORMAL}
| LANGUAGE language
| ROWCOUNT number
| TEXTSIZE number
| TRANSACTION ISOLATION LEVEL {READ COMMITTED | READ
UNCOMMITTED | REPEATABLE READ | SERIALIZABLE}}

where

ANSI_NULL_DFLT_OFF

Alters the session's behavior not to use ANSI compatibility for nullability. When this session option is turned on, it overrides the default database nullability configured by the sp_dboption system stored procedure. New columns defined without explicit nullability will be defined not to allow NULLs (as long as the underlying datatype is nullable). For more information on datatypes, see the Datatypes topic.

ANSI_NULL_DFLT_ON

Alters the sessions behavior to ANSI compatibility for nullability. When this session option is turned on, it overrides the default database nullability configured by the sp_dboption system stored procedure. New columns defined without explicit nullability will be defined to allow NULLs.

Note  ANSI_NULL_DFLT_ON and ANSI_NULL_DFLT_OFF are mutually exclusive options, yet both options exist to determine whether or not the database option should be overridden. When turned ON, each option forces the opposite option to OFF. Neither option, when set OFF, turns the opposite option ON. Instead, turning an option OFF only discontinues the current ON setting.

ARITHABORT

Terminates a query when an overflow or divide-by-zero error occurs during query execution. It is possible for rows in a results set to be returned prior to the overflow or divide-by-zero occurrence.

ARITHIGNORE

Returns NULL when an overflow or divide-by-zero error occurs during a query. No warning message is returned.

Note  If neither ARITHABORT nor ARITHIGNORE is set, SQL Server returns NULL and returns a warning message after the query is executed.

FMTONLY

Returns only metadata to the client. No rows will be processed or sent to the client as a result of the request when FMTONLY is turned ON.

FORCEPLAN

Makes the SQL Server optimizer process joins in the same order as tables appear in the FROM clause. FORCEPLAN essentially overrides the optimizer.

IDENTITY_INSERT [database.[owner.]]tablename

Specifies the database, owner and table in which explicit identity values can be inserted. Only one table per user can have the IDENTITY_INSERT option set. If the value inserted is larger than the current identity value for the table, SQL Server will automatically use the new inserted value as the current identity value. For details, see the IDENTITY property.

NOCOUNT

Turns off the message returned at the end of each statement that states how many rows were affected by the statement. The global variable @@ROWCOUNT is updated even when NOCOUNT is turned ON.

In SQL Server, SET NOCOUNT ON eliminates the sending of DONE_IN_PROC messages to the client for each statement in a stored procedure. 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.

NOEXEC

Compiles each query but does not execute it. NOEXEC is often used with SHOWPLAN. Once NOEXEC is turned on, no subsequent statements are executed (including other SET statements) until NOEXEC is turned OFF.

Statement processing consists of two phases, compilation and execution. NOEXEC stops the processing after compilation.

OFFSETS

Returns the keyword_list offset (position in relation to the beginning of the query) of specified keywords in SQL statements. The keyword_list is a list, separated with commas, that can include any of these SQL constructs: SELECT, FROM, ORDER, COMPUTE, TABLE, PROCEDURE, STATEMENT, PARAM, and EXECUTE.

The OFFSETS option is used only in a DB-Library application.

PARSEONLY

Checks the syntax of each query and returns any error messages without generating a sequence tree, compiling, or executing the query. Do not use PARSEONLY in a stored procedure or a trigger. PARSEONLY returns offsets if the OFFSETS option is ON and no errors occur.

PROCID

Returns the identification number of the stored procedure to DB-Library (not to the user) before sending rows generated by that stored procedure.

QUOTED_IDENTIFIER

Causes the current session to differentiate between single and double quotation marks when evaluating an expression. When QUOTED_IDENTIFIER is turned ON, strings with double quotation marks (") will not be evaluated or checked against keywords. For details, see the Identifiers topic.

SHOWPLAN

Generates a description of the processing plan for the query and immediately processes it unless NOEXEC is set. This option can indicate whether an index is being used to retrieve query results.

STATISTICS IO

Displays the number of scans, the number of logical reads (pages accessed in cache), and the number of physical reads (number of times the disk was accessed) for each table referenced in the statement.

STATISTICS TIME

Displays the time, in milliseconds, required to parse and compile each command and the time required to execute each step of the command.

DATEFIRST number

Sets the first weekday to a number from 1 through 7. The U.S. English default is 7 (Sunday).

DATEFORMAT format

Sets the order of the date parts (month/day/year) for entering datetime or smalldatetime data. Valid parameters include mdy, dmy, ymd, ydm, myd, and dym. The U.S. English default is mdy.

DEADLOCKPRIORITY {LOW | NORMAL}

Controls how this session reacts when in a deadlock situation. If set to LOW, this process will be the preferred victim of a deadlock situation. Use the NORMAL option to return the session to the default deadlock-handling method.

LANGUAGE language

Specifies the language in which system messages are displayed. The language must be available on the server. The default is us_english.

ROWCOUNT number

Causes SQL Server to stop processing the query after the specified number of rows are returned. To turn this option off (so that all rows are returned), use SET ROWCOUNT 0.

Note  Setting the ROWCOUNT option causes all Transact-SQL statements to stop processing when they have each affected number rows. This includes triggers and data modification statements such as INSERT, UPDATE, and DELETE as well as the filling of a keyset cursor at the specified number of rows. This option should be used with caution and primarily with the SELECT statement.

TEXTSIZE number

Specifies the size, in bytes, of text data to be returned with a SELECT statement. If you specify a TEXTSIZE of 0, the size is reset to the default (4K). Setting TEXTSIZE affects the global variable @@TEXTSIZE.

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 Microsoft SQL Server Programming DB-Library for C.

TRANSACTION ISOLATION LEVEL

Controls the default transaction locking behavior for all SQL Server SELECT statements for this connection. Only one of the options can be set at a time, and it remains set for that connection unless it is explicitly changed. This becomes the default behavior unless an optimization option is specified at the table level in the FROM clause of your statement. For details, see the SELECT statement. To see what isolation level is currently set, use DBCC USEROPTIONS. For more information on DBCC, see the DBCC statement.

where

READ COMMITTED

Is the default mode for SQL Server. Setting this option returns transaction locking behavior to the SQL Server default, and you will not encounter "dirty reads." However, because shared locks do not exclusively hold records until the completion of a transaction, you might still encounter non-repeatable reads and phantom values later within your transaction.

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 data, have values change if reread in the same transaction, and have phantom values.

REPEATABLE READ | SERIALIZABLE

Are currently implemented identically. In some database systems, REPEATABLE READ means that "dirty reads" and non-repeatable reads are not possible but phantoms are possible. However, because REPEATABLE READ is a synonym for SERIALIZABLE in SQL Server's implementation, phantoms are not allowed when one of these is set. Because concurrency is lower, use these options only when necessary.

These options have the same effect as setting HOLDLOCK on all tables in all SELECT commands within a transaction.

Remarks

If you use the SET statement inside a trigger or a stored procedure, the option reverts to its former setting after the trigger or stored procedure is executed.

Options changed with the SET statement take effect at the end of the batch. You can combine SET statements and queries in the same batch, but the SET options won't apply to the queries in that batch.

Examples

A.	SHOWPLAN

This example shows that setting the SHOWPLAN returns a description of the processing plan for each query prior to returning the results set. Notice that the SET option must be turned on prior to the execution of the SELECT statement.

SET SHOWPLAN ON

go

select * from publishers

go

STEP 1
The type of query is SELECT
FROM TABLE
publishers
Nested iteration
Table Scan

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

(8 row(s) affected)

B.	SHOWPLAN and NOEXEC

This example shows how the query plan can be viewed without returning the results.

SET SHOWPLAN ON

SET NOEXEC ON

go

SELECT * FROM publishers

go

STEP 1
The type of query is SELECT
FROM TABLE
publishers
Nested iteration
Table Scan

C.	ROWCOUNT

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.

SELECT Count = count(*)

FROM titles

WHERE advance >= 5000

go

Count
-----------
10

(1 row(s) affected)

SET ROWCOUNT 4

go

UPDATE titles

SET advance = 5000

WHERE advance >= 5000

go

(4 row(s) affected)

D.	ANSI NULL Default, Create Tables and sp_help

The publishers table is created without explicitly defining the nullability for each of the columns. In the INSTPUBS.SQL script, all nullability is explicitly defined. But for this example, all NULL definitions were replaced by a single SET option defined prior to the CREATE TABLE batch. Also note that the SET option is explicitly turned off within the script.

In scripts run against databases where nullability may be changed, make sure to do one of the following:

•	Explicitly define the nullability for each column.

•	Manually set the nullability for the script's session using one of the ANSI NULL default options.

SET ANSI_NULL_DFLT_ON ON

go

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

city	varchar(20),

state	char(2),

country	varchar(30)	DEFAULT('USA')

)

go

sp_help publishers

go

/* For simplicity only a subset of the results of sp_help is

shown here. */

Column_name	Nullable
------------- --------------
pub_id	no
pub_name	yes
city	yes
state	yes
country	yes

SET ANSI_NULL_DFLT_ON OFF

E.	TRANSACTION ISOLATION LEVEL in an Explicit Transaction

In this example, the TRANSACTION ISOLATION LEVEL is set for the session. For each Transact-SQL statement that follows, SQL Server will hold 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

F.	Arithmetic Handling

In this example, all arithmetic SET options and the results displayed by an invalid entry are shown. Table t1 is created with only one column of type tinyint. In the statements that follow, the default SQL Server behavior, and ARITHABORT and ARITHIGNORE are shown.

CREATE TABLE t1

(

col1	tinyint	NOT NULL

)

go

INSERT t1 VALUES(-1)

go

Arithmetic overflow occurred.
(0 row(s) affected)

SET ARITHABORT ON

go

INSERT t1 VALUES(-1)

go

Arithmetic overflow error for type tinyint, value = -1.

SET ARITHABORT OFF

SET ARITHIGNORE ON

go

INSERT t1 VALUES(-1)

go

(0 row(s) affected)

See Also

Batches	Keywords
CREATE PROCEDURE	NULL Values
CREATE TRIGGER	Quoted Identifiers
IDENTITY


SETUSER Statement

Allows a database owner to impersonate another user. The SETUSER statement is used by the system administrator or a database owner when he or she wants to adopt the identity of another user in order to use another user's database object, to grant permissions to that object, to create an object, and so on.

Syntax

SETUSER ['username' [WITH NORESET]]

where

username

Specifies the name of the user who will be impersonated by the system administrator or the database owner. The username supplied must be listed in the sysusers table. When no username is specified, the original identity of the system administrator or database owner is re-established.

NORESET

Specifies that subsequent SETUSER statements (with no specified username) will not reset to the system administrator or database owner.

Remarks

Using SETUSER to impersonate a user, a database owner, or system administrator will have only those rights given to the user being impersonated. Because the owner of an object always retains the rights to that object, no users, other than those given explicit permission to that object, can access it. Because a database owner and the system administrator always have supervisory permission over their database (or the system) they can temporarily adopt another database user's identity. The database owner or system administrator can act as that user, create objects in that user's name, and test permissions as given to that user. The SETUSER statement remains in effect until another SETUSER statement is issued or until the current database is changed with the USE statement.

In SQL Server 6.0, the SETUSER statement does not need to be used to drop objects owned by another user. The database owner and system administrator can drop user's objects by explicitly qualifying the object name with the owner's name. For details, see the DROP statements (DROP DEFAULT, DROP PROCEDURE, DROP TABLE, and so on).

In earlier releases of SQL Server, the system administrator retained full system administrator permissions and could not use SETUSER to acquire another user's permissions. If you want to maintain compatibility with this previous behavior, use trace flag 206. For details, see the Trace Flags topic.

Permission

Execute permission defaults to the database owner and is not transferable.

Examples

A.	SETUSER

In this example, Mary (the database username of mary) has created a table called computer_types. Mary happens to be out of town and another user (Joe) needs to access Mary's computer_types table. The database owner or system administrator can execute:

SETUSER 'mary'

go

GRANT SELECT ON computer_types TO joe

go

SETUSER

B.	NORESET Option

In this example, the database owner needs to create some objects and then test their usability with minimal permissions. For simplicity, the database owner wants to maintain only Mary's permission for the entire session. The database owner or system administrator can execute:

SETUSER 'mary' WITH NORESET

go

CREATE TABLE computer_types2

.

.

.

GRANT ...

go

SETUSER	/* This statement will have no effect. */

The only way the database owner or system administrator can re-establish his or her own rights is to log off and then log on again.

See Also

GRANT	USE
REVOKE


SHUTDOWN Statement

Stops SQL Server. Only the system administrator can execute this statement.

Syntax

SHUTDOWN [WITH NOWAIT]

where

WITH NOWAIT

Shuts down SQL Server immediately, without performing checkpoints in every database. SQL Server exits after attempting to terminate all user processes and roll back any active transactions.

Remarks

Unless the system administrator uses the WITH NOWAIT option, SHUTDOWN tries to shut down SQL Server in an orderly fashion by:

1.	Disabling logins (except for the system administrator). To see a listing of all current users, use the sp_who system stored procedure.

2.	Waiting for currently executing Transact-SQL statements or stored procedures to finish. To see a listing of all active processes and locks, use the sp_lock and sp_who system stored procedures.

3.	Performing a checkpoint in every database.

Using the SHUTDOWN statement minimizes the amount of automatic recovery work needed when the system administrator restarts SQL Server.

The following tools and methods can also be used to stop SQL Server. Each of these performs a checkpoint in all databases and then a SHUTDOWN WITH NOWAIT to flush all committed data from data cache and stop the server quickly.

•	SQL Enterprise Manager.

•	NET STOP SQLSERVER from a Win32 command prompt.

SQL Server can also be stopped by the following methods. Because these methods do not perform checkpoints in each database prior to shutdown, they are not recommended and may increase the recovery time needed the next time the server is restarted. You can stop SQL Server in these additional ways:

•	By using the Services application from the Windows NT Control Panel.

•	By pressing CTRL+C if sqlservr.exe was started from the command-line.

Permission

SHUTDOWN permission defaults to the system administrator and cannot be transferred.

See Also

sqlservr Command-line Executable	sp_who System Stored Procedure
sp_lock System Stored Procedure


Stored Procedures

Catalog Stored Procedures

Extended Stored Procedures

Replication Stored Procedures

SQL Executive Stored Procedures

System Stored Procedures


Stored Procedures-Catalog Stored Procedures

Catalog stored procedures provide a uniform catalog interface for accessing database gateways as well as SQL Server from the same application. These stored procedures are compatible with the catalog interface for the Microsoft Open Database Connectivity (ODBC) API.

These are the SQL Server catalog stored procedures:

sp_column_privileges	sp_special_columns
sp_columns	sp_sproc_columns
sp_databases	sp_statistics
sp_datatype_info	sp_stored_procedures
sp_fkeys	sp_table_privileges
sp_pkeys	sp_tables
sp_server_info
Some of these stored procedures support wildcard pattern matching for some parameters. Wildcard pattern matching allows you to substitute the % and _ characters for one or more characters in the parameter, just as in a LIKE expression in Transact-SQL. For example, to find all tables in the current database starting with the letter s, type:

sp_tables 's%'

For details about catalog stored procedures, see the description of the specific catalog stored procedure in the following sections or see the Microsoft ODBC Programmer's Reference and SDK Guide, available separately.


sp_column_privileges Catalog Stored Procedure

For more updated SQL Server 6.5 syntax, see sp_column_privileges.

Returns column privilege information for a single table in the current environment.

Syntax

sp_column_privileges table_name [, table_owner] [, table_qualifier]
[, column_name]

where

table_name

Specifies the table used to return catalog information. The table_name can be a variable-length character name with a maximum of 32 characters. Wildcard pattern matching is not supported.

table_owner

Specifies the table owner of the table used to return catalog information. The table_owner can be a variable-length character name with a maximum 32 characters. Wildcard pattern matching is not supported. If the 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 the table_owner is not specified and the current user does not own a table with the specified table_name, this procedure will look for a table with the specified table_name owned by the database owner. If one exists, that table's columns are returned.

table_qualifier

Is the name of the table qualifier. 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.

column_name

Specifies a single column and is used when only one column of catalog information is desired. If column_name is not specified, all columns will be returned. In Microsoft SQL Server, this column_name represents the column name as listed in the syscolumns table. The value specified can include wildcard characters using the underlying DBMS's wildcard matching patterns. For maximum interoperability, the gateway client should assume only ANSI-standard SQL pattern matching (the % and _ wildcard characters).

Remarks

With SQL Server, privileges are given with the GRANT statement and taken away by the REVOKE statement.

The sp_column_privileges catalog stored procedure is equivalent to SQLColumnPrivileges in ODBC. The results returned are order by TABLE_QUALIFIER, TABLE_OWNER, TABLE_NAME, COLUMN_NAME, and PRIVILEGE.

This is the results set:

Column	Datatype	Description
TABLE_QUALIFIER	varchar(32)	Is the name of the table qualifier. 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_OWNER	varchar(32)	Is the name of the table owner. Various DBMS products support three-part naming for tables (qualifier.owner.name). In Microsoft SQL Server, this column represents the name of the database user who created the table. This field will always return a value.
TABLE_NAME	varchar(32)	Is the name of the table. Various DBMS products support three-part naming for tables (qualifier.owner.name). In Microsoft SQL Server, this column represents the table name as listed in the sysobjects table. This field will always return a value.
COLUMN_NAME	varchar(32)	Is the name of the column, for each column of the TABLE_NAME returned. In Microsoft SQL Server, this column represents the column name as listed in the syscolumns table. This field will always return a value.
GRANTOR	varchar(32)	Is the name of the database user who has granted permissions on this COLUMN_NAME to the listed GRANTEE. In Microsoft SQL Server, this column will always be the same as the TABLE_OWNER. This field will always return a value.
GRANTEE	varchar(32)	Is the name of the database user who has been granted permissions on this COLUMN_NAME by the listed GRANTOR. In Microsoft SQL Server, this column will always include a database user from the sysusers table. This field will always return a value.
PRIVILEGE	varchar(32)	Is one of the available column privileges. Column privileges can be one of the following values (or other values supported by the data source when implementation is defined): SELECT   The GRANTEE can retrieve data for the columns. INSERT   The GRANTEE can provide data for this column when new rows are inserted (by the GRANTEE) into the table. UPDATE   The GRANTEE can modify existing data in the column. REFERENCES   The GRANTEE can reference a column in a foreign table in a primary key/foreign key relationship. In SQL Server 6.0, primary key/foreign key relationships are defined with table constraints.
IS_GRANTABLE	varchar(3)	Indicates whether the GRANTEE is permitted to grant privileges 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. In SQL Server 6.0, "grant with grant" permission is not supported.


sp_columns Catalog Stored Procedure

For more updated SQL Server 6.5 syntax, see sp_columns.

Returns column information for a single object that can be queried in the current environment. The returned columns belong to a table or a view.

Syntax

sp_columns object_name [, object_owner] [, object_qualifier] [, column_name]

where

object_name

Is the name of the table or view used to return catalog information. The object_name can be a variable character name with a maximum of 32 characters. Wildcard pattern matching is not supported.

object_owner

Specifies the object owner of the table or view used to return catalog information. The object_owner can be a variable character name with a maximum of 32 characters. Wildcard pattern matching is not supported. If object_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 object_owner is not specified and the current user does not own a table or view with the specified object_name, this procedure looks for a table or view with the specified object_name owned by the database owner. If one exists, that table's columns are returned.

object_qualifier

Specifies the name of the table or view qualifier. 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.

column_name

Specifies a single column and is used when only one column of catalog information is desired. If column_name is not specified, all columns will be returned. In Microsoft SQL Server, this column_name represents the column name as listed in the syscolumns table. The value specified can include wildcard characters using the underlying DBMS's wildcard matching patterns. For maximum interoperability, the gateway client should assume only ANSI-standard SQL pattern matching (the % and _ wildcard characters).

Remarks

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.

This is the results set:

Column	Datatype	Description
TABLE_QUALIFIER	varchar(32)	Is the name of the table or view qualifier. 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_OWNER	varchar(32)	Is the name of the table or view owner. Various DBMS products support three-part naming for tables (qualifier.owner.name). In Microsoft SQL Server, this column represents the name of the database user that created the table. This field will always return a value.
TABLE_NAME	varchar(32)	Is the name of the table or view. Various DBMS products support three-part naming for tables (qualifier.owner.name). In Microsoft SQL Server, this column represents the table or view name as listed in the sysobjects table. This field will always return a value.
COLUMN_NAME	varchar(32)	Is the name of the column, for each column of the TABLE_NAME returned. In Microsoft SQL Server, this column represents the column name as listed in the syscolumns table. This field will always return a value.
DATA_TYPE	smallint	Is an integer code for ODBC datatype. If this is a datatype that cannot be mapped to an ODBC type, it is NULL. The native datatype name is returned in the TYPE_NAME column.
TYPE_NAME	varchar(13)	Is a string representing a datatype. The underlying DBMS presents this datatype name.
PRECISION	int	Is the number of significant digits.
LENGTH	int	Is the transfer size of the data. (*)
SCALE	smallint	Is the number of digits to the right of the decimal point.
RADIX	smallint	Is the base for numeric types.
NULLABLE	smallint	Specifies nullability. 1 means NULL is possible; 0 means NOT NULL.
REMARKS	varchar(254)	For Microsoft SQL Server, this field will always return NULL.
SS_DATA_TYPE	tinyint	Is a SQL Server datatype, as defined in Microsoft SQL Server Programming Open Data Services, used by ODS gateway applications. The gateway converts the underlying data to this SQL Server datatype as the default. If the gateway supports configurable datatype conversions, either per installation or per session, then the conversion type is returned when the stored procedure is executed.
COLID	tinyint	Is a SQL Server − specific column appended to the result set. This column does not need to appear in Open Data Services gateway implementations of catalog stored procedures.
* For details about length, see the Microsoft ODBC Programmer's Reference and SDK Guide, available separately.


sp_databases Catalog Stored Procedure

Lists databases present in the SQL Server installation or accessible through a database gateway.

Syntax

sp_databases

Remarks

In SQL Server, sp_databases returns the databases listed in the sysdatabases system table. Because some DBMS systems 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.

The sp_databases catalog stored procedure has no equivalent in ODBC.

This is the results set:

Column	Datatype	Description
DATABASE_NAME	char(32)	Is the name of the database. In Microsoft SQL Server, this column represents the database name as stored in the sysdatabases system table.
DATABASE_SIZE	int	Is the size of database, in kilobytes.
REMARKS	int	For Microsoft SQL Server, this field will always return NULL.


sp_datatype_info Catalog Stored Procedure

For more updated SQL Server 6.5 syntax, see sp_datatype_info.

Returns information about the datatypes supported by the current environment.

Syntax

sp_datatype_info [data_type]

where

data_type

Is the code number for the specified datatype. The value supplied should be an integer value.

Remarks

The sp_datatype_info catalog stored procedure is equivalent to SQLGetTypeInfo in ODBC. The results returned are ordered by DATA_TYPE and then by how closely the datatype maps to the corresponding ODBC SQL data type.

This is the results set:

Column	Datatype	Description
TYPE_NAME	varchar(30)	Is a DBMS-dependent datatype name (the same as the TYPE_NAME column in the sp_columns results set).
DATA_TYPE	smallint	Is a code for the ODBC type to which all columns of this type are mapped.
PRECISION	int	Is the maximum precision of the datatype on the data source. NULL is returned for datatypes where precision is not applicable.
LITERAL_PREFIX	varchar(32)	Are character(s) used before a literal. For example, a single quotation mark (') for character types and 0x for binary in SQL Server.
LITERAL_SUFFIX	varchar(32)	Are character(s) used to terminate a literal. For example, a single quotation mark (') for character types and none for binary.
CREATE_PARAMS	varchar(32)	Is a description of the creation parameters for this datatype. For example, decimal is "precision, scale", float is NULL, and varchar is "max_length".
NULLABLE	smallint	Specifies nullability. 1 means this datatype can be created allowing null values; 0 means null values are not allowed.
CASE_SENSITIVE	smallint	Specifies case sensitivity. 1 means all columns of this type are case-sensitive (for collations); 0 means they are case-insensitive.
SEARCHABLE	smallint	Is a column type. 1 means columns of this type can be used in a WHERE clause.
UNSIGNED_ATTRIBUTE	smallint	Specifies the sign of the datatype. 1 means the datatype is unsigned; 0 means the datatype is signed.
MONEY	smallint	Specifies the money datatype. 1 means it is a money datatype; 0 means it is not.
AUTO_INCREMENT	smallint	Specifies auto-incrementing. 1 means the datatype is auto-incrementing; 0 means the datatype is not. NULL is returned if the attribute is not applicable to the datatype. An application can insert values into a column that has this attribute, but it cannot update the values in the column. This attribute is valid only for numeric datatypes.
LOCAL_TYPE_NAME	varchar(128)	Is the localized version of the data source−dependent name of the datatype. For example, DECIMAL is DECIMALE in French. NULL is returned if a localized name is not supported by the data source.
MINIMUM_SCALE	smallint	Is the minimum scale of the datatype on the data source. If a datatype has a fixed scale, the MINIMUM_SCALE and MAXIMUM_SCALE columns both contain this value. NULL is returned where scale is not applicable. For more information, see the Datatypes topic.
MAXIMUM_SCALE	smallint	Is the maximum scale of the datatype 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. For more information, see the Datatypes topic.
USERTYPE	smallint	The identifier for the datatype. In SQL Server 6.0, this is the uid of the datatype from the syscomments table.


sp_fkeys Catalog Stored Procedure

For more updated SQL Server 6.5 syntax, see sp_fkeys.

Returns logical foreign key information for the current environment.

Syntax

sp_fkeys [pktable_name] [, pktable_owner] [, pktable_qualifier]
[, fktable_name] [, fktable_owner] [, fktable_qualifier]

where

pktable_name

Specifies the table (with the primary key) used to return catalog information. The pktable_name can be a variable character name with a maximum 32 characters. Wildcard pattern matching is not supported. This parameter or the fktable_name parameter, or both, must be supplied.

pktable_owner

Is the name of the owner of the table (with the primary key) used to return catalog information. The pktable_owner parameter can be a variable character name with a maximum 32 characters. 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 the 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

Is the name of the table (with the primary key) qualifier. 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.

fktable_name

Specifies the name of the table (with a foreign key) used to return catalog information. The fktable_name can be a variable character name with a maximum of 32 characters. Wildcard pattern matching is not supported. This parameter or the pktable_name parameter, or both, must be supplied.

fktable_owner

Is the name of the owner of the table (with a foreign key) used to return catalog information. The fktable_owner can be a variable character name with a maximum of 32 characters. Wildcard pattern matching is not supported. If fktable_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 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

Specifies the name of the table (with a foreign key) qualifier. 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.

Remarks

If the primary key table name is supplied and the foreign key table name is NULL, this procedure 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, the procedure 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. The results returned are ordered by FKTABLE_QUALIFIER, FKTABLE_OWNER, FKTABLE_NAME, and KEY_SEQ.

This is the results set:

Column	Datatype	Description
PKTABLE_QUALIFIER	varchar(32)	Is the name of the table (with the primary key) qualifier. Various DBMS products support three-part naming for tables (qualifier.owner.name). In Microsoft SQL Server, this column represents the database name for the table with a PRIMARY KEY constraint. In some products, it represents the server name of the table's database environment. This field can be NULL.
PKTABLE_OWNER	varchar(32)	Is the name of the table (with the primary key) owner. Various DBMS products support three-part naming for tables (qualifier.owner.name). In Microsoft SQL Server, this column represents the name of the database user that created the table (with a PRIMARY KEY constraint). This field will always return a value.
PKTABLE_NAME	varchar(32)	Is the name of the table (with the primary key). Various DBMS products support three-part naming for tables (qualifier.owner.name). In Microsoft SQL Server, this column represents the table name (with a PRIMARY KEY constraint) as listed in the sysobjects table. This field will always return a value.
PKCOLUMN_NAME	varchar(32)	Is the name of the primary key column(s), for each column of the TABLE_NAME returned. In Microsoft SQL Server, this column represents the column name as listed in the syscolumns table. This field will always return a value.
FKTABLE_QUALIFIER	varchar(32)	Is the name of the table (with a foreign key) qualifier. Various DBMS products support three-part naming for tables (qualifier.owner.name). In Microsoft SQL Server, this column represents the database name for the table (with a FOREIGN KEY constraint). In some products, it represents the server name of the table's database environment. This field can be NULL.
FKTABLE_OWNER	varchar(32)	Is the name of the table (with a foreign key) owner. Various DBMS products support three-part naming for tables (qualifier.owner.name). In Microsoft SQL Server, this column represents the name of the database user that created the table (with a FOREIGN KEY constraint). This field will always return a value.
FKTABLE_NAME	varchar(32)	Is the name of the table (with a foreign key). Various DBMS products support three-part naming for tables (qualifier.owner.name). In Microsoft SQL Server, this column represents the table name as listed in the sysobjects table (with a FOREIGN KEY constraint). This field will always return a value.
FKCOLUMN_NAME	varchar(32)	Is the name of the foreign key column(s), for each column of the TABLE_NAME returned. In Microsoft SQL Server, this column represents the column name as listed in the syscolumns table. This field will always return a value.
KEY_SEQ	smallint	Is the sequence number of the column in a multicolumn primary key. This field will always return a value.
UPDATE_RULE	smallint	Is the action applied to the foreign key when the SQL operation is UPDATE. SQL Server returns 1 for these columns. Open Data Services gateways can return non-null 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	Is that action applied to the foreign key when the SQL operation is DELETE. SQL Server returns 1 for these columns. Open Data Services gateways can return non-null 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	varchar(128)	Is a foreign key identifier. It is NULL if not applicable to the data source. SQL Server 6.0 returns the FOREIGN KEY constraint name.
PK_NAME	varchar(128)	It is a primary key identifier. It is NULL if not applicable to the data source. SQL Server 6.0 returns the PRIMARY KEY constraint name.


sp_pkeys Catalog Stored Procedure

Returns primary key information for a single table in the current environment.

Syntax

sp_pkeys table_name [, table_owner] [, table_qualifier]

where

table_name

Specifies the table used to return catalog information. The table_name can be a variable-length character name with a maximum of 32 characters. Wildcard pattern matching is not supported.

table_owner

Specifies the table owner of the table used to return catalog information. The table_owner can be a variable character name with a maximum of 32 characters. Wildcard pattern matching is not supported. If the table_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 the table_owner is not specified and the current user does not own a table with the specified table_name, this procedure will look for a table with the specified table_name owned by the database owner. If one exists, that table's columns are returned.

table_qualifier

Is the name of the table qualifier. 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.

Remarks

In SQL Server 6.0, sp_pkeys returns information about columns explicitly defined with a PRIMARY KEY constraint. Because not all systems support explicitly named primary keys, the gateway implementor 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 and that 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.

This is the results set:

Column	Datatype	Description
TABLE_QUALIFIER	varchar(32)	Is the name of the table qualifier. 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_OWNER	varchar(32)	Is the name of the table owner. Various DBMS products support three-part naming for tables (qualifier.owner.name). In Microsoft SQL Server, this column represents the name of the database user who created the table. This field will always return a value.
TABLE_NAME	varchar(32)	Is the name of the table. Various DBMS products support three-part naming for tables (qualifier.owner.name). In Microsoft SQL Server, this column represents the table name as listed in the sysobjects table. This field will always return a value.
COLUMN_NAME	varchar(32)	Is the name of the column, for each column of the TABLE_NAME returned. In Microsoft SQL Server, this column represents the column name as listed in the syscolumns table. This field will always return a value.
KEY_SEQ	smallint	Is the sequence number of the column in a multicolumn primary key. NOT NULL.
PK_NAME	varchar(32)	Is a primary key identifier. Returns NULL if not applicable to the data source.


sp_server_info Catalog Stored Procedure

Returns a list of attribute names and matching values for SQL Server, the database gateway, and/or the underlying data source.

Syntax

sp_server_info [@attribute_id = ] attribute_id]

where

@attribute_id = attribute_id

Is the integer ID of the attribute.

Remarks

The sp_server_info stored procedure is a subset of the information provided by SQLGetInfo in ODBC.

This is the results set:

Column	Datatype	Description
ATTRIBUTE_ID	int	NOT NULL
ATTRIBUTE_NAME	varchar(60)	NOT NULL
ATTRIBUTE_VALUE	varchar(255)
These are the rows in this results set. 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 Name of the DBMS accessed by the gateway.	Microsoft SQL Server
2	DBMS_VER Version of the DBMS accessed by the gateway.	@@version string
10	OWNER_TERM DBMS vendor's term for a table owner (the second part of a three-part name).	Owner
11	TABLE_TERM DBMS vendor's term for a table (the second part of a three-part name).	Table
12	MAX_OWNER_NAME_LENGTH Maximum length of the name for a table owner (the second part of a three-part name).	30
16	IDENTIFIER_CASE The case-sensitivity of user-defined names (table names, column names, stored procedure names) in the database (the case in which these objects are presented in the system catalogs).	MIXED
15	COLUMN_LENGTH Maximum number of characters for a column name.	30
13	TABLE_LENGTH Maximum number of characters for a table name.	30
100	USERID_LENGTH Maximum number of characters for a username.	30
17	TX_ISOLATION Initial transaction isolation level the server assumes, corresponding to an isolation level defined in ANSI SQL-92.	2
18	COLLATION_SEQ Assumed ordering of the character set for this server.	charset ID
14	MAX_QUAL_LENGTH Maximum length of the name for a table qualifier (the first part of a three-part table name).	30
101	QUALIFIER_TERM DBMS vendor's term for a table qualifier (the first part of a three-part name).	Database
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 results sets (multiple statements can be sent through the gateway with multiple results sets returned to the client).	Y
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
113	REMOTE_SPROC Specifies whether stored procedures can be executed through the remote stored procedure functions in DB-Library.	Y
22	ACCESSIBLE_TABLES Specifies whether in the sp_tables stored procedure, the gateway returns only tables, views, and so on that are accessible by the current user (that is, the user who has at least SELECT privileges for the table).	Y
104	ACCESSIBLE_SPROC Specifies whether in the sp_stored_procedures stored procedure, the gateway returns only stored procedures that are executable by the current user.	Y
105	MAX_INDEX_COLS 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.	N
111	DESCENDING_INDEXES Specifies whether descending indexes are supported.	N
112	SP_RENAME Specifies whether a stored procedure can be renamed.	Y
500	SYS_SPROC_VERSION The version of the catalog stored procedures currently implemented.	Current version number


sp_special_columns Catalog Stored Procedures

Returns the optimal set of columns that uniquely identify a row in the table and columns that are automatically updated when any value in the row is updated by a transaction.

Syntax

sp_special_columns table_name [, table_owner] [, table_qualifier] [, col_type] [, scope] [, nullable]

where

table_name

Specifies the table used to return catalog information. The table_name can be a variable character length name with a maximum of 32 characters. Wildcard pattern matching is not supported.

table_owner

Specifies the table owner of the table used to return catalog information. The table_owner can be a variable character name with a maximum 32 characters. Wildcard pattern matching is not supported. If the table_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 the table_owner is not specified and the current user does not own a table with the specified table_name, this procedure will look for a table with the specified table_name owned by the database owner. If one exists, that table's columns are returned.

table_qualifier

Is the name of the table qualifier. 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.

col_type

Specifies the column type, either R or V. 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 pseudo column 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

Specifies the minimum required scope of the ROWID, either C or 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

Specifies whether or not the special column can accept a null value, either U or O. Nullable U specifies that this special column allows null values. Nullable O is a special column that does not allow null values.

Remarks

The sp_special_columns stored procedure is equivalent to SQLSpecialColumns in ODBC. The results returned are ordered by SCOPE.

This is the results set:

Column	Datatype	Description
SCOPE	int	Is the actual scope of the row ID. Can be 0, 1, or 2. SQL Server always returns 0. This field will always return 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	varchar(32)	Is the name of the column, for each column of the TABLE_NAME returned. In Microsoft SQL Server, this column represents the column name as listed in the syscolumns table. This field will always return a value.
DATA_TYPE	smallint	Is an ODBC SQL datatype.
TYPE_NAME	varchar(13)	Is a data source−dependent datatype name; for example, 'CHAR', 'VARCHAR', 'MONEY', or 'TEXT'.
PRECISION	int	Is the precision of the column on the data source. This field will always return a value.
LENGTH	int	Is the length, in bytes, required for the datatype in its binary form in the data source. For example, 10 for CHAR(10), 4 for INTEGER, and 2 for SMALLINT.
SCALE	smallint	Is the scale of the column on the data source. NULL is returned for datatypes where scale is not applicable.
PSEUDO_COLUMN	smallint	Indicates whether the column is a pseudo column. SQL Server 6.0 always returns 2. Can be: 0 SQL_PC_UNKNOWN 1 SQL_PC_PSEUDO 2 SQL_PC_NOT_PSEUDO


sp_sproc_columns Catalog Stored Procedures

For more updated SQL Server 6.5 syntax, see sp_sproc_columns.

Returns column information for a single stored procedure in the current environment.

Syntax

sp_sproc_columns procedure_name [, procedure_owner] [, procedure_qualifier] [, column_name]

where

procedure_name

Is the name of the procedure used to return catalog information. The procedure_name can be a variable character name with a maximum of 42 characters. Wildcard pattern matching is not supported.

procedure_owner

Is the name of the owner of the procedure used to return catalog information. The procedure_owner can be a variable character name with a maximum of 30 characters. Wildcard pattern matching is not supported. If procedure_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 table's columns are returned. If procedure_owner is not specified and the current user does not own a procedure with the specified procedure_name, this procedure looks for a procedure with the specified procedure_name owned by the database owner. If one exists, that table's columns are returned.

procedure_qualifier

Specifies the name of the procedure qualifier. 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.

column_name

Specifies a single column and is used when only one column of catalog information is desired. If column_name is not specified, all columns will be returned. In Microsoft SQL Server, this column_name represents the column name as listed in the syscolumns table. The value specified can include wildcard characters using the underlying DBMS's wildcard matching patterns. For maximum interoperability, the gateway client should assume only ANSI-standard SQL pattern matching (the % and _ wildcard characters).

Remarks

The returned columns belong to the parameters or results set of a stored procedure. If the SP_NUM_PARAMETERS and SP_NUM_RESULT_SETS columns returned by sp_stored_procedure for a particular stored procedure are −1 (indeterminate), sp_proc_columns returns no rows for that stored procedure. In SQL Server 6.0, only the column information about input and output parameters for the stored procedure are returned.

The sp_sproc_columns catalog stored procedure 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.

This is the results set:

Column	Datatype	Description
PROCEDURE_QUALIFIER	char(32)	Is the name of the procedure qualifier. 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.
PROCEDURE_OWNER	char(32)	Is the name of the procedure owner. Various DBMS products support three-part naming for tables (qualifier.owner.name). In Microsoft SQL Server, this column represents the name of the database user that created the table. This field will always return a value.
PROCEDURE_NAME	char(41)	Is the name of the procedure. Various DBMS products support three-part naming for tables (qualifier.owner.name). In Microsoft SQL Server, this column represents the procedure name as listed in the sysobjects table. This field will always return a value.
COLUMN_NAME	char(32)	Is the name of the column, for each column of the TABLE_NAME returned. In Microsoft SQL Server, this column represents the column name as listed in the syscolumns table. This field will always return a value.
COLUMN_TYPE	smallint	This field will always return a value. Can be: 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	Is an integer code for an ODBC datatype. If this datatype cannot be mapped to an ANSI type, the value will be NULL. The native datatype name is returned in the TYPE_NAME column.
TYPE_NAME	char(30)	Is the string representation of the datatype. This is the datatype name as presented by the underlying DBMS.
PRECISION	int	Is the number of significant digits.
LENGTH	int	Is the transfer size of the data.
SCALE	smallint	Is the number of digits to the right of the decimal point.
RADIX	smallint	Is the base for numeric types.
NULLABLE	smallint	Specifies nullability. 1 means this datatype can be created allowing null values; 0 means null values are not allowed.
REMARKS	varchar(254)	Is a description of the procedure column. SQL Server will not return a value for this column.
SS_DATA_TYPE	tinyint	Is a SQL Server datatype, as defined in Microsoft SQL Server Programming DB-Library for C. The gateway converts the underlying data to this SQL Server datatype as the default, for use by Open Data Services gateway implementations of catalog stored procedures. If the gateway supports configurable datatype conversions, either per installation or per session, the conversion type when the stored procedure is executed is returned.
COLID	tinyint	Is a SQL Server − specific column added to the result set. This column does not need to appear in Open Data Services gateway implementations of catalog stored procedures.


sp_statistics Catalog Stored Procedures

Returns a list of all indexes on a specified table.

Syntax

sp_statistics table_name [, table_owner] [, table_qualifier]
[, index_name] [, is_unique]

where

table_name

Specifies the table used to return catalog information. The table_name can be a variable character length name with a maximum of 32 characters. Wildcard pattern matching is not supported.

table_owner

Specifies the table owner of the table used to return catalog information. The table_owner can be a variable character name with a maximum 32 characters. Wildcard pattern matching is not supported. If the table_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 the table_owner is not specified and the current user does not own a table with the specified table_name, this procedure will look for a table with the specified table_name owned by the database owner. If one exists, that table's columns are returned.

table_qualifier

Is the name of the table qualifier. 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.

index_name (varchar(32))

Is the index name. Wildcard pattern matching is not supported.

is_unique (char(1))

Identifies indexes to be returned. Enter Y if only unique indexes are to be returned.

Remarks

The indexes in the results 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.

The sp_statistics stored procedure is equivalent to SQLStatistics in ODBC. The results returned are ordered by NON_UNIQUE, TYPE, INDEX_QUALIFIER, INDEX_NAME, and SEQ_IN_INDEX.

This is the results set:

Column	Datatype	Description
TABLE_QUALIFIER	varchar(32)	Is the name of the table qualifier. 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_OWNER	varchar(32)	Is the name of the table owner. Various DBMS products support three-part naming for tables (qualifier.owner.name). In Microsoft SQL Server, this column represents the name of the database user who created the table. This field will always return a value.
TABLE_NAME	varchar(32)	Is the name of the table. Various DBMS products support three-part naming for tables (qualifier.owner.name). In Microsoft SQL Server, this column represents the table name as listed in the sysobjects table. This field will always return a value.
NON_UNIQUE	smallint	NOT NULL. 0 means unique; 1 means non unique.
INDEX_QUALIFIER	varchar(32)	Is the name of the index owner. Some DBMS products allow users other than the table owner to create indexes. In Microsoft SQL Server, this column will always be the same as TABLE_OWNER.
INDEX_NAME	varchar(32)	Is the name of the index. This field will always return a value.
TYPE	smallint	This field will always return a value. SQL Server 6.0 returns 0, 1, or 3. Can be: 0 Statistics for a table 1 Clustered 2 Hashed 3 Other
SEQ_IN_INDEX	smallint	Is the position of the column within the index.
COLUMN_NAME	varchar(32)	Is the name of the column, for each column of the TABLE_NAME returned. In Microsoft SQL Server, this column represents the column name as listed in the syscolumns table. This field will always return a value.
COLLATION	char(1)	Is the order used in collation. SQL Server 6.0 always returns A. Can be: A          Ascending D          Descending NULL  Not applicable
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	varchar(128)	SQL Server 6.0 does not return a value.


sp_stored_procedures Catalog Stored Procedures

Returns a list of stored procedures in the current environment.

Syntax

sp_stored_procedures [procedure_name] [, procedure_owner] [, procedure_qualifier]

where

procedure_name

Is the name of the procedure used to return catalog information. The procedure_name can be a variable character name with a maximum of 42 characters. Wildcard pattern matching is supported.

procedure_owner

Is the name of the owner of the procedure used to return catalog information. The procedure_owner can be a variable character name with a maximum of 30 characters. Wildcard pattern matching is supported. If procedure_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 table's columns are returned. If procedure_owner is not specified and the current user does not own a procedure with the specified procedure_name, this procedure looks for a procedure with the specified procedure_name owned by the database owner. If one exists, that table's columns are returned.

procedure_qualifier

Specifies the name of the procedure qualifier. 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.

Remarks

For maximum interoperability, the gateway client should assume only ANSI-standard SQL 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 results set for sp_server_info, then only stored procedures that can be executed by the current user are returned.

The sp_stored_procedures stored procedure is equivalent to SQLProcedures in ODBC. The results returned are ordered by PROCEDURE_QUALIFIER, PROCEDURE_OWNER, and PROCEDURE_NAME.

This is the results set:

Column	Datatype	Description
PROCEDURE_QUALIFIER	varchar(32)	Is the name of the procedure qualifier. 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.
PROCEDURE_OWNER	varchar(32)	Is the name of the procedure owner. Various DBMS products support three-part naming for tables (qualifier.owner.name). In Microsoft SQL Server, this column represents the name of the database user that created the table. This field will always return a value.
PROCEDURE_NAME	varchar(41)	Is the name of the procedure. Various DBMS products support three-part naming for tables (qualifier.owner.name). In Microsoft SQL Server, this column represents the procedure name as listed in the sysobjects table. This field will always return 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)	Is a description of the procedure. SQL Server will not return a value for this column.
PROCEDURE_TYPE	smallint	Is the procedure type. SQL Server 6.0 always returns 2.0. Can be: 0 SQL_PT_UNKNOWN 1 SQL_PT_PROCEDURE 2 SQL_PT_FUNCTION


sp_table_privileges Catalog Stored Procedures

For more updated SQL Server 6.5 syntax, see sp_table_privileges.

Returns privilege information for a single table in the current environment.

Syntax

sp_table_privileges table_name [, table_owner] [, table_qualifier]

where

table_name

Specifies the table used to return catalog information. The table_name can be a variable character length name with a maximum of 32 characters. Wildcard pattern matching is supported.

table_owner

Specifies the table owner of the table used to return catalog information. The table_owner can be a variable character name with a maximum of 32 characters. Wildcard pattern matching is supported. If the table_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 the table_owner is not specified and the current user does not own a table with the specified table_name, this procedure will look for a table with the specified table_name owned by the database owner. If one exists, that table's columns are returned.

table_qualifier

Is the name of the table qualifier. 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.

Remarks

SQL Server does not support the ability to grant privileges through SELECT_GRANTABLE, INSERT_GRANTABLE, UPDATE_GRANTABLE, DELETE_GRANTABLE, and REFERENCES_GRANTABLE.

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.

This is the results set:

Column	Datatype	Description
TABLE_QUALIFIER	varchar(32)	Is the name of the table qualifier. 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_OWNER	varchar(32)	Is the name of the table owner. Various DBMS products support three-part naming for tables  (qualifier.owner.name). In Microsoft SQL Server, this column represents the name of the database user who created the table. This field will always return a value.
TABLE_NAME	varchar(32)	Is the name of the table. Various DBMS products support three-part naming for tables (qualifier.owner.name). In Microsoft SQL Server, this column represents the table name as listed in the sysobjects table. This field will always return a value.
GRANTOR	varchar(32)	Is the name of the database user who has granted permissions on this TABLE_NAME to the listed GRANTEE. In Microsoft SQL Server, this column will always be the same as the TABLE_OWNER. This field will always return a value.
GRANTEE	varchar(32)	Is the name of the database user who has been granted permissions on this TABLE_NAME by the listed GRANTOR. In Microsoft SQL Server, this column will always include a database user from the sysusers table. This field will always return a value.
PRIVILEGE	varchar(32)	Is one of the available table privileges. Table privileges can be one of the following values (or other values supported by the data source when implementation is defined): SELECT The GRANTEE can retrieve data for one or more of the columns. INSERT The GRANTEE can provide data for new rows for one or more of the columns. UPDATE The GRANTEE can modify existing data for one or more of the columns. DELETE The GRANTEE can remove rows from the table. REFERENCES The GRANTEE can reference a column in a foreign table in a primary key/foreign key relationship. In SQL Server 6.0, 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 might 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 privileges 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. In SQL Server 6.0, "grant with grant" permission is not supported.


sp_tables Catalog Stored Procedures

Returns a list of objects that can be queried in the current environment (that is, any object that can appear in a FROM clause).

Syntax

sp_tables [table_name] [, table_owner] [, table_qualifier] [, table_type]

where

table_name

Specifies the table used to return catalog information. The table_name can be a variable character length name with a maximum of 32 characters. Wildcard pattern matching is supported.

table_owner

Specifies the table owner of the table used to return catalog information. The table_owner can be a variable character name with a maximum of 32 characters. Wildcard pattern matching is supported. If the table_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 the table_owner is not specified and the current user does not own a table with the specified table_name, this procedure will look for a table with the specified table_name owned by the database owner. If one exists, that table's columns are returned.

table_qualifier

Is the name of the table qualifier. 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.

table_type (varchar(60))

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/or 'VIEW'.

Note  Single quotation marks must surround each table type, and double quotation marks must enclose the entire parameter. Table types must be uppercase. If QUOTED_IDENTIFIER is on, each single quotation mark must be doubled and the entire parameter must be surrounded by single quotation marks.

Remarks

For maximum interoperability, the gateway client should assume only ANSI-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 results 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 results set for sp_server_info, only tables that are accessible by the current user are returned.

The sp_tables stored procedure is equivalent to SQLTables in ODBC. The results returned are ordered by TABLE_TYPE, TABLE_QUALIFIER, TABLE_OWNER, and TABLE_NAME.

This is the results set:

Column	Datatype	Description
TABLE_QUALIFIER	varchar(32)	Is the name of the table qualifier. 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_OWNER	varchar(32)	Is the name of the table owner. Various DBMS products support three-part naming for tables (qualifier.owner.name). In Microsoft SQL Server, this column represents the name of the database user who created the table. This field will always return a value.
TABLE_NAME	varchar(32)	Is the name of the table. Various DBMS products support three-part naming for tables (qualifier.owner.name). In Microsoft SQL Server, this column represents the table name as listed in the sysobjects table. This field will always return a value.
TABLE_TYPE	varchar(32)	Is a table, system table or view.
REMARKS	varchar(254)	SQL Server does not return a value for this column.


Stored Procedures-Extended Stored Procedures

Extended stored procedures provide a way to dynamically load and execute a function within a dynamic-link library (DLL) in a manner similar to that of a stored procedure, seamlessly extending SQL Server functionality. Actions outside of SQL Server can be easily triggered and external information returned to SQL Server. Return status codes and output parameters (identical to their counterparts in regular stored procedures) are also supported. SQL Server includes system stored procedures that add (sp_addextendedproc), drop (sp_dropextendedproc), and provide information about (sp_helpextededproc) extended stored procedures.

For better performance, extended stored procedures are implemented as DLLs rather than as separate processes. A separate process requires a context switch as well as additional security overhead. Instead, the DLL is executed by the user thread and is part of the SQL Server process, and therefore shares its address space and Windows NT system security privileges. However, the DLL does not know of, or have direct access to, SQL Server data structures.

Extended stored procedures are categorized by their use. The categories of extended procedures are:

Integrated Security

These are the Integrated Security extended stored procedures:

xp_enumgroups	xp_logininfo
xp_grantlogin	xp_revokelogin
xp_loginconfig
SQL Mail

These are the SQL Mail extended stored procedures:

xp_deletemail	xp_sendmail
xp_findnextmsg	xp_startmail
xp_readmail	xp_stopmail
General

These are the general extended stored procedures:

xp_cmdshell	xp_sprintf
xp_logevent	xp_sscanf
xp_msver
Internal

A number of additional extended stored procedures exist for internal use by other stored procedures (replication, system, and so on). Although these procedures can be executed separately, they are not guaranteed to be included in future releases.

User-defined

Additional extended stored procedures can be created by programmers using Microsoft Open Data Services. For information about creating extended stored procedures, see Microsoft SQL Server Programming Open Data Services.

An additional level of security is added to the DLL by the SQL Server exception handler, which prevents the entire SQL Server from being stopped if an extended stored procedure causes a protection violation (typically, only that thread would be affected). SQL Server is protected from DLLs that might affect memory or harm the running SQL Server process. However, because SQL Server and all DLLs do share address space, there is always some small risk that a poorly written or insufficiently tested DLL could disrupt the entire system. It is important that the DLL (and all extended stored procedures within it) be well written and tested extensively. For this reason, only the SA can add extended stored procedures (using sp_addextendedproc).

Important  Because extended stored procedures are external to SQL Server, they must be specified in the case (lowercase for all SQL Server−supplied extended stored procedures) in which they were designed.

Each of the following sections describe these extended stored procedures.


xp_cmdshell Extended Stored Procedure

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

Syntax

xp_cmdshell command_string [, no_output]

where

command_string

Specifies the command string to execute at the operating-system command shell.

no_output

Is an optional parameter that executes the given command_string but does not return any output to the client.

Remarks

Be aware that when you grant execute permission for xp_cmdshell to users, the users will be able to execute any operating-system command at the Windows NT command shell that the account running SQL Server (typically local system) has privilege to execute.

To restrict xp_cmdshell access to users who have administrator permission on the Windows NT-based computer where SQL Server is running, use SQL Setup or SQL Enterprise Manager to set the server options, selecting the "xp_cmdshell - Impersonates Client" option.  With this option selected, only users who have connected to SQL Server via a trusted connection and are members of the local Administrators group on that computer are allowed to use xp_cmdshell. The commands run by xp_cmdshell continue to execute in the server's security context.

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.	Do Not Return Output

This example uses xp_cmdshell to execute a command string without returning the output to the client.

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.

DECLARE @result int

EXEC @result = xp_cmdshell "dir *.exe"

IF (@result = 1)

PRINT "Success"

ELSE

PRINT "Failure"

Permission

Execute permission defaults to the system administrator, who can grant permission to other users.

See Also

CREATE PROCEDURE	EXECUTE
CREATE TRIGGER


xp_deletemail Extended Stored Procedure

Deletes a message from the SQL Server inbox. This procedure is used by the sp_processmail system stored procedure to process mail in the SQL Server inbox.

Syntax

xp_deletemail [@msg_id = ] msg_id

where

@msg_id = msg_id

Specifies the ID (as assigned by xp_findnextmsg) of the mail message in the inbox that should be deleted.

Remarks

This extended stored procedure returns a successful (0) or failed (1) status. Any failure except an invalid parameter is logged to the Windows NT application event log.

Example

This example deletes the message ID as supplied from xp_findnextmsg. In this example, the value from xp_findnextmsg is placed in a local variable named @message_id.

xp_deletemail @message_id

Permission

Execute permission defaults to the system administrator, who can grant permission to other users.

See Also

sp_processmail	xp_sendmail
xp_findnextmsg	xp_startmail
xp_readmail	xp_stopmail


xp_enumgroups Extended Stored Procedure

Provides a list of local Windows NT − based groups or a list of groups defined in a specified Windows NT domain.

Syntax

xp_enumgroups [domain_name]

where

domain_name

Is the name of the Windows NT domain to enumerate a list of groups for.

Remarks

The xp_enumgroups extended stored procedure enumerates the global groups in a domain. If domain_name is the name of the Windows NT − based computer on which SQL Server is running, xp_enumgroups enumerates the computer's local groups. If no domain name is specified, the computer's local groups are enumerated.

Example

This example enumerates the groups in the salesdomain domain.

xp_enumgroups salesdomain

Permission

Execute permission defaults to the system administrator and can be granted to other users.

See Also

xp_grantlogin	xp_logininfo
xp_loginconfig	xp_revokelogin


xp_findnextmsg Extended Stored Procedure

Accepts a message ID for input and returns the message ID for output. This extended stored procedure is used with the sp_processmail system stored procedure in order to process mail in the SQL Server inbox.

Syntax

xp_findnextmsg [@msg_id = msg_id [OUTPUT]]
[, @type = type]
[, @unread_only = {'true' | 'false'}])

where

@msg_id = msg_id

Is an input and output parameter; specifies the string of the message on input and the string of the next message on output.

OUTPUT

When specified, places the value of the msg_id in the output parameter. When not specified, the msg_id is returned as a single-column, single-row results set.

@type = type

Is the input message type based on the MAPI mail definition:

IP[M | C].Vendorname.subclass

Message types beginning with IPM will appear in the inbox of the mail client, and will be found or read by xp_findnextmsg if the @type is NULL. 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 = 'true' | 'false'

Specifies that only unread messages are considered. The default is true.

Remarks

This extended stored procedure returns a successful (0) or failed (1) status. Any failure except an invalid parameter is logged to the Windows NT application event log.

Example

This example returns the status when searching for the next message ID (for only unread messages). In this example, the value from xp_findnextmsg is placed in a local variable named @message_id.

EXEC @status = xp_findnextmsg @msg_id = @message_id OUTPUT

Permission

Execute permission defaults to the system administrator, who can grant permission to other users.

See Also

sp_processmail	xp_sendmail
xp_deletemail	xp_startmail
xp_readmail	xp_stopmail


xp_grantlogin Extended Stored Procedure

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

Syntax

xp_grantlogin 'account_name' [, {'admin' | 'repl' | 'user'}]

where

account_name

Specifies the Windows NT − based group or user. The group or user must already be defined in Windows NT. If the group or username does not include a domain name and a backslash (\), Windows NT initially searches for a matching user on the local computer, then on the primary domain controller, and then on trusted domains.

admin

Gives account_name system administrator privilege.

repl

Gives account_name privilege to log on as repl_publisher.

user

Explicitly gives account_name user privilege. If no parameter is specified, user privilege is granted.

Remarks

You can change accounts from one privilege level to another by executing xp_grantlogin.

Example

This example grants SQL Server access to the sqladmins group and gives the group system administrator privilege.

xp_grantlogin 'sqladmins', 'admin'

Permission

Execute permission defaults to the system administrator and can be granted to other users.

See Also

xp_enumgroups	xp_logininfo
xp_loginconfig	xp_revokelogin


xp_logevent Extended Stored Procedure

Logs a user-defined message in the SQL Server log file and/or in the Windows NT Event Viewer. When sending messages from Transact-SQL procedures, triggers, batches, and so on, use the RAISERROR statement instead of xp_logevent. If raising an error to the client is not desired, xp_logevent can be used to send an alert without sending a message to the client.

Syntax

xp_logevent error_number, message, [severity]

where

error_number

Is a user-defined error number greater than 50,000. The maximum value is 1,073,741,823 (2 (30)  − 1).

message

Is a character string less than 255 characters. This message is logged in the SQL Server log file and/or in the Windows NT Event Viewer.

severity

Is one of three character strings: Informational, Warning, or Error. This parameter is optional; the default is Informational.

Remarks

The xp_logevent extended stored procedure does not call a client's message handler or set @@ERROR. To write messages to the Windows NT Event Viewer and/or to the SQL Server error log file with SQL Server 6.0, you can execute the RAISERROR statement. For details, see the RAISERROR statement.

Example

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)

SELECT @@tabname = 'titles'

SELECT @@username = USER_NAME()

SELECT @@message = 'The table "' + @@tabname + '" is not owned by the user
"' + @@username + '."'

EXEC xp_logevent 60000, @@message, informational

Permission

Execute permission defaults to the system administrator and can be granted to other users.

See Also

PRINT	RAISERROR


xp_loginconfig Extended Stored Procedure

Reports the login security configuration of the server.

Syntax

xp_loginconfig ['config_name']

where

config_name

Specifies the configuration value about which to display information. If no config_name is specified, all configuration values are reported. These values are valid:

Configuration value	Description
login mode	The login security mode. Possible values are standard, integrated, and mixed.
default login	The name of the default SQL Server login ID for authorized users of trusted connections (for users without matching login names in the syslogins table). This value is NULL if no default is allowed (users without matching login names in syslogins will not be allowed to connect) or if the login mode is standard.
default domain	The name of the default Windows NT domain for network users of trusted connections. This value is NULL if the login mode is standard.
audit level	The audit level. Possible values are none, success, failure, and all. Audits are written to the error log and/or 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 for users under integrated security. Possible values are true or false. If this is set, the network username appears in output from sp_who.
map _	Reports which special Windows NT characters are mapped to the valid SQL Server character _ (underscore). Possible values are domain separator, space, null, or any single character.
map #	Reports which special Windows NT characters are mapped to the valid SQL Server character # (pound sign). Possible values are domain separator, space, null, or any single character.
map $	Reports which 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.
Remarks

The xp_loginconfig extended stored procedure cannot be used to set configuration values. Use the SQL Server setup program to change configuration settings.

Example

A.	Report All Configuration Values

This example shows all of the currently configured settings for integrated login security.

xp_loginconfig

name	config_value
----------------	-------------------------
login mode	integrated
default login	guest
default domain	REDMOND
audit level	none
set hostname	false
map _	domain separator
map $	NULL
map #	-
B.	Report Login Mode Configuration Value

This example shows the setting for only the login mode.

xp_loginconfig 'login mode'

name	config_value
----------------	-------------------------
login mode	standard
Permission

Execute permission defaults to the system administrator and can be granted to other users.

See Also

xp_grantlogin	xp_revokelogin
xp_logininfo


xp_logininfo Extended Stored Procedure

Reports the account, the type of account, the privilege level of the account, the map name of the account, and the permission path by which the account has access to SQL Server.

Syntax

xp_logininfo ['account_name' [, 'all' | 'members']
[, [@@privilege] = variable_name OUTPUT]]

where

account_name

Is the name of a Windows NT − based group or user granted SQL Server access. If no account_name is given, all groups and users that have been explicitly granted login permission are reported.

all | members

Specifies whether to report information on all permission paths for the account, or to report information on the members of the group.

@@privilege = variable_name

Is an optional output parameter that returns the privilege level of the specified Windows NT account. The privilege level returned is 'user', 'admin', or 'repl'.

Remarks

If an 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 in which the groups were granted access to SQL Server). 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 is specified as the first parameter and all is specified as the second parameter, all permission paths for that account are listed. If a given username is a member of multiple groups, all of which have been granted access to SQL Server, multiple rows are returned. The system administrator 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. This parameter applies to both individual users and groups.

If account_name is specified as the first parameter and members is specified as the second parameter, then 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.

Examples

A.	Login Information for a Single Group

This example returns information about only a single group (admin).

EXEC xp_logininfo 'admin'

go

account name	type	privilege	mapped login name	permission path
----------------	-----------	---------	-----------------	---------------
SQLSRV\admin	user	(null)	(null)	Everyone
(1 row(s) affected)

These are the results columns for xp_logininfo:

Column heading	Description
account name	The fully qualified account name as known to Windows NT.
type	The type of Windows NT account. Valid values are user,  local group, global group, and well-known group.
privilege	The access privilege for SQL Server. Valid values are admin, repl, or user.
mapped login name	For user accounts with user privilege, mapped login name shows the mapped login name that SQL Server will try to use when logging in with this account, using the mapped rules with the domain name added before it.
permission path	The group membership that allowed the account access.
B.	Windows NT Account Information

This example shows how the optional output parameter that returns the privilege level of the specified Windows NT account might be used:

DECLARE @@value varchar (30)

SELECT @@value = NULL

EXEC xp_logininfo '\nwind1\plato', 'all', @@value OUTPUT

SELECT 'The NT account nwind1\plato has ''' + @@value + ''' privilege.'

Permission

Execute permission defaults to the system administrator and can be granted to other users.

See Also

xp_grantlogin	xp_revokelogin
xp_loginconfig


xp_msver Extended Stored Procedure

Returns and allows to be queried 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]

where

optname

Specifies one of these option names:

Option name	Internal version	Example of string description
ProductName	NULL	Microsoft SQL Server
ProductVersion	393216	6.00.105 (6.00 is the version, 105 is the internal build number used by Microsoft)
Language	1033	U.S. English
Platform	NULL	NT INTEL X86
Comments	NULL	NT INTEL X86
CompanyName	NULL	Microsoft Corporation
FileDescription	NULL	SQL Server Windows NT
FileVersion	NULL	1995.04.28
InternalName	NULL	SQLSERVR
LegalCopyright	NULL	Copyright © Microsoft Corp. 1995
LegalTrademarks	NULL	Microsoft® is a registered trademark of Microsoft Corporation
OriginalFilename	NULL	SQLSERVR.EXE
PrivateBuild	NULL	NULL
SpecialBuild	0	NULL
WindowsVersion	65680131	3.51 (1002) (3.51 is the Windows NT version, 1002 is the internal build number used by Microsoft)
ProcessorCount	1	1
ProcessorActiveMask	1	00000001
ProcessorType	486	PROCESSOR_INTEL_486
PhysicalMemory	32	32 (33357821)
Product ID	NULL	12345-1234567890
Remarks

The Product ID (PID) is specified during installation. The number entered is located on a sticker on the original SQL Server CD case.

Permissions

Execute permission defaults to the public group.


xp_readmail Extended Stored Procedure

Reads a mail message from the SQL Server mail inbox. This procedure is used by the sp_processmail system stored procedure to process all mail in the SQL Server inbox.

Syntax

xp_readmail ([@@msg_id = msg_id] [, @@type = type [OUTPUT]]
[, @@peek = {'true' | 'false'}]
[, @@suppress_attach = {'true' | 'false'}]
[, @@originator = @@sender OUTPUT]
[, @@subject = @@subject_line OUTPUT]
[, @@message = @@body_of_message OUTPUT]
[, @@recipients = @@recipient_list OUTPUT]
[, @@cc_list = @@cc_list OUTPUT]
[, @@bcc_list = @@bcc_list OUTPUT]
[, @@date_received = @@date OUTPUT]
[, @@unread = {'true' | 'false'}]
[, @@attachments = @@temp_file_paths OUTPUT])
[, @@skip_bytes = @@bytes_to skip OUTPUT]
[, @@msg_length = @@length_in_bytes OUTPUT])

where

@@msg_id = msg_id

Specifies the ID of the message to read.

@@type = type

Returns the message class based on the MAPI mail definition:

IP[M | C].Vendorname.subclass

If used on input, this must define the type for a specific message; this parameter is ignored on input if the msg_id is NULL.

The default type is NULL.

@@peek = {'true' | 'false'}

Allows SQL Server to return the message of the mail without changing the mail status to read. The default is false (treat the mail as though it has been read).

@@suppress_attach = {'true' | 'false'}

Suppresses mail attachments. When set to true, prevents the creation of temporary files when xp_readmail reads a message with attachments. The default is true (do not create temporary files).

@@originator = @@sender

Is the variable in which the mail address of the sender will be returned. Define this variable as varchar(255).

@@subject = @@subject_line

Is the variable in which the subject of the mail message will be returned. Define this variable as varchar(255).

@@message = @@body_of_message

Is the variable in which the body (the actual text) of the mail message will be returned. Define this variable as varchar(255).

@@recipients = @@recipient_list

Is the variable in which the list of the recipients of the mail message will be returned. Recipients' names are separated by a semicolon (;). Define this variable as varchar(255).

@@cc_list = @@cc_list

Is the variable in which the list of the copied recipients (cc:'ed) of the mail message will be returned. Recipients' names are separated by a semicolon (;). Define this variable as varchar(255).

@@bcc_list = @@bcc_list

Is the variable in which the list of the blind copy recipients (bcc:'ed) of the mail message will be returned. Recipients' names are separated by a semicolon (;). Define this variable as varchar(255).

@@date_received = @@date

Is the variable in which the date of the mail message will be returned. Define this variable as varchar(255).

@@unread = 'true' | 'false'

Specifies that only unread messages are considered. The default is true.

@@attachments = @@temp_file_paths

Is the variable in which the temporary paths of the mail attachments will be returned. Temporary paths are separated by a semicolon (;). Define this variable as varchar(255).

@@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 @@skip_bytes is used, @@body_of_message will include the next portion of the message and @@bytes_to_skip will return with the next starting point within the message (the previous @@bytes_to_skip plus the length of @@body_of_message).

@@msg_length = @@length_in_bytes OUTPUT

Returns the total length of the message, in bytes. When used with @@skip_bytes in a stored procedure, this parameter will allow messages to be read in chunks of 255 bytes.

Remarks

This extended stored procedure returns a successful (0) or failed (1) status. Any failure except an invalid parameter is logged to the Windows NT application event log.

Example

This example returns the status when reading a message. In this example, the value of a message ID from xp_findnextmsg is placed in a local variable named @@message_id and passed to xp_readmail.

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'

Permission

Execute permission defaults to the system administrator, who can grant permission to other users.

See Also

sp_processmail	xp_sendmail
xp_deletemail	xp_startmail
xp_findnextmsg	xp_stopmail


xp_revokelogin Extended Stored Procedure

Revokes SQL Server access from a Windows NT − based group or user.

Syntax

xp_revokelogin 'account_name'

where

account_name

Specifies the Windows NT − based group or username for which to revoke access. If the group or username does not include a domain name and a backslash (\), Windows NT initially searches for a matching user on the local computer, then on the primary domain controller, and then on trusted domains.

Remarks

You can revoke permission only on an account on which you have been explicitly granted permission through xp_grantlogin.

Example

This example revokes SQL Server access from the SQL Server Administrator group.

xp_revokelogin 'SQL Server administrator'

Permission

Execute permission defaults to the system administrator and can be granted to other users.

See Also

xp_grantlogin	xp_logininfo
xp_loginconfig


xp_sendmail Extended Stored Procedure

Sends a message, and/or a query results set, and/or an attachment to the specified recipients.

Syntax

xp_sendmail @@recipient = recipient [; recipient2; [...; recipientn]]
[, @@message = message]
[, @@query = query]
[, @@attachments = attachments]
[, @@copy_recipients = recipient [; recipient2; [...; recipientn]]]
[, @@blind_copy_recipients = recipient [; recipient2; [...; recipientn]]]
[, @@subject = subject]
[, @@type = type]
[, @@attach_results = {'true' | 'false'}]
[, @@no_output = {'true' | 'false'}]
[, @@no_header = {'true' | 'false'}]
[, @@width = width]
[, @@separator = separator]
[, @@echo_error = {'true' | 'false'}]
[, @@set_user = user]
[, @@dbuse = dbname]

where

@@recipient = recipient

Is a required parameter specifying the people to whom you are sending the mail. If you specify more than one name, separate the names with semicolons.

@@message = message

Is an optional parameter that specifies the message to be sent.

@@query = query

Is an optional parameter that specifies a valid SQL Server query, the result of which will be sent in mail.

@@attachments = attachments

Is an optional parameter that specifies a file to attach to the mail.

@@copy_recipients

Is an optional parameter that identifies recipients to whom you are sending a copy of the mail (cc:'ing).

@@blind_copy_recipients

Is an optional parameter that identifies recipients to whom you are sending a blind copy of the mail (bcc:'ing).

@@subject = subject

Is an optional parameter that specifies the subject of the mail. If you do not specify a subject, "SQL Server Message" is used as the subject.

@@type = type

Is the input message type based on the MAPI mail definition:

IP[M | C].Vendorname.subclass

Message types beginning with IPM will appear in the inbox of the mail client, and will be found or read by xp_findnextmsg if the @@type is NULL. 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 details about using custom message types, see the Microsoft Windows NT Resource Kit or the Microsoft Mail Technical Reference, available separately.

@@attach_results = {'true' | 'false'}

Is an optional parameter that specifies that the results 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 filename in @@attachments will be used as the filename for the results. If @@attachments is NULL, a filename will be generated with a .TXT extension. The default for this parameter is false, which means that the results set is appended to the message.

@@no_output = {'true' | 'false'}

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 = {'true' | 'false'}

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 that sets the line width of the output text for an @@query message. This parameter is identical to the /w parameter in isql. For queries that produce long output rows, use @@width together with @@attach_results to send the output without line breaks in the middle of output lines. The default width is 80 characters.

@@separator = separator

Specifies the column separator (field terminator) for each column of the results set. This allows the files to be accessible by spreadsheet applications for formatting, and so on. This parameter is identical to the /t parameter in isql. For example, use @@separator with @@attach_results to send files with comma-separated values.

@@echo_error = {'true' | 'false'}

When true, causes SQLMail 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 will be appended to the mail message.

Note  If @@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

Specifies the security context in which the query should be run. The default is 'guest' (the guest user).

@@dbuse = dbname

Specifies the database context in which the query should be run. The default is NULL (which means the user is placed in his or her default database).

Remarks

The SQLMail session must be started prior to executing xp_sendmail. Sessions can be started either automatically (using the Auto Start Mail Client option in the Set Server Options dialog box of setup) or with xp_startmail. One SQLMail session supports all users on the SQL Server, but only one user at a time can send a message. Other users sending mail messages will 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 that issued xp_sendmail. Note that @@query can be blocked by a lock held by the client connection that issued xp_sendmail. For example, if you are updating a table within a transaction and you create a trigger for that update that attempts to select the updated row information as the @@query parameter, the SQLMail connection will be blocked by the exclusive lock held on that row by the initial client connection.

For details, see the Microsoft SQL Server Administrator's Companion.

Examples

A.	With No Variables

This example sends a message to user1 that the master database is full.

xp_sendmail 'user1', 'The master database is full.'

B.	With Variables

This example sends the message to user1 and user2, with copies sent to user3 and user4. It also specifies a subject line for the message.

xp_sendmail @@recipients = 'user1;user2',

@@message = 'The master database is full.',
@@copy_recipients = 'user3;user4',
@@subject = 'Master Database Status'

C.	Send Results

This example sends the results of the sp_configure system stored procedure to user1.

xp_sendmail 'user1', @@query = 'sp_configure'

D.	Send Results as an Attached File

This example sends the results of the query SELECT * from sysobjects as a text file attachment to user1. It includes a subject line for the mail and a message that will appear before the attachment. The @@width option is used to prevent line breaks in the output lines.

xp_sendmail @@recipients = 'user1',

@@query = 'select * from sysobjects',
@@subject = 'SQL Server Report',
@@message = 'The contents of sysobjects:',
@@attach_results = 'TRUE', @@width = 250

E.	Send Messages Longer than 255 Characters

This example shows how to send a message longer than 255 characters. Because the @@message parameter is limited to the length of a varchar (as are all stored procedure parameters), this example writes the long message into a global temporary table consisting of a single text column. The contents of this temporary table are then sent in mail using the @@query parameter.

CREATE TABLE ##texttab (c1 text)
INSERT ##texttab values ('Put your long message here.')
DECLARE @@cmd varchar(56)
SELECT @@cmd = 'SELECT c1 FROM ##texttab
EXEC master.dbo.xp_sendmail 'user1',
@@query = @@cmd, @@no_header= 'TRUE'
DROP TABLE ##texttab

Permission

Execute permission defaults to the system administrator, who can grant permission to other users.

See Also

sp_processmail	xp_readmail
xp_deletemail	xp_startmail
xp_findnextmsg	xp_stopmail


xp_sprintf Extended Stored Procedure

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

where

@@string OUTPUT

Is a varchar OUTPUT parameter that will return the result string.

format

Is a format character string similar to that supported by the C-language sprintf. Currently, only the '%s' format argument is supported.

argument

Is a character string that represents the value of the corresponding format argument. As many as 50 arguments can be specified.

Example

Sending an INSERT

This example uses the @@string parameter to send an INSERT statement. The actual value of @@string will contain 'INSERT table1 VALUES(1, 2).'

DECLARE @@string varchar (255)

EXEC xp_sprintf @@string OUTPUT, 'INSERT INTO %s VALUES (%s, %s)', 'table1', '1', '2'

Permission

Execute permission defaults to the public group.

See Also

xp_sscanf


xp_sscanf Extended Stored Procedure

Reads data from the string into the argument locations given by each format argument.

Syntax

xp_sscanf string, format, [, argument]...

where

string

Is the character string to read the argument values from.

format

Is a formatted character string similar to what is supported by the C-language sscanf. Currently only the '%s' format argument is supported.

argument

Is a varchar output parameter that will return the value of the corresponding format argument. Up to 50 arguments can be specified.

Example

In this example, the @@filename parameter will contain the value authors10.tmp.

DECLARE @@filename varchar (255)

EXEC xp_sscanf 'sync -b -fauthors10.tmp', 'sync -b -f%s',

@@argument1=@@filename OUTPUT

Permission

Execute permission defaults to the public group.

See Also

xp_sprintf


xp_startmail Extended Stored Procedure

Starts a SQL Server mail client session.

Syntax

xp_startmail ['user'] [, 'password']

where

user

Is an optional parameter specifying a mail username.

password

Is the mail password for the named user. NULL is allowed when the mail client is started (on the same computer) before running xp_startmail.

Remarks

If user and password are provided, 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 no user or password are provided, SQL Server uses the username and password specified in SQL Setup, using the Mail Login dialog box under Server Options.

If there is an existing mail session, xp_startmail will 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 before xp_startmail is used or before SQL Server (if using the Set Server Options "Auto Start Mail Client" option found in SQL Setup). For more information, see the Microsoft SQL Server Administrator's Companion.

Examples

A.	No Variables with xp_startmail

This example starts mail using the username and password specified in SQL Setup.

xp_startmail

B.	Variables with xp_startmail

This example starts mail using the username mailuser and the password abc12345.

xp_startmail 'mailuser', 'abc12345'

Permission

Execute permission defaults to the system administrator, who can grant permission to other users.

See Also

sp_processmail	xp_readmail
xp_deletemail	xp_sendmail
xp_findnextmsg	xp_stopmail


xp_stopmail Extended Stored Procedure

Stops a SQL Server mail client session.

Syntax

xp_stopmail

Remarks

If there is no existing SQL Server mail session to stop, a message is returned.

Permission

Execute permission defaults to the system administrator, who can grant permission to other users.

See Also

sp_processmail	xp_readmail
xp_deletemail	xp_sendmail
xp_findnextmsg	xp_startmail


Stored Procedures-Replication Stored Procedures

This section describes the stored procedures used by replication to implement and initiate replication on a SQL Server 6.0 server. Replication uses stored procedures to perform:

•	Server configuration

•	Publication administration tasks

•	Subscription administration tasks

•	Replication operations

•	Replicated transaction management

•	Scheduling

Stored Procedures Used for Server Configuration

These are the stored procedures used by replication for server configuration:

sp_addpublisher	sp_dropsubscriber
sp_addsubscriber	sp_helpdistributor
sp_changesubscriber	sp_helpserver
sp_dboption	sp_helpsubscriberinfo
sp_droppublisher	sp_replsync
Stored Procedures Used for Publication Administration

These are the stored procedures used by replication for publication administration tasks:

sp_addarticle	sp_helparticle
sp_addpublication	sp_helparticlecolumns
sp_articlecolumn	sp_helppublication
sp_changearticle	sp_helppublicationsync
sp_changepublication	sp_helpreplicationdb
sp_droparticle	sp_replflush
sp_droppublication	sp_replstatus
sp_enumfullsubscribers
Stored Procedures Used for Subscription Administration

These are the stored procedures used by replication for subscription administration tasks:

sp_addsubscription	sp_helpsubscription
sp_changesubscription	sp_subscribe
sp_changesubstatus	sp_unsubscribe
sp_dropsubscription	sp_helpreplicationdb
Stored Procedures Used for Replication Operations

These are the stored procedures used for replication operations:

sp_distcounters	sp_replica
sp_replcleanup	sp_replsync
Stored Procedures Used for Replicated Transaction Management

These are the extended stored procedures used to manage and return information about replicated transactions:

sp_MSkill_job	sp_repldone
sp_replcmds	sp_repltrans
sp_replcounters
Stored Procedures Used for Replication Scheduling

These are the stored procedures used for scheduling of replication tasks in the msdb database:

sp_addtask	sp_helptask
sp_droptask
For details, see the SQL Executive stored procedures.


sp_addarticle Replication Stored Procedure

Creates an article and adds it to a publication.

Syntax

sp_addarticle publication,  article,  source_table [, destination_table]
[, vertical_partition] [, type] [, filter] [, sync_object] [, ins_cmd]
[, del_cmd] [, upd_cmd] [, creation_script] [, description]
[, pre_creation_cmd] [, filter_clause]

where

publication

Specifies the name of the publication that will contain the article. This name must be unique in the database.

article

Is the article's name. The name must be unique within the publication.

source_table

Specifies the name of the underlying table represented by the article.

destination_table

Is the name of the destination (subscription) table, if different from source_table.

vertical_partition

Determines the vertical position. If set to false, indicates there is no vertical partition, will publish all columns. If set to true, clears all columns except the declared primary key. Columns are added using the sp_articlecolumn replication stored procedure.

type

Specifies the type of article. Can be:
1  Log-based article (the default)
3  Log-based article with manual filter
5  Log based article with manual view
7  Log-based article with manual filter and manual view

filter

Specifies the stored procedure (created with FOR REPLICATION) used to filter the table (horizontal partition). The default is NULL, which means that sp_articlefilter will be called to automatically generate the filter. This occurs after adding any columns with sp_articlecolumn. If not NULL, the filter procedure will not be created (assumes manual stored procedure creation).

sync_object

Is the name of the table or view used for producing a synchronization output file. The default is NULL, which means that sp_articleview will be called to automatically create the view that will synchronize the output file. This occurs after adding any columns with sp_articlecolumn. If not NULL, a view will not be created (assumes manual view creation).

ins_cmd

Specifies the command to execute upon insert; otherwise, the insert is constructed from the log. The default is SQL.

del_cmd

Specifies the command to execute upon delete; otherwise, the delete is constructed from the log. The default is SQL.

upd_cmd

Specifies command to execute upon update; otherwise, the update is constructed from the log. The default is SQL.

creation_script

Is the path and name of an article schema script used to create target tables. The default is NULL.

description

Is an optional descriptive entry for the article.

pre-creation_cmd

Is a pre-creation command for drop table, delete table, or truncate. Can be:

0  None
1  Drop (the default)
2  Delete
3  Truncate

filter_clause

Is a WHERE clause specifying the horizontal partitioning.

Remarks

If vertical_partition is false and filter_clause is not NULL, a view is created and a filter procedure on the source table using the filter_clause is created. 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).

Example

This example creates the article authors and adds it to the authors_publication publication.

sp_addarticle authors_publication, authors, authors,
@@creation_script='c:\sql95\repldata\authors.sch'
@@description='Authors Table Article'

Permission

Execute permission defaults to the database owner and the system administrator.

Tables Used

sysobjects, sysarticles, syspublications

See Also

sp_addpublication	sp_droparticle
sp_articlecolumn	sp_droppublication
sp_articlefilter	sp_enumfullsubscribers
sp_articlecolumn	sp_helparticle
sp_changearticle	sp_helparticlecolumns
sp_changepublication	sp_helppublication


sp_addpublication Replication Stored Procedure

Creates a publication.

Syntax

sp_addpublication publication, taskid,
[, @@restricted = {'true' | 'false'}
[, @@sync_method = {'native' | 'character'}
[, @@repl_freq = {'continuous' | 'snapshot'}
[, @@description = 'string description'
[, @@status= {'inactive' | 'active'}]]]]]

where

publication

Names the publication to create. The name must be unique within the database.

taskid

Is a unique scheduler task ID (must be created before the publication).

restricted

Specifies who can view the publication. If set to false (the default), the publication can be viewed by all (open enrollment). If set to true, the publication can be viewed only by authorized subscription servers.

sync_method

Specifies the synchronization mode. If set to native (the default), produces native-mode BCP output of all tables. If set to character, produces character-mode BCP output of all tables.

repl_freq

Specifies that if set to continuous (the default), the publisher provides output of all log-based transactions. If set to snapshot, the publisher produces only scheduled synchronization events.

description

Is an optional descriptive entry for the publication job.

status

Specifies when publication data will be available. If set to inactive (the default), publication data will not be available for subscribers when the publication is first created (they can subscribe, but the subscription will not be processed). If set to active, publication data will immediately be available for subscribers.

Remarks

Only the system administrator or the database owner can add a publication.

Example

This example creates the publication authors_publication, using a preexisting sync task with taskid equal to 1.

sp_addpublication authors_publication, 1, @@status=active,
@@description='Full Authors Table'

Permission

Execute permission defaults to the database owner and the system administrator.

Tables Used

syspublications, sysdatabases

See Also

sp_addarticle	sp_droppublication
sp_articlecolumn	sp_enumfullsubscribers
sp_changearticle	sp_helparticle
sp_changepublication	sp_helparticlecolumns
sp_droparticle	sp_helppublication


sp_addpublisher Replication Stored Procedure

Adds a new publication server.

Syntax

sp_addpublisher publisher [, 'dist']

where

publisher

Is the name of the server to be added.

dist

Defines the specified server as a potential publisher to this distribution server. This is true if the local server is set up with a distribution database. (Sets the server option to dpub, and adds a remote login mapping of SA to SA with the trusted option.)

Remarks

If 'dist' is not specified the publisher's distributor (SQL Executive) user account will be granted repl privilege. Only the system administrator can add a server to master.sysservers as a publication server.

Example

This example adds the publication server WOLFHOUND and defines it as a potential publisher.

sp_addpublisher WOLFHOUND, 'dist'

Permission

Execute permission defaults to the system administrator.

Table Used

sysservers

See Also

sp_addremotelogin	sp_dropsubscriber
sp_addserver	sp_helpdistributor
sp_addsubscriber	sp_helpserver
sp_changesubscriber	sp_helpsubscriberinfo
sp_dboption	sp_remoteoption
sp_droppublisher	sp_serveroption


sp_addsubscriber Replication Stored Procedure

For more updated SQL Server 6.5 syntax, see sp_addsubscriber.

Adds a new subscription server and sets up a trusted remote login mapping from SA of the subscriber to the repl_subscriber login ID on the publisher (unless system administrator on the subscriber is already mapped to system administrator on the publisher).

Syntax

sp_addsubscriber subscriber [, type] [, login] [, password] [, commit_batch_size]
[, status_batch_size] [, flush_frequency] [, frequency_type]
[, frequency_interval] [, frequency_relative_interval]
[, frequency_recurrence_factor] [, frequency_subday]
[, frequency_subday_interval] [, active_start_time_of_day]
[, active_end_time_of_day] [, active_start_date] [, active_end_date]

where

subscriber

Specifies the name of the server to be added as a valid subscriber to this server's publications.

type

Specifies the type of subscription server: 0 indicates a SQL Server 6.0 subscription server; 1 indicates a non−SQL Server 6.0 or other ODBC data source server. The default is 0.

login

Is reserved for future use.

password

Is reserved for future use.

commit_batch_size

Specifies the maximum number of transactions that will be sent to the subscription server as a single unit. The default is 20.

status_batch_size

Is reserved for future use.

flush_frequency

Specifies the frequency with which transactions will be removed from the distribution database tables after they have been successfully distributed to the subscriber's database. The default is 0.

frequency_type

Specifies the frequency with which to schedule the distribution task. The default is 4 (daily). The value can be:
1	One Time
2	On Demand
4	Daily
8	Weekly
16	Monthly
32	Monthly Relative
64	Autostart
124	Recurring

frequency_interval

Is the value to apply to the frequency set by frequency_type. The default is 1.

frequency_relative_interval

Specifies the date of the distribution task. Used when frequency_type is set to 32 (monthly relative). The default is 1. The value can be:

1	First
2	Second
4	Third
8	Fourth
16	Last

frequency_recurrence_factor

Is the recurrence factor used by frequency_type. The default is 0.

frequency_subday

Specifies how often to reschedule during the defined period. The default is 4 (minute).
1	Once (default)
2	Second
4	Minute
8	Hour

frequency_subday_interval

Is the interval for frequency_subday. The default is 5.

active_start_time_of_day

Specifies when the distribution task will first be scheduled. Formatted as HHMMSS. The default is 0.

active_end_time_of_day

Specifies when the distribution task will stop being scheduled. Formatted as HHMMSS. The default is 235939.

active_start_date

Specifies the date when the distribution task will first be scheduled. Formatted as YYYYMMDD. The default is 0.

active_end_date

Specifies the date when the distribution task will stop being scheduled. Formatted as YYYYMMDD. The default is 99991231.

Remarks

This stored procedure writes to the MSsubscriber_info table in the distribution database.

Example

This example sets up BLOODHOUND as a subscription server.

sp_addsubscriber BLOODHOUND

Permission

Execute permission defaults to the system administrator.

Tables Used

sysservers, sysremotelogins

See Also

sp_addpublisher	sp_dropsubscriber
sp_addremotelogin	sp_helpdistributor
sp_addserver	sp_helpserver
sp_changesubscriber	sp_helpsubscriberinfo
sp_dboption	sp_remoteoption
sp_droppublisher	sp_serveroption


sp_addsubscription Replication Stored Procedure

For more updated SQL Server 6.5 syntax, see sp_addsubscription.

Adds a subscription to an article and sets the subscriber's status.

Syntax

sp_addsubscription publication [, 'article'] , subscriber [, destination_db]
[, @sync_type = {'automatic' | 'manual' | 'none'}]
[, @status = {'inactive' | 'active' | 'subscribed'}]

where

publication

Specifies the name of the publication.

article

Specifies the article that will be subscribed to. The article name must be unique within the publication. If set to all or not supplied, a subscription is added to all articles in that publication.

subscriber

Is the name of the subscription server subscribing to this article.

destination_db

Is the name of the destination database in which to place replicated data. The default uses the same name as the publication database.

@sync_type

Is the subscription synchronization type. When set to automatic (the default), synchronization is applied to the subscription server via the distribution process. When set to manual, a synchronization file is automatically produced, but it must be manually applied to the subscription server. This parameter can also be set to none (no initial synchronization).

@status

Is the subscription status. If sync_type = none, the default for status is active; otherwise the default is subscribed. To enable a subscriber to see articles in a restricted publication article, a "placeholder" subscription must be created with inactive status.

Remarks

Only the system administrator or database owner can locally add a subscription to an existing article.

Example

This example adds the subscriber AIREDALE to the article authors in the publication authors_publication.

sp_addsubscription authors_publication, authors, AIREDALE

Permission

Execute permission defaults to the system administrator and database owner.

Tables Used

sysarticles, syspublications, syssubscriptions, sysservers

See Also

sp_changesubscription	sp_helpsubscription
sp_changesubstatus	sp_subscribe
sp_dropsubscription	sp_unsubscribe


sp_articlecolumn Replication Stored Procedure

Modifies columns for an article. Use sp_articlecolumn to create vertical partitions.

Syntax

sp_articlecolumn publication, article [, 'column'
[, @operation = {'add' | 'drop'}]]

where

publication

Is the name of the publication that contains this article.

article

Is the name of the article.

column

Is the name of the column to be added or dropped. The default is NULL. If NULL, all columns are published.

@operation

Specifies the replication status; add (the default) marks the column for replication; drop unmarks the column.

Remarks

This stored procedure sets a bit in sysarticles. Only an unsubscribed article can be partitioned using sp_articlecolumn.

Example

This example modifies the column col5, marking it for replication.

sp_articlecolumn PUB_TEST, ART_ALLS, 'col5', 'add'

Permission

Execute permission defaults to the system administrator and database owner.

Tables Used

syscolumns, sysarticles, syspublications, sysdatabases

See Also

sp_addarticle	sp_droppublication
sp_addpublication	sp_enumfullsubscribers
sp_articleview	sp_helparticle
sp_changearticle	sp_helparticlecolumns
sp_changepublication	sp_helppublication
sp_droparticle


sp_articlefilter Replication Stored Procedure

Creates a filter stored procedure used to horizontally partition data replicated from a published table.

Syntax

sp_articlefilter publication, article [, filter_name] [, filter_clause]

where

publication

Is the name of the publication that contains the article.

article

Is the name of the article.

filter_name

Is the name of the filter stored procedure to be created from the filter_clause.

filter_clause

Is a restriction (WHERE) clause that defines a horizontal partition. When entering the restriction clause, omit the word "WHERE."

Remarks

This stored procedure creates the filter and inserts the ID of the filter stored procedure in the filter column of the sysarticles table, and it inserts the text of the restriction clause in the filter_clause column.

Only unsubscribed articles can be modified by this stored procedure.

To create an article with a horizontal partition, 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) or 3 (log-based article with manual filter), the filter will be dropped and re-created.

If filter_name and filter_clause are not provided, the previous filter is deleted and the filter ID is set to 0.

Example

This example creates the mypub filtered stored procedure.

sp_articlefilter, MyPub, MyArticle, MyFilter, 'state = "OR"'

Permission

Only the system administrator and the database owner can use this stored procedure.

Tables Used

sysobjects, syspublications, syssubscriptions, sysarticles

See Also

sp_addarticle	sp_articleview
sp_articlecolumn


sp_articleview Replication Stored Procedure

Creates the synchronization object for an article when a table is filtered vertically and/or horizontally. This synchronization object is a view that is used as the filtered source of the schema and data for the destination tables.

Syntax

sp_articleview publication, article [, view_name] [, filter_clause]

where

publication

Is the name of the publication that contains the article.

article

Is the name of the article.

view_name

Is the name of the synchronization object.

filter_clause

Is a restriction (WHERE) clause that defines a horizontal partition. When entering the restriction clause, omit the word "WHERE."

Remarks

This stored procedure 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.

Only unsubscribed articles can be modified by this stored procedure.

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 will drop the existing view and create a new one if the type in sysarticles is 1 (log-based article) or 3 (log-based article with manual filter).

If you manually create a custom filter stored procedure and a synchronization object, do not run sp_articleview. Instead, provide them as the filter and sync_object parameters to sp_addarticle, along with the appropriate type value.

Example

This example creates the synchronization view MyView for MyPub and filters on the zip code 94609.

sp_articleview 'MyPub', 'MyArticle', 'MyView', 'zip = "94609"'

Permission

Only the system administrator or the database owner can use this stored procedure.

Tables Used

sysobjects, syscolumns, syspublications, syssubscriptions, sysarticles

See Also

sp_addarticle	sp_articlefilter
sp_articlecolumn


sp_changearticle Replication Stored Procedure

Changes an article's properties.

Syntax

sp_changearticle publication, article [, property, value]

where

publication

Is the name of the publication that contains the article.

article

Is the name of the article whose property is to be changed.

property

States an article property to change. Can be:

name
description
sync_object
type
ins_cmd
del_cmd
upd_cmd
filter
dest_table
creation_script
pre_creation_cmd

value

Specifies the article value. Can be used with:

name

Is the new name for the article.

description

Is a descriptive entry for the publication job.

sync_object

Is the name of the table or view used to produce a synchronization output file. The default is NULL.

type

Is the article type:
1	Log-based article (the default)
3	Log-based article with manual filter
5	Log-based article with manual view
7	Log-based article with manual filter and manual view

ins_cmd

Is the INSERT statement to execute; otherwise, it will be constructed from the log.

del_cmd

Is the DELETE statement to execute; otherwise, it will be constructed from the log.

upd_cmd

Is the UPDATE statement to execute; otherwise, it will be constructed from the log.

filter

Specifies a stored procedure used to the filter the table (horizontal partition). The default is NULL.

dest_table

Is the destination table, if different from the source table (source_table).

creation_script

Is the path and name of an article schema script used to create target tables. The default is NULL.

pre_creation_cmd

Specifies a pre-creation command that can drop, delete, or truncate the destination table before synchronization is applied. Can be:

None
Drop
Delete
Truncate

Remarks

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. Only the system administrator and the database owner can change an article.

Example

This example renames the ART_ALL article to ART_NEW.

sp_changearticle PUB1, ART_ALL, name, 'ART_NEW'

Permission

Execute permission defaults to the system administrator and the database owner.

Tables Used

sysobjects, sysarticles, syspublications, sysdatabases

See Also

sp_addarticle	sp_droppublication
sp_addpublication	sp_enumfullsubscribers
sp_articlecolumn	sp_helparticle
sp_changepublication	sp_helparticlecolumns
sp_droparticle	sp_helppublication


sp_changepublication Replication Stored Procedure

Changes a publication's properties.

Syntax

sp_changepublication publication [, property, 'value']

where

publication

Is the name of the publication.

property

Specifies the publication property to change. Can be name, description, taskid, sync_method, status, repl_freq, or restricted.

value

Specifies the publication value. Can be used with:

name

Is the new publication name.

description

Is an optional entry describing the publication.

taskid

Is a unique scheduler task ID created using the sp_addtask stored procedure.

sync_method

Specifies the 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).

status

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

Specifies the frequency of replication. Can be continuous (provides output of all log-based transactions) or snapshot (produces only scheduled synchronization events).

restricted

Specifies access to the publication. Can be false (the publication allows open enrollment and is visible to all) or true (the publication can be viewed only by authorized subscription servers).

Example

This example changes the name of the publication authors_publication to au_pub.

sp_changepublication authors_publication, name, 'au_pub'

Permission

Execute permission defaults to the system administrator and the database owner.

Tables Used

syspublications, sysdatabases

See Also

sp_addarticle	sp_droppublication
sp_addpublication	sp_enumfullsubscribers
sp_articlecolumn	sp_helparticle
sp_changearticle	sp_helparticlecolumns
sp_droparticle	sp_helppublication


sp_changesubscriber Replication Stored Procedure

For more updated SQL Server 6.5 syntax, see sp_changesubscriber.

Changes the options for a subscription server. Any distribution task for the publisher's subscribers will be updated.

Syntax

sp_changesubscriber subscriber [, type] [, login] [, password]
[, commit_batch_size] [, status_batch_size] [, flush_frequency]
[, frequency_type] [, frequency_interval] [, frequency_relative_interval]
[, frequency_recurrence_factor] [, frequency_subday]
[, frequency_subday_interval] [, active_start_time_of_day]
[, active_end_time_of_day] [, active_start_date] [, active_end_date]

where

subscriber

Is the name of the subscription server that will have its options changed.

type

Specifies the subscription server type; 0 indicates a SQL Server 6.0 subscription server; 1 indicates a non−SQL Server 6.0 or other ODBC data source server. The default is 0.

login

Is reserved for future use.

password

Is reserved for future use.

commit_batch_size

Specifies the maximum number of transactions that will be sent to the subscription server as a single unit.

status_batch_size

Is reserved for future use.

flush_frequency

Specifies the frequency with which transactions will be removed from the distribution database tables after they have been successfully distributed to the subscriber's database.

frequency_type

Specifies the frequency with which to schedule the distribution task:
1	One Time
2	On Demand
4	Daily
8	Weekly
16	Monthly
32	Monthly Relative
64	Autostart
128	Recurring

frequency_interval

Specifies the interval for frequency_type.

frequency_relative_interval

Specifies the date of the distribution task. Used when frequency_type is set to 32 (monthly relative). The default is 1. The value can be:

1	First (default)
2	Second
4	Third
8	Fourth
16	Last

frequency_recurrence_factor

Specifies how often the distribution task should re-occur during the defined frequency_type.

frequency_subday

Specifies how often to reschedule during the defined period:
1	Once (default)
2	Second
4	Minute
8	Hour

frequency_subday_interval

Specifies the interval for frequency_subday.

active_start_time_of_day

Specifies when the distribution task will first be scheduled. Formatted as HHMMSS. The default is 0.

active_end_time_of_day

Specifies when the distribution task will stop being scheduled. Formatted as HHMMSS. The default is 0.

active_start_date

Specifies the date when the distribution task will be scheduled initially. Formatted as YYYYMMDD. The default is 0.

active_end_date

Specifies the date when the distribution task will stop being scheduled. Formatted as YYYYMMDD. Default is 0.

Remarks

Only the system administrator can change a subscription server. This stored procedure writes to the MSsubscriber_info table in the distribution database.

Example

This example changes the BLOODHOUND subscriber's frequency from daily (the default) to weekly.

sp_changesubscriber BLOODHOUND, @frequency_type = 8

Permission

Execute permission defaults to the system administrator.

Table Used

sysservers

See Also

sp_addpublisher	sp_dropsubscriber
sp_addsubscriber	sp_helpdistributor
sp_dboption	sp_helpserver
sp_droppublisher	sp_helpsubscriberinfo


sp_changesubscription Replication Stored Procedure

Changes the subscription properties for an article or a publication. Is executed on a subscription server.

Syntax

sp_changesubscription publication, article, subscriber [, 'property', 'value']

where

publication

Is the name of the publication containing the article.

article

Is the name of the article.

subscriber

Is the name of the subscription server. If subscriber is not specified, defaults to @@REMSERVER (the server name contained within a remote server's login record).

property

Is the property to set. Can be sync_type or dest_db.

value

Is the value of property. For sync_type, can be none, manual, or automatic. For dest_db, is the name of a destination database.

Example

This example changes the subscription property of the myart3 article to a synchronization type of manual.

sp_changesubscription mypub1, myart3, sync_type, manual

Permission

Execute permission defaults to the system administrator and the database owner.

Tables Used

sysarticles, syspublications, syssubscriptions, sysservers

See Also

sp_addsubscription	sp_helpsubscription
sp_changesubstatus	sp_subscribe
sp_dropsubscription	sp_unsubscribe


sp_changesubstatus Replication Stored Procedure

Changes the status of an existing subscriber.

Syntax

sp_changesubstatus [publication [, article [, subscriber [, ]]]]
status [, previous_status]

where

publication

Is the name of the publication. If publication is not specified, all publications are affected.

article

Is the name of the article. It must be unique to the publication. If article is not specified, all articles are affected.

subscriber

Is the name of the subscription server that is to have its status changed. If no subscriber is specified, status is changed for all subscribers to the specified article.

status

Is the subscription status in the syssubscriptions table. Can be:

inactive	Subscriber entry exists without a subscription, which is used for restricted publications.
subscribed	Subscriber is requesting data but is not yet synchronized.
active	Subscriber is synchronized and receiving data.
previous_status

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.) Normally, is NULL.

Remarks

This stored procedure 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.

Example

This example changes the status of the subscriber POODLE to inactive (entry exits without subscription).

sp_changesubstatus mypub1, myart3, POODLE, inactive

Permission

Execute permission defaults to the system administrator and the database owner.

Tables Used

sysobjects, sysarticles, syspublications, syssubscriptions, sysservers

See Also

sp_addsubscription	sp_helpsubscription
sp_changesubscription	sp_subscribe
sp_dropsubscription	sp_unsubscribe
sp_helpdistributor


sp_distcounters Replication Stored Procedure

Displays the latest information for all subscription servers. Used by SQL Performance Monitor.

Syntax

sp_distcounters

Remarks

This stored procedure returns the subscription server name, the number of delivered jobs, the number of undelivered jobs, the delivery rate (number of jobs per second), and the delivery latency (in seconds).

A delivered job is one that is still in the distribution database but has already been executed against the destination database. An undelivered job is one that is currently in the distribution database but has not yet been executed against the destination database. The delivery rate is the number of jobs per second that were executed in the last batch sent to that subscription server. Latency refers to the amount of time that elapses from when a job is inserted into the distribution database to when it is executed against the subscriber.

This information can be viewed by using the appropriate counters in SQL Performance Monitor.

Example

This example displays the current status for the BLOODHOUND subscription server. Note "deliv" is short for delivered in this output.

sp_distcounters

go

subscriber  deliv_jobs  undeliv_jobs  delivery_rate  delivery_latency

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

BLOODHOUND  0  	         0             6              1

Permission

Execute permission defaults to the system administrator and is granted to public.

Table Used

None.

See Also

sp_replsync	sp_replica
sp_replcleanup


sp_droparticle Replication Stored Procedure

Drops an article.

Syntax

sp_droparticle publication, article

where

publication

Is the name of the publication that contains the article to be dropped.

article

Is the name of the article to be dropped.

Remarks

An article cannot be removed if one or more subscriptions to it exist. Only the system administrator or the database owner can drop an article.

This stored procedure 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.

Example

This example drops the article myarticle5 from the publication mypub.

sp_droparticle mypub, myarticle5

Permission

Execute permission defaults to the system administrator and the database owner.

Tables Used

sysobject, sysarticles, syspublications, syssubscriptions

See Also

sp_addarticle	sp_droppublication
sp_addpublication	sp_enumfullsubscribers
sp_articlecolumn	sp_helparticle
sp_changearticle	sp_helparticlecolumns
sp_changepublication	sp_helppublication


sp_droppublication Replication Stored Procedure

Drops a publication and its associated articles.

Syntax

sp_droppublication publication

where

publication

Is the name of the publication to be dropped. If all is specified, all publications are dropped from the publication database, except for those with subscriptions.

Remarks

This stored procedure 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 will also be dropped. Only the system administrator or the database owner can drop a publication.

Example

This example drops the mypub3 publication.

sp_droppublication mypub3

Permission

Execute permission defaults to the system administrator and the database owner.

Tables Used

sysarticles, syspublications, syssubscriptions

See Also

sp_addarticle	sp_droparticle
sp_addpublication	sp_enumfullsubscribers
sp_articlecolumn	sp_helparticle
sp_changearticle	sp_helparticlecolumns
sp_changepublication	sp_helppublication


sp_droppublisher Replication Stored Procedure

Drops a publication server.

Syntax

sp_droppublisher publisher [, dist]

where

publisher

Is the name of the publication server to be dropped.

dist

Drops the server as the distribution server. (Removes the server option dpub, and removes the remote login mapping of SA to SA with the trusted option.)

Remarks

Only the system administrator can drop a publication server. If dist is not provided, the publisher's subscriber (SQL Executive) Windows NT user account has its replication privilege revoked.

Example

The example drops the WOLFHOUND publication server entry.

sp_droppublisher WOLFHOUND

Permission

Execute permission defaults to the system administrator.

Table Used

sysservers

See Also

sp_addpublisher	sp_dropsubscriber
sp_addsubscriber	sp_helpdistributor
sp_changesubscriber	sp_helpserver
sp_dboption	sp_helpsubscriberinfo


sp_dropsubscriber Replication Stored Procedure

Drops a subscription server.

Syntax

sp_dropsubscriber subscriber

where

subscriber

Is the name of the subscription server to be dropped.

Remarks

This stored procedure removes the server sub option and removes the remote login mapping of SA to repl_subscriber. Only the system administrator can drop a subscription server.

Example

This example drops the subscription server BLOODHOUND.

sp_dropsubscriber BLOODHOUND

Permission

Execute permission defaults to the system administrator.

Tables Used

sysservers, sysremotelogins

See Also

sp_addpublisher	sp_droppublisher
sp_addsubscriber	sp_helpdistributor
sp_changesubscriber	sp_helpserver
sp_dboption	sp_helpsubscriberinfo


sp_dropsubscription Replication Stored Procedure

Drops subscriptions to a particular article, publication, or set of subscriptions on the publication server.

Syntax

sp_dropsubscription 'publication', 'article', 'subscriber'

where

publication

Is the name of the associated publication. Specifying all cancels all subscriptions for all publications for the specified subscriber.

article

Is the name of the article. Specifying all drops subscriptions to all articles for each specified publication and subscriber. If article is not supplied, subscriptions are dropped for all articles in the publication.

subscriber

Is the name of the subscription server that will have its subscriptions dropped. Specifying all drops all subscriptions for all subscribers.

Remarks

Only the system administrator, database owner, and a remote connection from the subscription server can drop a subscription to an existing publication or article.

Examples

This example drops all articles from all publications and drops all subscriptions for all subscribers.

sp_dropsubscription 'all', 'all', 'all'

Permission

Execute permission defaults to the system administrator and database owner.

Tables Used

sysarticles, syspublications, syssubscriptions, sysservers

See Also

sp_addsubscription	sp_helpsubscription
sp_changesubscription	sp_subscribe
sp_changesubstatus	sp_unsubscribe


sp_enumfullsubscribers Replication Stored Procedure

Returns a list of subscribers who have subscribed to all articles in a specified publication.

Syntax

sp_enumfullsubscribers publication

where

publication

Is the name of the publication.

Example

This example returns a list of all subscribers who have subscribed to all articles in the publication pub3.

sp_enumfullsubscribers pub3

Permission

Execute permission defaults to the system administrator and the database owner.

Tables Used

sysarticles, syspublications, syssubscriptions, sysservers

See Also

sp_addarticle	sp_droparticle
sp_addpublication	sp_droppublication
sp_articlecolumn	sp_helparticle
sp_changearticle	sp_helparticlecolumns
sp_changepublication	sp_helppublication


sp_helparticle Replication Stored Procedure

Displays information about an article.

Syntax

sp_helparticle publication[, article] [, returnfilter]

where

publication

Is the name of the publication.

article

Is the name of an article in the publication. If article is not supplied, information on all articles for the specified publication is returned.

returnfilter

Specifies if the filter clause should be returned. Is 1 if the filter clause should be returned, 0 if not. The default is 1.

Remarks

Displays the article name, base table name, destination table, synchronization object, type, status, filter, description, insert command, update command, delete command, creation script path, and (depending on the returnfilter parameter) filter clause.

Example

This example returns information about the types_table article in the pub_alltypes publication. The filter clause will be returned.

sp_helparticle pub_alltypes, types_table

Permission

Execute permission defaults to the public group.

Table Used

sysobjects, syscolumns, sysusers, sysarticles, syspublications, syssubscriptions, sysservers

See Also

sp_addarticle	sp_droparticle
sp_addpublication	sp_droppublication
sp_articlecolumn	sp_enumfullsubscribers
sp_changearticle	sp_helparticlecolumns
sp_changepublication	sp_helppublication


sp_helparticlecolumns Replication Stored Procedure

Displays all columns in the underlying table.

Syntax

sp_helparticlecolumns publication, article

where

publication

Is the name of the publication that contains the article.

article

Is the name of the article that will have its columns displayed.

Remarks

This stored procedure returns 1 for columns that are published and 0 for those that are not published. It is useful in checking a vertical partition.

Example

This example displays the columns of the authors article in the authors_publication publication.

sp_helparticlecolumns authors_publication, authors

Permission

Execute permission defaults to the public group.

Tables Used

syscolumns, sysarticles, syspublications, syssubscriptions, sysservers

See Also

sp_addarticle	sp_droparticle
sp_addpublication	sp_droppublication
sp_articlecolumn	sp_enumfullsubscribers
sp_changearticle	sp_helparticle
sp_changepublication	sp_helppublication


sp_helpdistributor Replication Stored Procedure

Lists information about the distribution server, distribution database, working directory, and SQL Executive user account.

Syntax

sp_helpdistributor

Remarks

This stored procedure returns the name of the server's distribution server, the distribution database, the path of the distribution working directory, and the name of the Windows NT user account that the distribution process runs under. If the distribution database is not installed, a null value is returned.

Example

This example displays distribution information.

sp_helpdistributor

Permission

Execute permission defaults to the public group.

Table Used

sysservers

See Also

sp_addpublisher	sp_droppublisher
sp_addsubscriber	sp_dropsubscriber
sp_changesubscriber	sp_helpserver
sp_changesubstatus	sp_helpsubscriberinfo
sp_dboption


sp_helppublication Replication Stored Procedure

Displays information about a publication.

Syntax

sp_helppublication [publication]

where

publication

Is the name of the publication to be viewed.

Remarks

This stored procedure displays the publication ID, the name, whether the publication is unrestricted/restricted, the status, the SQL Executive task ID, the replication frequency, the synchronization method, and a description. If publication is not provided, information on all publications is returned.

Example

This example displays information about the mypub5 publication.

sp_helppublication mypub5

Permission

Execute permission defaults to the public group.

Tables Used

sysarticles, syspublications, syssubscriptions, sysservers

See Also

sp_addarticle	sp_droparticle
sp_addpublication	sp_droppublication
sp_articlecolumn	sp_enumfullsubscribers
sp_changearticle	sp_helparticle
sp_changepublication	sp_helparticlecolumns


sp_helppublicationsync Replication Stored Procedure

Provides information about a scheduled synchronization task for a publication.

Syntax

sp_helppublicationsync publication

where

publication

Is the publication name.

Remarks

Using this stored procedure is the equivalent to running the sp_helptask stored procedures in full mode against the publication task ID.

It returns the information as supplied when the synchronization task was defined. For more information, see the ,sp_addtask SQL Executive Stored Procedure.

Example

This example displays information about the scheduled synchronization task for the mypub publication.

sp_helppublicationsync mypub

Permission

Execute permission defaults to the public group.

See Also

sp_addtask


sp_helpreplicationdb Replication Stored Procedure

Returns information about a specified database or a list of all publication databases on the server.

Syntax

sp_helpreplicationdb [databasename [, {pub | sub}]]

where

databasename

Is the name of the database about which information will be returned. Wildcard characters can be used; % is the default.

pub | sub

Determines what information will be returned. When pub (the default) is specified, checks whether the specified database is a publication database. When sub is specified, checks whether the specified database is a subscription (destination) database.

Remarks

If run without options, this stored procedure returns a list of all published databases on the server. If run with options, it returns the databasename only if that database is set for publishing (when the pub option is supplied) or subscribing (when the sub option is supplied).

Example

This example returns information about the inventory database and indicates if it is a subscription database.

sp_helpreplicationdb inventory, sub

Permission

Execute permission defaults to the public group.

Table Used

sysdatabases

See Also

sp_helppublication


sp_helpsubscriberinfo Replication Stored Procedure

For more updated SQL Server 6.5 syntax, see sp_helpsubscriberinfo in the "What's New for SQL Server 6.5".

Displays information about a subscription server.

Syntax

sp_helpsubscriberinfo subscriber

where

subscriber

Is the name of the subscription server.

Remarks

This stored procedure displays information about the parameters set by sp_addsubscriber.

Example

This example displays information about the subscription server WOLFHOUND.

sp_helpsubscriberinfo WOLFHOUND

Permission

Execute permission defaults to the system administrator.

Table Used

sysservers

See Also

sp_addpublisher	sp_droppublisher
sp_addsubscriber	sp_dropsubscriber
sp_changesubscriber	sp_helpdistributor
sp_dboption	sp_helpserver


sp_helpsubscription Replication Stored Procedure

Lists subscription information associated with a particular publication, article, subscriber, or set of subscriptions.

Syntax

sp_helpsubscription [publication [, article [, subscriber ]]]

where

publication

Is the name of the associated publication. If publication is not given, returns all subscription information for this server.

article

Is the name of the article. If article is not given, returns all subscription information for selected publications and subscribers.

subscriber

Specifies the subscription server that will view subscriptions. If subscriber is not provided, returns all subscription information for selected publications and articles.

Remarks

This stored procedure returns subscriber, publication, article, destination database, subscription status, and synchronization type.

Example

This example returns all subscription information about the publication authors_publication and the article authors.

sp_helpsubscription authors_publication, authors

Permission

Execute permission defaults to the public group.

Tables Used

sysarticles, syspublications, syssubscriptions, sysservers

See Also

sp_addsubscription	sp_dropsubscription
sp_changesubscription	sp_subscribe
sp_changesubstatus	sp_unsubscribe


sp_MSkill_job Replication Stored Procedure

Removes a single job from the distribution database while continuing to send all other data to the subscriber. Used on the distribution server.

Syntax

sp_MSkill_job job_id, publisher, publisher_db [, subscriber [, subscriber_db]]

where

job_id

Is the ID of the job being removed.

publisher

Is the name of the publication server where the job originated.

publisher_db

Is the name of the published database.

subscriber

Is the name of the subscription server.

subscriber_db

Is the name of the destination database.

Remarks

The sp_MSkill_job replication stored procedure is useful if all subscribers are failing on the distribution of a replicated transaction.

Important  Use this procedure with caution. It is used on the distribution database.

Example

This example terminates job 90 that is waiting to be distributed.

sp_MSkill_job 90, WOLFHOUND, pubs

See Also

MSlast_job_info


sp_replcleanup Replication Stored Procedure

Removes transactions from the distribution database tables after they have been successfully distributed to the subscriber's database.

Syntax

sp_replcleanup publisher, subscriber, retention

where

publisher

Is the name of a publication server.

subscriber

Is the name of a subscription server.

retention

Is the number of hours to retain transactions after they have been successfully distributed to the subscription server.

Remarks

The sp_replcleanup stored procedure cleans up jobs for the specified publisher/subscriber pair. It is run on the distribution database and removes entries from these destination database tables: MSjob_commands, MSjobs, MSsubscriber_status, and MSsubscriber_jobs.

Important  Each distribution database is automatically cleaned up once a day. There is a default subscriber cleanup task (which has a large overhead) that is scheduled by default to run daily at 1:05 A.M.

Example

This example "cleans up" (removes transactions from) the distribution database tables on the AIREDALE server after they have been successfully distributed to the server WOLFHOUND and retains transactions for at least 8 hours.

sp_replcleanup AIREDALE, WOLFHOUND, 8

Permission

Execute permission defaults to the system administrator.

Tables Used

MSjob_commands, MSjobs, MSsubscriber_status, MSsubscriber_jobs

See Also

sp_replsync	sp_replica
sp_distcounters


sp_replcmds Replication Stored Procedure

For more updated SQL Server 6.5 syntax, see sp_replcmds.

Returns the commands for transactions marked for replication.

Syntax

sp_replcmds [maxtrans]

where

maxtrans

Is an integer indicating the number of transactions to return information about. If maxtrans is not provided, defaults to 1 (the next transaction waiting for distribution).

Remarks

This replication stored procedure is used by the logreader process. It returns information about the publication database from which it is executed. It allows you to view transactions currently not distributed (those transactions remaining in the transaction log that have not been sent to the distribution server), with their commands and it returns article ID, partial_command (true or false), the command, page, row, and timestamp.

Example

This example returns the commands for two transactions marked for replication.

sp_replcmds 2

Permission

Execute permission defaults to the system administrator.

Table Used

None.

See Also

sp_repldone	sp_replstatus
sp_replflush	sp_repltrans


sp_replcounters System Stored Procedure
sp_replcounters Replication Stored Procedure

Returns replication statistics about latency, throughput, and transaction count for each published database. Used by SQL Performance Monitor.

Syntax

sp_replcounters

Remarks

This stored procedure returns a list of published databases, and for each published database, returns the number of replicated transactions in the log that have not yet been delivered to the distribution database. It also returns the number of transactions per second that have been read out of the log.

This information can be viewed by using the appropriate counters in SQL Performance Monitor.

Example

This example shows information about replicated transactions in the pubs database.

sp_replcounters

go

database  repl. trans  repl. rate trans/sec  repl. latency(sec)

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

pubs      72           0.739645              174015000.0

Permission

Execute permission defaults to the system administrator and is granted to probe.

Table Used

None.

See Also

sp_replcmds	sp_replflush
sp_repldone	sp_replstatus


sp_repldone Replication Stored Procedure

Updates the record that identifies the server's last distributed transaction.

Syntax

sp_repldone page, row [, timestamp] [, numtrans] [, time] [, reset]

where

page

Specifies the page for the server's last distributed transaction.

row

Specifies the row for the server's last distributed transaction.

timestamp

Is the timestamp of the server's last distributed transaction.

numtrans

Is the number of transactions distributed.

time

Specifies the number of milliseconds, if provided, needed to distribute the last batch of transactions.

reset

Specifies the reset status. When set to 1, all replicated transactions in the log are marked as distributed. When set to 0, the transaction log is reset to the first replicated transaction and no replicated transactions are marked as distributed.

Valid only when page is 0 and row is 0.

Remarks

This replication stored procedure is used by the logreader process to keep track of which transactions have been distributed.

Caution  If you execute this stored procedure manually, you can invalidate the order and consistency of delivered transactions.

With this stored procedure, you can manually tell the server that a transaction has been replicated (sent to the distribution server). 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 will be marked as distributed.)

The required parameters page and row can be obtained using the sp_repltrans or sp_replcmds replication stored procedures.

When page is 0, row is 0, 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 (for example, a published table has been dropped) and you want to truncate the log. For example:

sp_repldone 0, 0, NULL, 0, 0, 1

When page is 0, row is 0, and reset is 0, the transaction log is reset to the first replicated transaction and no replicated transactions are marked as distributed. This is useful if you want to scan the transaction log's replicated transactions. For example:

sp_repldone 0, 0, 0, NULL, 0, 0, 0

Or, because these are all default settings:

sp_repldone

Permission

Execute permission defaults to the system administrator.

Table Used

None.

See Also

sp_replcmds	sp_replstatus
sp_replflush	sp_repltrans


sp_replflush Replication Stored Procedure

Flushes the article cache.

Syntax

sp_replflush

Remarks

Article definitions are stored in cache for efficiency. This stored procedure is used by other "sp_repl" replication stored procedures whenever an article definition is modified or dropped.

You should not have to execute this procedure manually.

Permission

Only the system administrator can use this procedure.

See Also

sp_replcmds	sp_replstatus
sp_repldone	sp_repltrans


sp_replica Replication Stored Procedure

Remotely sets on a subscription server a sysobjects category bit that marks the table as a replica.

Syntax

sp_replica tabname, replicated

where

tabname

Is a unique table name (owner.table) within the current database.

replicated

Sets a category bit that indicates that this is a destination table, a copy and not the original (publication) table. If false, clears the category replica_bit; if true, sets the category replica_bit.

Example

This example marks the authors table as a replica.

sp_replica authors, true

Permission

Execute permission defaults to the system administrator.

Table Used

sysobjects

See Also

sp_distcounters	sp_replcleanup
sp_replsync


sp_replstatus Replication Stored Procedure

Used to update the internal table structure for replication (the internal table structure indicates whether the table is being replicated).

Syntax

sp_replstatus objectID, status

where

objectID

Is the object ID of the table being replicated.

status

Specifies the status. Can be 0 (not replicated) or 1 (replicated).

Remarks

This replication stored procedure is used by the logreader process. It returns information about the publication database from which it is executed.

Executing sp_replstatus must be done in conjunction with an update of the category bit in the sysobjects table.

Example

This example indicates the sp_replstatus is being replicated.

sp_replstatus

Permission

Execute permission defaults to the system administrator and is granted to repl_subscriber.

Table Used

None.

See Also

sp_replcmds	sp_replflush
sp_repldone	sp_repltrans


sp_replsync Replication Stored Procedure

Used from a subscription server to acknowledge completion of a manual synchronization.

Syntax

sp_replsync publisher, publisher_db, publication [, article]

where

publisher

Is the name of the publisher.

publisher_db

Is the name of the database used.

publication

Is the name of the publication.

article

Is the name of the article.

Remarks

This stored procedure informs the distribution server that manual synchronization is complete. If all three of these fields are matched in the MSlast_job_info table, sp_replsync increments job_id by 1. (These fields are populated in MSlast_job_info when the distribution process encounters the job containing this specific manual synchronization event.) If no article is specified, all articles in the publication are marked as synchronized.

Example

This example, used from a subscription server, acknowledges the completion of manual synchronization for the WOLFHOUND server's mydb database, containing the mypub1 publication with the article myart3.

sp_replsync WOLFHOUND, mydb, mypub1, myart3

Permission

Execute permission defaults to the system administrator and the database owner.

Tables Used

sysobjects, MSlast_job_info

See Also

sp_distcounters	sp_replica
sp_replcleanup


sp_repltrans Replication Stored Procedure

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

Remarks

This replication stored procedure returns information about the publication database from which it is executed. It allows you to view transactions currently not distributed (those transactions remaining in the transaction log that have not been sent to the distribution server). It returns a results set displaying the row identifier (RID, containing the page and row) and the timestamp for each transaction. It is similar to the sp_replcmds stored procedure but does not return the commands for the transactions.

Example

This example returns all transactions in the publication database transaction log marked for publication but not yet distributed.

sp_repltrans

go

page        row    timestamp

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

5131        0      0x00000001000011d6

(1 row(s) affected)

Permission

Execute permission defaults to the system administrator.

Table Used

None.

See Also

sp_replcmds	sp_replstatus
sp_repldone	sp_repltrans
sp_replflush


sp_subscribe Replication Stored Procedure

Remotely adds a subscription to a particular article within a publication.

Syntax

sp_subscribe publication, [article [, destination_db
[, @sync_type = {'automatic' | 'manual' | 'none'}]]]

where

publication

Is the name of the publication.

article

Is the name of the article. The name must be unique within the publication. If article is not supplied or if set to all, a subscription is added to all articles in the publication.

destination_db

Is the name of the destination (subscription) database in which to place replicated data. The default is NULL (indicating the same database name as the publication database).

@sync_type

Specifies the synchronization type. If set to automatic (the default), the subscription synchronization job is passed to the distribution database. If set to manual, the synchronization holder is passed to the distribution database and must be manually reset by the subscriber.

If set to none, there is no synchronization. A synchronization file is not created, there is no synchronization job passed to the distribution database, and the subscriber's status is set to active instead of subscribed. All future transactions are sent to the subscriber.

Remarks

This stored procedure causes rows to be added to the syssubscriptions table only if those rows indicate that the publication was unrestricted. If the publication was restricted, a valid entry must already exist in syssubscriptions. Running sp_subscribe causes the status for this entry to be changed from inactive to subscribed.

Example

This example adds remote subscription to the types_table article in the pub_alltype publication for the mydb database (on the subscription server) and sets the synchronization type to manual.

sp_subscribe pub_alltypes, types_table, mydb, 'manual'

Permission

Execute permission defaults to the system administrator and database owner and is also granted to repl_subscriber.

Tables Used

sysarticles, syspublications, syssubscriptions, sysservers

See Also

sp_addsubscription	sp_dropsubscription
sp_changesubscription	sp_helpsubscription
sp_changesubstatus	sp_unsubscribe


sp_unsubscribe Replication Stored Procedure

Remotely cancels a subscription to a particular article within a publication, to a whole publication, or to all publications. It also removes all pending jobs from the distribution database.

Syntax

sp_unsubscribe 'publication', 'article'

where

publication

Is the name of the associated publication. Specifying all drops all subscriptions. An entry is required.

article

Is the name of the article. Specifying all drops subscriptions to all articles for each specified publication.

Remarks

If the publication is restricted, running sp_unsubscribe causes the status for this subscription to be changed to inactive.

Example

This example cancels a subscription to all articles and all publications.

sp_unsubscribe 'all', 'all'

Permission

Execute permission defaults to the system administrator and the database owner and is also granted to repl_subscriber.

Tables Used

sysarticles, syspublications, syssubscriptions, sysservers

See Also

sp_addsubscription	sp_dropsubscription
sp_changesubscription	sp_helpsubscription
sp_changesubstatus	sp_subscribe


Stored Procedures-SQL Executive Stored Procedures

SQL Executive stored procedures give system administrators the ability to create tasks for replication, event scheduling and alert management. The SQL Executive stored procedures are rarely executed directly, they are usually manipulated by SQL Enterprise Manager, which provides an easy, graphical way to manage the entire alerting and scheduling system. It is recommended that you use SQL Enterprise Manager to configure your alert and scheduling infrastructure.

This section describes the stored procedures used by SQL Executive to implement and initiate scheduled events and alerts. The stored procedures can be categorized by type: alert stored procedures and scheduling stored procedures.

Alert Stored Procedures

These are the stored procedures used by the SQL Executive to provide alerts:

sp_addalert	sp_helpalert
sp_addnotification	sp_helpnotification
sp_addoperator	sp_helpoperator
sp_dropalert	sp_updatealert
sp_dropnotification	sp_updatenotification
sp_dropoperator	sp_updateoperator
Scheduling Stored Procedures

These are the stored procedures used by the SQL Executive to provide scheduling:

sp_addtask	sp_helptask
sp_droptask	sp_purgehistory
sp_helphistory	sp_updatetask
All of the SQL Executive stored procedures are listed individually within this section.


sp_addalert SQL Executive Stored Procedure

Creates an alert.

Syntax

sp_addalert name, message_id, severity [, enabled] [, delay_between_responses] [, notification_message] [, include_event_description_in] [, database_name] [, event_description_keyword] [, task_name]

where

name

Is the name of the alert (for example, 605 Alert). This name will appear in the e-mail and/or page sent in response to the alert. It must be unique and be no more than 60 characters.

message_id

Is the message error number that defines the alert. (Normally corresponds to an error number in the sysmessages table.) If severity is used to define the alert, message_id must be zero or NULL. Note that only sysmessages errors written to the event log can cause an alert to be sent.

severity

Specifies the severity level (9 through 25, 110, 120, 130, or 140) that defines the alert. Any SQL Server message stored in the sysmessages table that is sent to the Windows NT event log with the indicated severity will cause the alert to be sent. If message_id is used to define the alert, severity must be zero or NULL.

enabled

Indicates whether the alert is currently enabled (1 if enabled, 0 if not). A non-enabled alert will not be sent. The default is enabled (1).

delay_between_responses

Specifies the wait period, in seconds, between responses to the alert. The response consists of :

•	One or more notifications sent via e-mail and/or pager

and/or

•	A task to execute

By setting this value it is possible to prevent, for example, an unwanted flood of e-mail messages from being sent when an alert repeatedly occurs in a short period of time. If a value is not supplied, the default is 0, which means there is no waiting between responses (each occurrence of the alert generates a response).

notification_message

Is an optional additional message that will be sent to the operator as part of the e-mail and/or pager notification. Specifying notification_message is useful for adding special notes such as remedial procedures. It can contain as many as 255 characters.

include_event_description_in

Specifies whether the description of the SQL Server error from the Windows NT event log should be included as part of the notification message. Must be NONE, EMAIL, PAGER or BOTH.

database_name

More restrictively defines the alert by specifying the database in which the error must occur in order for the alert to fire. If database_name is not supplied, the alert will fire regardless of in which database the error occurred.

event_description_keyword

More restrictively defines the alert by specifying that the description of the SQL Server error in the Windows NT event log must be like the supplied sequence of characters. Transact-SQL LIKE expression pattern-matching characters can be used. This parameter is useful for filtering object names (for example, %customer_table%). It can contain as many as 100 characters.

task_name

Specifies an On-Demand task to be executed in response to an alert. The task must be of type CmdExec or TSQL. For details, see the sp_addtask SQL Executive Stored Procedure.

Remarks

This stored procedure must be run from the msdb database.

The following summarizes the circumstances under which errors/messages generated by SQL Server and SQL Server applications are sent to the Windows NT event log and can therefore raise alerts:

•	Severity 19 or higher sysmessages errors

•	information/warnings/errors from the server (severities 110, 120, and 130)

•	Any RAISERROR statement invoked with WITH_LOG syntax

•	Any user-defined messages in the sysmessages table that were created with a WITH_LOG option of 'TRUE'

•	Any sysmessages error modified using the sp_altermessage SQL executive stored procedure (for example, sp_altermessage 123456, with_log, true)

•	Any event logged using the xp_logevent extended stored procedure

SQL Enterprise Manager provides an easy, graphical way to manage the entire alerting system. Using SQL Enterprise Manager is the recommended way to configure your alert infrastructure.

If an alert is not functioning properly, check the following:

•	The SQL Executive service is running

•	The event appeared in the Windows NT event log

•	The alert is enabled

Example

This example adds an alert ('Test Alert') that invokes the task 'Back up the Customer Database,' when fired.

EXEC sp_addalert @name = 'Test Alert', @message_id = 55001, @severity = NULL, @notification_message = 'Error 55001 has occurred. The database will be backed up...', @task_name = 'Back up the Customer Database'

Permission

Only the system administrator can use this procedure.

Tables Used

sysalerts, systasks

See Also

sp_addnotification	sp_helpalert
sp_addtask	sp_updatealert
sp_dropalert


sp_addnotification SQL Executive Stored Procedure

Sets up a notification for an alert.

Syntax

sp_addnotification alert_name, operator_name, notification_method

where

alert_name

Specifies which alert this notification is for.

operator_name

Specifies the operator to be notified when the alert occurs.

notification_method

Indicates the method by which the operator will be notified. Can be EMAIL, PAGER, or BOTH.

Remarks

This stored procedure must be run from the msdb database.

To send a notification in response to an alert, you must first configure SQLServer to send mail. For details, see the Microsoft SQL Server Administrator's Companion.

You can add a notification for an operator who does not have the necessary address information to be notified by using the specified notification_method. If a failure occurs when sending an e-mail message or pager notification, the failure is reported in the Windows NT application event log.

SQL Enterprise Manager provides an easy, graphical way to manage the entire alerting system. Using SQL Enterprise Manager is the recommended way to configure your alert infrastructure.

Example

This example adds a notification for the specified alert ('Test Alert').

EXEC sp_addnotification 'Test Alert', 'John Doe', EMAIL

Permission

Only the system administrator can use this procedure.

Tables Used

sysalerts, sysnotifications, sysoperators

See Also

sp_dropnotification	sp_updatenotification
sp_helpnotification


sp_addoperator SQL Executive Stored Procedure

Sets up an operator (notification recipient) for use with alerts.

Syntax

sp_addoperator name [, enabled] [, email_address] [, pager_number]
[, weekday_pager_start_time] [, weekday_pager_end_time] [, saturday_pager_start_time] [, saturday_pager_end_time] [, sunday_pager_start_time] [, sunday_pager_end_time] [, pager_days]

where

name

Is the name of the operator (notification recipient). This name must be unique and can be as many as 50 characters.

enabled

Indicates the operator's current status (1 if currently enabled, 0 if not). If an operator is not enabled, he or she will not receive notifications. The default is 1 (enabled).

email_address

Specifies the e-mail address of the operator. This string will be passed directly to the e-mail system. It can be as many as 100 characters.

pager_number

Specifies the pager address of the operator. This string will be passed directly to the e-mail system. It can be as many as 100 characters.

weekday_pager_start_time

Sets the start time after which to send pager notification to the specified operator Monday through Friday. It must be of the form HHMMSS. The default is 9:00 A.M.

weekday_pager_end_time

Sets the end time after which to cease pager notification to the specified operator Monday through Friday. It must be of the form HHMMSS. The default is 6:00 P.M.

saturday_pager_start_time

Sets the start time after which to send pager notification to the specified operator on Saturdays. It must be of the form HHMMSS. The default is 9:00 A.M. (if not supplied).

saturday_pager_end_time

Sets the end time after which to cease a pager notification to the specified operator on Saturdays. It must be of the form HHMMSS. The default is 6:00 P.M. (if not supplied).

sunday_pager_start_time

Sets the start time after which to send a pager notification to the specified operator on Sundays. It must be of the form HHMMSS. The default is 9:00 A.M. (if not supplied).

sunday_pager_end_time

Sets the end time after which to cease pager notification to the specified operator on Sundays. It must be of the form HHMMSS. The default is 6:00 P.M. (if not supplied).

pager_days

Specifies the days that the operator is available for pages (subject to the specified start/end times). Must be a value from 0 through 127. The value is calculated by adding together the individual values for the required days:

1	Sunday
2	Monday
4	Tuesday
8	Wednesday
16	Thursday
32	Friday
64	Saturday

For example, Monday through Friday would be 2+4+8+16+32 = 62. If no value is supplied, the default is 0 (meaning that the operator is never available to receive a page).

Remarks

This stored procedure must be run from the msdb database.

Paging is supported via the e-mail system, which must have an e-mail−to−pager capability if you want to use paging.

SQL Enterprise Manager provides an easy, graphical way to manage the entire alerting system. Using SQL Enterprise Manager is the recommended way to configure your alert infrastructure.

Example

This example sets up the operator information for John Doe.

EXEC sp_addoperator @name = 'John Doe', @email_address = 'JohnD@company.com'

Permission

Only the system administrator can use this procedure.

Tables Used

sysoperators

See Also

sp_dropoperator	sp_updateoperator
sp_helpoperator


sp_addtask SQL Executive Stored Procedure

For more updated SQL Server 6.5 syntax, see sp_addtask.

Creates a scheduled task.

Syntax

sp_addtask name [, subsystem] [, server] [, username] [, databasename]
[, enabled] [, freqtype] [, freqinterval] [, freqsubtype] [, freqsubinterval]
[, freqrelativeinterval] [, freqrecurrencefactor] [, activestartdate]
[, activeenddate] [, activestarttimeofday] [, activeendtimeofday]
[, nextrundate] [, nextruntime] [, runpriority] [, emailoperatorname]
[, retryattempts] [, retrydelay] [, command] [, loghistcompletionlevel]
[, emailcompletionlevel] [, description] [, tagadditionalinfo] [, tagobjectid]
[, tagobjecttype] [, @newid OUTPUT]

where

name

Is the name of the task being scheduled.

subsystem

Specifies the subsystem to use. Can be Distribution, LogReader, Sync, TSQL, or CmdExec. These must be typed using the capitalization (case) shown.

server

Specifies the server on which to execute this task.

username

Specifies the database user to impersonate when executing this task. Only the system administrator or the database owner can specify this parameter.

databasename

Specifies the database to use when executing the task.

enabled

Specifies the status of scheduled tasks: 1 indicates enabled, the tasks will be scheduled and run; 0 indicates disabled, the tasks will not be scheduled and run.

freqtype

Specifies the frequency for this task:
1	One Time
2	On Demand (the default)
4	Daily
8	Weekly
16	Monthly
32	Monthly Relative
64	Autostart
124	Recurring

freqinterval

Specifies the interval for freqtype.

freqsubtype

Specifies how often to reschedule the task during the defined period:
1  Once (the default)
2  Second
4  Minute
8  Hour

freqsubinterval

Specifies the value for freqsubtype when the freqsubtype is set to second, minute, or hour.

freqrelativeinterval

Specifies the value used when freqtype is set to 32 (monthly relative). Indicates the first, second, third, fourth, or last day of the month:

1	First (the default)
2	Second
4	Third
8	Fourth
16	Last

freqrecurrencefactor

Specifies how often the task should reoccur during the defined freqtype.

activestartdate

Specifies the date when this task will first be scheduled. Formatted as YYYYMMDD. The default is 0.

activeenddate

Specifies the date when this task will stop being scheduled. Formatted as YYYYMMDD. The default is 0.

activestarttimeofday

Specifies when this task will be scheduled initially. Formatted as HHMMSS. The default is 0.

activeendtimeofday

Specifies when this task will stop being scheduled. Formatted as HHMMSS. The default is 0.

nextrundate

Specifies the date the task will be scheduled. If the current date is greater than activestartdate, specifies the next date that the task will be scheduled; 0 indicates that the SQL Executive will calculate the next appropriate date. Formatted as YYYYMMDD. The default is 0.

nextruntime

Specifies the date the task will be scheduled if the current time is greater than the activestarttime. 0 indicates that the SQL Executive will calculate the next appropriate time. Formatted as HHMMSS. The default is 0.

runpriority

Specifies the thread priority level at which the subsystem event thread runs. The default is 0.

emailoperatorname

The e-mail name of the operator who will receive notifications. The default is NULL.

retryattempts

Specifies the number of times the SQL Executive retries before issuing an error. The default is 0.

retrydelay

Specifies the interval the SQL Executive waits before retrying the task. The default is 1.

command

Specifies a command string (based on the valid specified subsystem commands) to be passed to the subsystem. If the specified subsystem is TSQL, the command cannot consist of more than one batch. The batch separator GO is not supported. The default is NULL.

loghistcompletionlevel

Specifies the level of events to capture in the event log: 1 captures all successfully run events, 2 captures only failed events.

emailcompletionlevel

Specifies the level of events to capture via e-mail: 1 captures all successfully run events; 2 captures only failed events. The default is 2.

description

Is a description of the task.

tagadditionalinfo

Is user-defined information. This parameter is not required and is normally not used. Varchar (96).

tagobjectid

Is user-defined information. This parameter is not required and is normally not used. Integer.

tagobjecttype

Is user-defined information. This parameter is not required and is normally not used. Integer.

@newid OUTPUT

Is an output parameter that returns the system generated ID for the task.

Remarks

This stored procedure must be run from the msdb database.

Examples

A.	Add a Sync Task

This example adds a task for "auth_table_sync" in subsystem "Sync" to run each hour from 9 A.M. to 11 P.M. If scheduled to run after September 26, 1995, the task starts at 4:00 P.M. the first day.

sp_addtask "auth_table_sync", "Sync", "server1", "sa",
"pubs", 1, 4, 1, 8, 1, 0, 0, 19950926, 19991231,
090000, 230000, 00000000, 160000, 0, "", 2, 1, "", 2, 2

B.	Add a Distribution Task

This example adds a task for "dist_server2_pubs" in subsystem "Distribution" to run every 15 minutes and pass the command string "-Sserver2 -Usa -P -dpubs -pserver1".

sp_addtask "dist_server2_pubs", "Distribution", "server1",
"sa", "pubs", 1, 4, 1, 4, 15, 0, 0, 19950926, 19991231, 000500,
235500, 00000000, 000000, 0, "", 2, 1,
"-server2 -Usa -P -dpubs -pserver1", 2, 2

Permission

Execute permission defaults to the public group.

Tables Used

systasks

See Also

sp_droptask	sp_purgehistory
sp_helphistory	sp_updatetask
sp_helptask


sp_dropalert SQL Executive Stored Procedure

Drops an alert.

Syntax

sp_dropalert name

where

name

Specifies which alert to drop.

Remarks

This stored procedure must be run from the msdb database.

Dropping an alert also drops all the associated notifications for that alert.

SQL Enterprise Manager provides an easy, graphical way to manage the entire alerting system. Using SQL Enterprise Manager is the recommended way to configure your alert infrastructure.

Example

This example drops the 'Test Alert' alert.

sp_dropalert 'Test Alert'

Permission

Only the system administrator can use this procedure.

Tables Used

sysalerts, sysnotifications

See Also

sp_addalert	sp_updatealert
sp_helpalert


sp_dropnotification SQL Executive Stored Procedure

Drops a notification for an alert.

Syntax

sp_dropnotification alert_name, operator_name

where

alert_name

Specifies the alert to drop the notification for.

operator_name

Is the name of the operator who is no longer to be notified when alert_name occurs.

Remarks

This stored procedure must be run from the msdb database.

SQL Enterprise Manager provides an easy, graphical way to manage the entire alerting system. Using SQL Enterprise Manager is the recommended way to configure your alert infrastructure.

Example

This example drops the notification information for the 'Test Alert' alert.

sp_dropnotification 'Test Alert', 'John Doe'

Permission

Only the system administrator can use this procedure.

Tables Used

sysalerts, sysnotifications, sysoperators

See Also

sp_addnotification	sp_updatenotification
sp_helpnotification


sp_dropoperator SQL Executive Stored Procedure

Drops an operator.

Syntax

sp_dropoperator name

where

name

Is the name of the operator to drop.

Remarks

This stored procedure must be run from the msdb database.

Dropping an operator also drops all of the operator's notifications. If the specified operator is the "Fail-Safe Operator," the operator cannot be dropped.

The "Fail-Safe Operator" is the operator who is notified if none of the pager notifications can be sent. The "Fail-Safe Operator" is defined using SQL Enterprise Manager, and SQL Enterprise Manager provides an easy, graphical way to manage the entire alerting system. Using SQL Enterprise Manager is the recommended way to configure your alert infrastructure.

Example

This example removes all of the operator information for John Doe.

sp_dropoperator 'John Doe'

Permission

Only the system administrator can use this procedure.

Tables Used

sysnotifications, sysoperators

See Also

sp_addoperator	sp_updateoperator
sp_helpoperator


sp_droptask SQL Executive Procedure
sp_droptask SQL Executive Stored Procedure

Removes a scheduled task.

Syntax

sp_droptask {name | loginname | id}

where

name

Is the name of the task to be removed.

loginname

Is a login name. If specified, all tasks assigned to that login name are dropped. If not NULL, loginname takes precedence over name and id.

id

Is the task ID of the task to be removed. If not NULL, id takes precedence over name.

Remarks

This stored procedure must be run from the msdb database.

Example

This example removes the auth_table_sync task.

sp_droptask auth_table_sync

Permission

Execute permission defaults to the public group.

Tables Used

systasks, syshistory

See Also

sp_addtask	sp_purgehistory
sp_helptask	sp_updatetask


sp_helpalert SQL Executive Stored Procedure

Reports information about the alerts defined for the server.

Syntax

sp_helpalert [having_name_like]

where

having_name_like

Is the string used to search for similar alert_names. Wildcard characters are supported.

Remarks

This stored procedure must be run from the msdb database.

SQL Enterprise Manager provides an easy, graphical way to manage the entire alerting system. Using SQL Enterprise Manager is the recommended way to configure your alert infrastructure.

Example

This example reports information about all alerts with a name beginning with Test.

sp_helpalert 'Test%'

Permission

Only the system administrator can use this procedure.

Tables Used

sysalerts, systasks

See Also

sp_addalert	sp_updatealert
sp_dropalert	Wildcard characters


sp_helphistory SQL Executive Stored Procedure

For more updated SQL Server 6.5 syntax, see sp_helphistory.

Reports the history of one or more scheduled events, alerts, or tasks.

Syntax

sp_helphistory [, taskname] [, taskid] [, eventid] [, messageid] [, severity] [, source] [, category] [, startdate] [, enddate] [, starttime] [, endtime] [, skipped] [, oldestfirst] [, mode]

where

taskname

Specifies the name of the task about which a history will be displayed.

taskid

Specifies the ID of the task about which a history will be displayed.

eventid

Specifies the ID of the event from the Windows NT application event log.

messageid

Specifies the ID of the message as stored in the sysmessages table.

severity

Specifies the severity of the message as stored in the sysmessages table or passed with the RAISERROR statement.

source

Specifies the source of the event. Currently, there is only one source, MSSQLServer.

category

Reserved for future use.

startdate

Specifies tasks beginning their scheduled run(s) on this date.

enddate

Specifies tasks ending their scheduled run(s) on this date.

starttime

Specifies tasks beginning their scheduled run(s) at this time.

endtime

Specifies tasks ending their scheduled run(s) at this time.

skipped

Specifies the number of times this task's run was skipped (usually because the server or SQL Executive were not running).

oldestfirst

Display the oldest task history first.

mode

Specifies the return mode. Can be full (returns all information) or quick (returns only the most useful information). The default is quick.

Remarks

The outcome of the sp_helphistory SQL Executive stored procedure is determined by a match on all specified parameters.

Examples

This example displays history of the sysmessages message 55001.

sp_helphistory @messageid = 55001

Permission

Execute permission defaults to the public group.

Tables Used

syshistory, sysoperators, systasks

See Also

sp_addtask	sp_purgehistory


sp_helpnotification SQL Executive Stored Procedure

Reports a list of notifications.

Syntax

sp_helpnotification object_type, name, enum_type, notification_method [, target_name]

where

object_type

Indicates the type of information to be returned. Can be ALERTS for a list of alerts assigned to the supplied operator name, or OPERATORS for a list of operators responsible for the supplied alert name.

name

Is either an operator name or an alert name.

enum_type

Controls what object_type information is returned. Specify ACTUAL (to see only the object_types associated with name), ALL (to see all the object_types including those that are not associated with name), or TARGET (to see only the object_type matching the supplied target_name, irrespective of association with name). This parameter will be ACTUAL in most cases.

notification_method

Specifies the notification method: EMAIL, PAGER or BOTH. When enum_type is ALL or TARGET, affects only the column headings appearing in the output. When enum_type is ACTUAL, affects both the column headings and the returned rows.

target_name

Specifies an alert name to search for (if object_type is ALERTS) or an operator name to search for (if object_type is OPERATORS). Needed only if enum_type is TARGET.

Remarks

This stored procedure must be run from the msdb database.

SQL Enterprise Manager provides an easy, graphical way to manage the entire alerting system. Using SQL Enterprise Manager is the recommended way to configure your alert infrastructure.

Examples

A.	Alerts for a Specific Operator

This example returns all alerts for which the operator John Doe receives any kind of notification.

sp_helpnotification 'ALERTS', 'John Doe', 'ACTUAL', 'BOTH'

B.	Operators for a Specific Alert

This example returns all operators who receive any kind of notification for the 'Test Alert' alert.

sp_helpnotification 'OPERATORS', 'Test Alert', 'ACTUAL', 'BOTH'

Permission

Only the system administrator can use this procedure.

Tables Used

sysalerts, sysnotifications, sysoperators

See Also

sp_addnotification	sp_updatenotification
sp_dropnotification


sp_helpoperator SQL Executive Stored Procedure

Reports information about the operators defined for the server.

Syntax

sp_helpoperator [having_name_like]

where

having_name_like

Is the string used to search for similar operator names. Wildcard characters are supported.

Remarks

This stored procedure must be run from the msdb database.

SQL Enterprise Manager provides an easy, graphical way to manage the entire alerting system. Using SQL Enterprise Manager is the recommended way to configure your alert infrastructure.

Example

This example reports information about all operators with two names, beginning with John.

sp_helpoperator 'John%'

Permission

Only the system administrator can use this procedure.

Tables Used

sysoperators

See Also

sp_addoperator	Wildcard characters
sp_updateoperator


sp_helptask SQL Executive Stored Procedure

For more updated SQL Server 6.5 syntax, see sp_helptask.

Provides information about one or more tasks.

Syntax

sp_helptask taskname [, taskid] [, loginname] [, operatorname] [, subsystem]
[, mode]

where

taskname

Returns information about all tasks with names like taskname.

taskid

Is the ID of the task.

loginname

Is the owner of the tasks whose information is to be returned.

operatorname

Is the name of the operator who might be paged or sent e-mail when the tasks are completed (depending on the e-mail completion level).

subsystem

Is the subsystem the tasks will run against. For replication, can be Distribution, LogReader, or Sync.

mode

Specifies the amount of information to return. Can be full (returns all information) or quick (returns only the most useful information). The default is quick.

Remarks

The quick mode returns the taskname, taskid, subsystem, server (the server on which to execute the task), username (the username used for login to execute the task), dbname (the database to be used when executing the task), and enabled status (1 indicates tasks will be scheduled and run, 0 indicates disabled).

The full mode adds information as supplied when the task was defined. For details, see the options in the sp_addtask SQL Executive Stored Procedure.

Example

This example returns all information about the auth_table_sync task.

sp_helptask auth_table_sync, @mode = 'full'

Permission

Execute permission defaults to the public group.

Tables Used

sysoperators, systasks

See Also

sp_addtask	sp_purgehistory
sp_droptask	sp_updatetask


sp_purgehistory SQL Executive Stored Procedure

Removes information from the history log.

Syntax

sp_purgehistory [taskname] [, taskid] [, eventid] [, messageid] [, severity] [, source] [, category] [, startdate] [, enddate] [, starttime] [, endtime] [, skipped]

where

taskname

Specifies the name of the task about which a history will be displayed. You must be the task owner, unless you are the system administrator.

taskid

Specifies the ID of the task about which a history will be displayed. You must be the task owner, unless you are the system administrator.

eventid

Reserved.

messageid

Specifies the ID of the message as stored in the sysmessages table.

severity

Specifies the severity of the message as stored in the sysmessages table or passed with the RAISERROR statement.

source

Reserved.

category

Reserved for future use.

startdate

Specifies tasks beginning their scheduled run(s) on this date.

enddate

Specifies tasks ending their scheduled run(s) on this date.

starttime

Specifies tasks beginning their scheduled run(s) at this time.

endtime

Specifies tasks ending their scheduled run(s) at this time.

skipped

Specifies the number of times this task's run was skipped (usually because the server or SQL Executive was not running).

Remarks

The sp_purgehistory SQL Executive stored procedure clears all records found by matching all specified parameters.

Example

This example clears the history for taskid 12.

sp_purgehistory @taskid = 12

Permission

Execute permission defaults to the public group.

Tables Used

syshistory, systasks

See Also

sp_addtask	sp_helphistory


sp_updatealert SQL Executive Stored Procedure

Updates information for an existing alert.

Syntax

sp_updatealert name [, new_name] [, enabled] [, message_id] [, severity] [, delay_between_responses] [, notification_message] [, include_event_description_in] [, database_name] [, event_description_keyword] [, task_name] [, occurrence_count] [, count_reset_date] [, count_reset_time] [, last_occurrence_date] [, last_occurrence_time] [, last_response_date] [, last_response _time]

where

name

Is the original name of the alert.

new_name

Is the new name for the alert. It must be unique and be no more than 60 characters.

enabled

Indicates whether the alert is currently enabled (1 if enabled, 0 if not). An alert must be enabled to run. The default is 1 (enabled).

message_id

Is the message/error number that defines the alert. Normally corresponds to an error number in the sysmessages table. If severity is used to define the alert, must be zero or NULL.

Note  Only sysmessages written to the Windows NT application event log can activate an alert.

severity

Specifies the severity level (9 through 25, 120, 130, or 140) that defines the alert. Any SQL Server message sent to the Windows NT event log with the indicated severity will activate the alert. If message_id is used to define the alert, must be zero or NULL.

delay_between_responses

Specifies the wait period, in seconds, between responses to the alert. The response consists of :

•	One or more notifications sent via e-mail and/or pager

and/or

•	A task to execute

By setting this value it is possible to prevent, for example, an unwanted flood of e-mail messages from being sent when an alert repeatedly occurs in a short period of time. If not supplied, the default is 0, which means there is no waiting between responses (each occurrence of the alert generates a response).

notification_message

Is an optional additional message that will be sent to the operator as part of the e-mail and/or pager notification. Specifying notification_message is useful for adding special notes such as remedial procedures. It can contain as many as 255 characters.

include_event_description_in

Specifies whether the description of the SQL Server error from the Windows NT event log should be included as part of the notification message. Must be NONE, EMAIL, PAGER, or BOTH.

database_name

More restrictively defines the alert by specifying the database in which the error must occur in order for the alert to fire. If database_name is not supplied, the alert will fire regardless of the database in which the error occurs.

event_description_keyword

More restrictively defines the alert by specifying that the description of the SQL Server error in the Windows NT event log must be like the supplied sequence of characters. Transact-SQL LIKE expression pattern-matching characters may be used. This parameter is useful for filtering object names (for example, %customer_table%). It can contain as many as 100 characters.

task_name

Specifies the On-Demand task that will execute in response to an alert. The task must be of type 'CmdExec' or 'TSQL'. For details, see the sp_addtask SQL executive stored procedure.

occurrence_count

Indicates the number of times the alert has occurred. This parameter is used for reset purposes only.

count_reset_date

Indicates the date the occurrence count was last reset. This parameter is used for reset purposes only.

count_reset_time

Indicates the time the occurrence count was last reset. This parameter is used for reset purposes only.

last_occurrence_date

Indicates the date the alert last occurred. This parameter is used for reset purposes only.

last_occurrence_time

Indicates the time the alert last occurred. This parameter is used for reset purposes only.

last_response_date

Indicates the date the alert was last responded to by the SQL Executive service. This parameter is used for reset purposes only.

last_response_time

The time the alert was last responded to by the SQL Executive service. This parameter is used for reset purposes only.

Remarks

This stored procedure must be run from the msdb database.

SQL Enterprise Manager provides an easy, graphical way to manage the entire alerting system. Using SQL Enterprise Manager is the recommended way to configure your alert infrastructure.

Example

This example updates the alert 'Test Alert' to an enabled status of 0.

sp_updatealert @name = 'Test Alert', @enabled = 0

Permission

Only the system administrator can use this procedure.

Tables Used

sysalerts, systasks

See Also

sp_addalert	sp_helpalert
sp_dropalert


sp_updatenotification SQL Executive Stored Procedure

Updates the notification method of an alert notification.

Syntax

sp_updatenotification alert_name, operator_name, notification_method

where

alert_name

Is the name of the alert associated with this notification.

operator_name

Specifies which operator will be notified when the alert occurs.

notification_method

Indicates the method by which the operator will be notified. Can be: EMAIL, PAGER, or BOTH.

Remarks

This stored procedure must be run from the msdb database.

You can update a notification for an operator who does not have the necessary address information to be notified using the specified notification_method. If a failure occurs when sending an e-mail message or pager notification, the failure is reported in the Windows NT application event log.

SQL Enterprise Manager provides an easy, graphical way to manage the entire alerting system. Using SQL Enterprise Manager is the recommended way to configure your alert infrastructure.

Example

This example sets the notification status to EMAIL.

sp_updatenotification 'Test Alert', 'John Doe', EMAIL

Permission

Only the system administrator can use this procedure.

Tables Used

sysalerts, sysnotifications, sysoperators

See Also

sp_addnotification	sp_helpnotification
sp_dropnotification


sp_updateoperator SQL Executive Stored Procedure

Updates information about an operator.

Syntax

sp_updateoperator name [, new_name] [, enabled] [, email_address] [, pager_number] [, weekday_pager_start_time] [, weekday_pager_end_time] [, saturday_pager_start_time] [, saturday_pager_end_time] [, sunday_pager_start_time] [, sunday_pager_end_time] [, pager_days]

where

name

Is the original name of the operator.

new_name

Is the new name for the operator. This name must be unique and can be as many as 50 characters.

enabled

Indicates the operator's current status (1 if currently enabled, 0 if not). If an operator is not enabled, he or she will not receive notifications. The default is 1 (enabled).

email_address

Specifies the e-mail address of the operator. This string will be passed directly to the e-mail system. It can be as many as 100 characters.

pager_number

Specifies the pager address of the operator. This string will be passed directly to the e-mail system. It can be as many as 100 characters.

weekday_pager_start_time

Sets the starting time after which to send a pager notification to this operator Monday through Friday. It must be of the form HHMMSS. The default is 9:00 A.M.

weekday_pager_end_time

Sets the end time after which to cease a pager notification to the specified operator Monday through Friday. It must be of the form HHMMSS. The default is 6:00 P.M.

saturday_pager_start_time

Sets the start time after which to send a pager notification to the specified operator on Saturdays. It must be of the form HHMMSS. The default is 9:00 A.M.

saturday_pager_end_time

Sets the end time after which to send a pager notification to the specified operator on Saturdays. It must be of the form HHMMSS. The default is 6:00 P.M.

sunday_pager_start_time

Sets the start time after which to send a pager notification to the specified operator on Sundays. It must be of the form HHMMSS. The default is 9:00 A.M.

sunday_pager_end_time

Specifies the end time after which to cease pager notification to the specified operator on Sundays. It must be of the form HHMMSS. The default is 6:00 P.M.

pager_days

Specifies the days that the operator is available for pages (subject to the specified start/end times). Must be a value from 0 through 127. The value is calculated by adding together the individual values for the required days:

1	Sunday
2	Monday
4	Tuesday
8	Wednesday
16	Thursday
32	Friday
64	Saturday

For example, Monday through Friday would be 2+4+8+16+32 = 62. If no value is supplied, the default is 0 (meaning that the operator is never available to receive a page, regardless of the pager schedule for that operator).

Remarks

This stored procedure must be run from the msdb database.

SQL Enterprise Manager provides an easy, graphical way to manage the entire alerting system. Using SQL Enterprise Manager is the recommended way to configure your alert infrastructure.

Example

This example updates the operator status to enabled.

sp_updateoperator @name = 'John Doe', @enabled = 1

Permission

Only the system administrator can use this procedure.

Tables Used

sysoperators

See Also

sp_addoperator


sp_updatetask SQL Executive Stored Procedure

Updates information about a task.

Syntax

sp_updatetask {currentname | id} [, name] [, subsystem] [, server] [, username] [, databasename] [, enabled] [, freqtype] [, freqinterval] [, freqsubtype] [, freqsubinterval] [, freqrelativeinterval] [, freqrecurrencefactor] [, activestartdate] [, activeenddate] [, activestarttimeofday] [, activeendtimeofday] [, nextrundate] [, nextruntime] [, runpriority] [, emailoperatorname] [, retryattempts] [, retrydelay] [, command] [, loghistcompletionlevel] [, emailcompletionlevel] [, description] [, tagadditionalinfo] [, tagobjectid] [, tagobjecttype]

where

currentname | id

Specifies which task to update.

name

Specifies a new name for the task.

subsystem

For replication, specifies which subsystem to use. Can be Distribution, LogReader, or Sync. These must be typed using the capitalization (case) shown.

server

Specifies the name of server on which to execute this task.

username

Specifies the database user to impersonate when creating this task. Only the system administrator or the database owner can specify this parameter.

databasename

Specifies the database to use when executing the task.

enabled

Specifies the status of scheduled tasks: 1 indicates enabled (tasks will be scheduled and run), 0 indicates disabled.

freqtype

Specifies the frequency with which to schedule this task:
1	One Time
2	On Demand (the default)
4	Daily
8	Weekly
16	Monthly
32	Monthly Relative
64	Autostart
124	Recurring

freqinterval

Specifies the interval for freqtype.

freqsubtype

Specifies how often to reschedule during the defined period:
1	Once (the default)
2	Second
4	Minute
8	Hour

freqsubinterval

Specifies the value for freqsubtype when the subtype is set to second, minute, or hour.

freqrelativeinterval

Is the value used when freqtype is set to 32 (monthly relative). Indicates the first, second, third, fourth, or last day of the month.

1	First (the default)
2	Second
4	Third
8	Fourth
16	Last

freqrecurrencefactor

Specifies how often the task should re-occur during the defined freqtype.

activestartdate

Specifies the date when this task will be scheduled initially. Formatted as YYYYMMDD. The default is 0.

activeenddate

Specifies the date when this task will stop being scheduled. Formatted as YYYYMMDD. The default is 0.

activestarttimeofday

Specifies the time this task will be scheduled initially. Formatted as HHMMSS. The default is 0.

activeendtimeofday

Specifies when this task will stop being scheduled. Formatted as HHMMSS. The default is 0.

nextrundate

Specifies the date the task will be scheduled. If the current date is greater than activestartdate, specifies the next date that the task will be scheduled: 0 indicates that the SQL Executive will calculate the next appropriate date. Formatted as YYYYMMDD. The default is 0.

nextruntime

Specifies the time the task will be scheduled. If the current time is greater than the activestarttime, specifies the next time that the task will be scheduled: 0 indicates that the SQL Executive will calculate the next appropriate time. Formatted as HHMMSS. The default is 0.

runpriority

Specifies the thread priority level at which the subsystem event thread runs. The default is 0.

emailoperatorname

Specifies the e-mail name of the operator who will receive notifications.

retryattempts

Specifies the number of times the SQL Executive retries before issuing an error. The default is 0.

retrydelay

Specifies the SQL Executive the SQL Executive waits before retrying the task. The default is 1.

command

Specifies a command string (based on the valid specified subsystem commands) to be passed to the subsystem. If the specified subsystem is TSQL, the command cannot consist of more than one batch. The batch separator GO is not supported. The default is NULL.

loghistcompletionlevel

Specifies the level of events to capture in the event log, 1 captures all successfully run events, 2 captures only failed events.

emailcompletionlevel

Specifies the level of events to capture via e-mail, 1 captures all successfully run events, 2 captures only failed events. The default is 2.

description

Is text describing the task.

tagadditionalinfo

Reserved for future use.

tagobjectid

Reserved for future use.

tagobjecttype

Reserved for future use.

Remarks

All specified (non-NULL) parameters are updated. To clear a string, use ' '.

Examples

This example renames the auth_table_sync task to authors_sync.

sp_updatetask 'auth_table_sync', @name = 'authors_sync'

Permission

Only the system administrator can use this procedure.

Table Used

systasks

See Also

sp_droptask	sp_addtask


Stored Procedures-System Stored Procedures

SQL Server system stored procedures are provided for your convenience. They make it easy to retrieve information from the system tables, administer databases, and perform other tasks that involve updating system tables.

System stored procedures are created in the master database during installation and are owned by the system administrator. The names of all system stored procedures begin with sp_. All stored procedures for which documentation is provided are for regular system use. Additional stored procedures exist in the master database for internal use only. Although these procedures can be viewed and used as examples for writing your own procedures, they are not guaranteed to be included in future releases.

You can run system stored procedures from any database. If a system stored procedure is executed from a database other than master, any non-qualified references to system tables are mapped to the database from which the procedure is being run. For example, if the database owner of the pubs database runs sp_adduser from pubs, the new user is added to pubs..sysusers.

When the parameter for a system stored procedure is a reserved word or an object name and the object name is qualified by a database name or owner name, the entire name must be enclosed in single quotation marks.

Because system stored procedures are located in the master database, their permissions are also set there. Some system stored procedures can be run only by database owners. These procedures make sure that the user executing the procedure is the owner of the database from which the procedures are being executed.

Other system stored procedures can be executed by any user who has been granted EXECUTE permission on them. The EXECUTE permission must be granted in the master database.

•	A user can have permission to execute a system stored procedure either in all databases or in none of them.

•	The owner of a user database cannot directly control permissions on the system stored procedures within his or her own database.

The following sections detail the system stored procedures intended for regular use by the system administrator, the database owner, or all users.


sp_addalias System Stored Procedure

Maps one user to another in a database.

Syntax

sp_addalias login_id, username

where

login_id

Is the master.dbo.syslogins login ID of the user who wants an alternate identity in the current database. An alias allows a SQL Server user to be known in a database as another user. If the user with this login_id exists in the database's sysusers table, SQL Server won't find the user's alias identity, since it checks sysusers before checking sysalternates.

username

Specifies the database user with whom the first user will be linked. This name must exist in both master.dbo.syslogins and in the sysusers table of the current database.

Remarks

Executing sp_addalias maps one user (login_id) to another (login_id) in the current database. The mapping is shown in sysalternates, where the two users' suids are connected.

A report on any users mapped to a specified user can be generated with the sp_helpuser system stored procedure if you give the specified login ID as a parameter.

When a user tries to use a database, SQL Server checks sysusers to see if the login ID is listed there. If the login ID is not there, it then checks sysalternates. If an entry (the user's suid) is found there. and it is mapped to a database user's suid (altsuid in sysalternates table), the first user is treated as the second user while using the database.

There are three ways that a user can be authorized to use a database (assuming the user is listed in master.dbo.syslogins).

•	The user can be listed in the sysusers table of that database. (New database users are added by the database owner with the sp_adduser system stored procedure.)

•	The user can have an alias in the database, which has been added by the database owner with the sp_addalias system stored procedure.

•	The user can use the database as guest if there is a guest entry in the database's sysusers table.

Example

In this example, there is a user named Albert in the current database's sysusers table and a login ID for a user ID Victoria in master.dbo.syslogins. The sp_addalias system stored procedure allows Victoria to use the current database and to be known as Albert in that database.

sp_addalias Victoria, Albert

Permission

Execute permission defaults to the database owner.

Tables Used

master.dbo.syslogins, sysalternates, sysusers

See Also

sp_addlogin	sp_helpuser
sp_adduser	USE
sp_dropalias


sp_addextendedproc System Stored Procedure

Registers the name of a new extended stored procedure to SQL Server.

Syntax

sp_addextendedproc function_name, dll_name

where

function_name

Is the name of the function to call within the DLL.

dll_name

Is the name of the DLL containing the function.

Remarks

Programmers using Microsoft Open Data Services can create extended stored procedures. Once an extended stored procedure is created, it must be added to SQL Server by using sp_addextendedproc. For more information about creating extended stored procedures, see Microsoft SQL Server Programming Open Data Services.

To execute an extended stored procedure from a database other than the one to which it is added, you must qualify the name of the extended stored procedure with the name of the database to which it was added.

The sp_addextendedproc procedure 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.

Example

This example adds the xp_diskfree extended stored procedure.

sp_addextendedproc xp_diskfree

Permission

Only the system administrator can use this procedure.

Table Used

syscomments, sysobjects

See Also

EXECUTE	sp_dropextendedproc
GRANT	sp_helpextendedproc
REVOKE


sp_addgroup System Stored Procedure

Creates a group in the current database.

Syntax

sp_addgroup grpname

where

grpname

Is the name of the group to add. Group names must follow the rules for identifiers.

Remarks

Groups are used as collective names for granting and revoking permissions.

The sp_addgroup system stored procedure adds an entry for the new group to a database's sysusers table. Each group's uid is a number greater than or equal to 16,384 (except the uid of the public group, which is always 0).

Once a group has been created, you can use the group name as an optional parameter with the sp_adduser system stored procedure, which adds the new user to a group at the same time as it is created. To add an already existing user to a group, use the sp_changegroup system stored procedure.

A user can be a member of only one group. Every database is created with a public group. If a user is not explicitly added to another group, he or she is a member of the public group.

Example

This example creates an accounting group.

sp_addgroup accounting

Permission

Execute permission defaults to the database owner.

Table Used

sysusers

See Also

GRANT	sp_changegroup
REVOKE	sp_dropgroup
sp_adduser	sp_helpgroup


sp_addlogin System Stored Procedure

For more updated SQL Server 6.5 syntax, see sp_addlogin.

Creates a new SQL Server user by adding an entry to master.dbo.syslogins.

Syntax

sp_addlogin login_id [, passwd [, defdb [, deflanguage]]]

where

login_id

Is the login ID of the user. Login IDs must follow the rules for identifiers.

passwd

Is the user's password. If no password is specified, the default password is NULL (no password needs to be explicitly entered). After sp_addlogin has been executed, the password is encrypted and stored in the syslogins table.

defdb

Specifies the user's default database (the database the user is connected to after logging in). If no defdb is specified, the default is master.

deflanguage

Is the default language assigned when a user logs in to SQL Server. If no deflanguage is specified, the server's default language, defined by the configuration variable default language, is used.

Remarks

After sp_addlogin is executed, the user can log in to SQL Server.

When you are using integrated security, the presence or absence of a login ID determines if a user is uniquely known within SQL Server or is instead mapped to a default account, if one exists. If no default account and no login ID exists for a specific user, that user cannot log in.

The user can change his or her own password at any time by using the sp_password system stored procedure. The system administrator can change any user's password by using sp_password with NULL as the old password.

If the name of a default database is supplied (defdb), the user is connected to the specified database without the USE statement and without passing through master. However, the user cannot use the default database until given access to that database by its database owner (by using the sp_adduser or sp_addalias system stored procedure).

The user can change his or her own default database at any time by using the sp_defaultdb system stored procedure. The system administrator can change any user's default database by using sp_defaultdb.

The user can change his or her own default language at any by using the sp_defaultlanguage system stored procedure. The system administrator can change any user's default language by using sp_defaultlanguage.

Examples

A.	Create a Login ID

This example creates a SQL Server login for the login ID Victoria. Since the passwd and defdb parameters are not included, Victoria's password is NULL and her default database is master.

sp_addlogin Victoria

B.	Create a Login ID and Default Database

This example creates a SQL Server login identification number for the user Albert. His password is food and his default database is corporate.

sp_addlogin Albert, food, corporate

C.	Create a Login ID with a Different Default Language

This example creates a SQL Server login for Claire. Her password is caniche, her default database is public_db, and her default language is French.

sp_addlogin Claire, caniche, public_db, french

Permission

Only the system administrator can use this stored procedure.

Tables Used

master.dbo.sysdatabases, master.dbo.syslogins, master.dbo.syslanguages

See Also

sp_addalias	sp_helpuser
sp_adduser	sp_password
sp_defaultdb	xp_grantlogin
sp_defaultlanguage	xp_logininfo
sp_droplogin	xp_revokelogin


sp_addmessage System Stored Procedure

Adds a new error message to the sysmessages table.

Syntax

sp_addmessage msg_id, severity, 'text of message'
[, language [, WITH_LOG [, REPLACE]]]

where

msg_id

Is the ID of the message. It must be an integer. Acceptable values for user-defined error messages start with 50001. The msg_id must be unique; an error will be returned if that ID already exists. By default, any message added will have the language ID (@@langid) of the connection adding the message. To add a message for a different language, first use the SET LANGUAGE statement.

severity

Represents the severity level of the error. Valid levels are 1 through 25. Only the system administrator can add a message with a severity level of 19 through 25. For details on severity levels and use, see the Microsoft SQL Server Administrator's Companion.

text of message

Is the text of the error message. The string can have as many as 255 characters and must be surrounded by single quotation marks.

language

Specifies the language for this message. Because multiple languages can be installed on the same server, language specifies in which language each message is written. When not specified, U.S. English is the default language.

WITH_LOG

Specifies that the sysmessages is to be written to the Windows NT event log when it occurs.

Note  If a message is written to the Windows NT event log, it is also written to the SQL Server error log file.

REPLACE

Is optionally used to overwrite an existing error message with new message text and severity level. This option must be specified if the msg_id already exists.

Remarks

If no parameters are supplied, a syntax diagram will be displayed.

Example

This example adds an informational message to sysmessages.

sp_addmessage 50001, 16, 'Percentage expects a value between 20 and 100. Please re-execute with a more appropriate value.'

Permission

Execute permission defaults to the system administrator, who can grant execute permission to other users.

Tables Used

sysmessages

See Also

CREATE TABLE	sp_altermessage
RAISERROR	sp_dropmessage


sp_addremotelogin System Stored Procedure

Adds a new remote login ID to master.dbo.sysremotelogins.

Syntax

sp_addremotelogin remoteserver [, login_ID [, remotename]]

where

remoteserver

Is the name of the remote server to which the remote login applies. The server must be known to the local server by an entry in the master.dbo.sysservers table.

login_ID

Is the login ID of the user on the local SQL Server. The user named by login_ID must already exist in the master.dbo.syslogins table. Use the sp_addserver system stored procedure to add a remote server.

remotename

Is the ID used by the remote server when logging in to the local server. All remote logins not explicitly matched to a local ID are automatically mapped to a local ID.

Remarks

When a server receives a remote login, the local server tries three ways to map the remote user to a local user. First, the local server looks for an entry in the sysremotelogins table that matches the remote server name and the remote login ID. If one is found, then the local server's user ID (suid) for that row logs in the remote user. If no entry is found, the local server searches for an entry with a value of NULL in the remoteusername column and a local server's user ID that is not −1. In this case, the remote user is mapped to the local server's user ID. Finally, if the previous attempts failed, the local server checks the sysremotelogins table for an entry with a remote name of NULL and a local server's user ID of −1. In this case, the remote login ID supplied by the remote server looks for a local server's user ID in the syslogins table.

The login ID of the local user may be different on the remote server.

Every remote login entry has a status. The default status is not trusted. This means that when a remote login with not trusted status is received, SQL Server checks the password. If you don't want the password to be checked, change the status to trusted by using the sp_remoteoption system stored procedure.

Examples

A.	Map One to One

This example shows a simple way to map remote names to local names when the local and remote servers have the same users. It creates an entry in the sysremotelogins table so that the remote server ACCOUNTS can validate logins. When no login parameters are given, a null value is entered in the remoteusername column of sysremotelogins.

sp_addremotelogin ACCOUNTS

B.	Map Many to One

This example creates an entry that maps all users from the remote server ACCOUNTS to a local login ID Albert.

sp_addremotelogin ACCOUNTS, Albert

C.	Explicit One-to-One Mapping

This example causes a remote login from the remote user Chris on the remote server ACCOUNTS to be mapped to the local user salesmgr.

sp_addremotelogin ACCOUNTS, salesmgr, Chris

Permission

Only the system administrator can execute this procedure.

See Also

sp_addlogin	sp_helpremotelogin
sp_addserver	sp_helpserver
sp_dropremotelogin	sp_remoteoption


sp_addsegment System Stored Procedure

Defines a segment on a database device in the current database.

Syntax

sp_addsegment segname, logical_name

where

segname

Is the name of the new segment, which is added to the syssegments table of the current database. Segment names must be unique in each database.

logical_name

Specifies the database device where segname will be located. A database device can have more than one segment associated with it.

Remarks

The sp_addsegment system stored procedure defines segment names for database devices that have been assigned to a specific database with the ALTER DATABASE or CREATE DATABASE statement. The maximum number of segments for any database is 32. Segments are named subsets of a database defined per device. Before you can use segment procedures in a database, make the database the current one by issuing the USE database statement.

Once a segment has been defined, it can be used with the CREATE TABLE statement, the CREATE INDEX statement, and in the sp_placeobject system stored procedure, which puts data for a table or index on the segment. When a table or index is created on a particular segment, all subsequent data for the table or index is put on that segment.

To extend the range of a segment to another database device used by the same database, use the sp_extendsegment system stored procedure.

If a database is extended with the ALTER DATABASE statement on a device used by that database, the segments mapped to that device are also extended.

The SYSTEM and DEFAULT segments are mapped to each database device included in a CREATE DATABASE  or ALTER DATABASE statement. The LOGSEGMENT is also mapped to each device, unless it is put on a separate device by using the LOG ON extension to the CREATE DATABASE statement or by using the sp_logdevice system stored procedure. To unmap these segments, use the sp_dropsegment system stored procedure. For more information, see the Microsoft SQL Server Administrator's Companion.

Example

This example creates a segment named INDEXES on the database device named DEV1.

sp_addsegment indexes, dev1

Permission

Execute permission defaults to the system administrator and the database owner.

Tables Used

syssegments, master.dbo.sysusages, master.dbo.sysdevices

See Also

ALTER DATABASE	sp_extendsegment
CREATE INDEX	sp_helpdb
CREATE TABLE	sp_helpdevice
DISK INIT	sp_placeobject
sp_dropsegment


sp_addserver System Stored Procedure

Defines a remote server or the name of the local server.

Syntax

sp_addserver server_name [, LOCAL]

where

server_name

Is the name of the new server, which is added to the master.dbo.sysservers table. Server names must be unique and must conform to the rules for identifiers.

LOCAL

Is an optional parameter that identifies the server being added as the local server. This parameter sets the value of the global variable @@SERVERNAME. (The setup program sets this variable to the computer name during installation. It is recommended that you do not change the name to something other than the computer name because the computer name is how users connect to SQL Server by default without the need for additional configuration). The local definition takes effect only after the server is shut down and restarted.

Remarks

To execute a stored procedure on a remote server, the remote server must be added to the sysservers table.

To set or clean server options, use the sp_serveroption system stored procedure .

Example

This example creates an entry for a remote server named ACCOUNTS in the local master.dbo.sysservers table.

sp_addserver ACCOUNTS

Permission

Execute permission defaults to the system administrator and the database owner.

Table Used

master.dbo.sysservers

See Also

sp_addremotelogin	sp_helpremotelogin
sp_dropremotelogin	sp_helpserver
sp_dropserver	sp_serveroption


sp_addtype System Stored Procedure

Creates a user-defined datatype. Executing sp_addtype creates a user-defined datatype and adds it to the systypes system table. Once a user datatype is created, you can use it in the CREATE TABLE and ALTER TABLE statements, as well as bind defaults and rules to it.

Syntax

sp_addtype typename, phystype [, nulltype]

where

typename

Names the user datatype. Datatype names must follow the rules for identifiers and must be unique in each database.

phystype

Is the physical, or SQL Server − supplied, type (char, int, and so on) on which the user datatype is based. For details on available datatypes, see the Datatypes topic. (Quotation marks are required around all parameters that have embedded blank spaces or punctuation marks. For example, 'char(10)'.)

nulltype

Indicates how the user-defined datatype handles null value entries. Can be NULL or NOT NULL. The default nullability, if not explicitly defined is NOT NULL. Nullability should be explicitly defined.

Note  Remember that datatype nullability only defines the default nullability for this datatype. If nullability is explicitly defined when the user-defined datatype is used during table creation, it will take precedence over the defined nullability. For details, see the ALTER TABLE and CREATE TABLE statements.

Remarks

Define each user datatype in terms of one of the physical (SQL Server − supplied) datatypes, preferably specifying NULL (allow null entries) or NOT NULL (disallow them). A user-defined datatype name must be unique in the database, but user-defined datatypes with different names can have the same definition.

Examples

A.	Datatype That Does Not Allow Null Values

This example creates a user-defined datatype named ssn to be used for columns that hold social security numbers.

Notice that varchar(11) is enclosed in single quotation marks because it contains punctuation (parentheses).

sp_addtype ssn, 'VARCHAR(11)', NOT NULL

B.	Datatype That Allows Null Values

This example creates a user-defined datatype (based on datetime) named birthday that allows null values.

sp_addtype birthday, datetime, NULL

Permission

Execute permission defaults to the public group.

Table Used

See Also

CREATE DEFAULT	sp_droptype
CREATE RULE	sp_rename
CREATE TABLE	sp_unbindefault
sp_bindefault	sp_unbindrule
sp_bindrule


sp_addumpdevice System Stored Procedure

Adds a dump device to SQL Server.

Syntax

sp_addumpdevice {'disk' | 'diskette' | 'tape'}, 'logical_name',
'physical_name' [, {{cntrltype [, noskip | skip [, media_capacity]]} |
{@@devstatus = {noskip | skip}}}]

where

disk | diskette | tape

Specifies the type of dump device. Use disk to add a hard disk file as a dump device. Use diskette to add a 5.25-inch or 3.5-inch diskette drive file as a dump device. Use tape for any tape devices supported by Windows NT. Enclose these options in single quotation marks.

logical_name

Is the logical name of the dump device used in the LOAD and DUMP statements. This name must follow the rules for identifiers.

physical_name

Is the physical name of the dump device. Physical names must follow the rules for operating-system filenames or universal naming conventions for network devices and must include a full path.

When creating a dump device on a remote network location, be sure that the name under which the 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 non-alphanumeric characters in quotation marks.

cntrltype

Is not required when creating dump devices. However, if used in scripts, it is still acceptable to supply this parameter, but SQL Server ignores it.

Note  As of SQL Server version 4.2, sp_addumpdevice no longer uses the cntrltype or media_capacity parameters because SQL Server automatically detects the control type and media capacity information. In this release of SQL Server, the syntax is still supported; however, both parameters will be removed in a future release.

skip | noskip

Indicates whether ANSI tape labels are read (noskip) or ignored (skip). For example, when skip is specified and the ANSI label of a tape warns that it has expired or that you don't have permission to write to it, SQL Server ignores the warning. Or, if the tape you are writing to is new (and therefore has no ANSI label), SQL Server writes a new label on the first try. The skip option prevents unnecessary retries as SQL Server tries to find a label.

Specifying noskip tells SQL Server to read existing ANSI tape labels on the tape to which you are writing. Use noskip for diskette dump devices.

The sp_addumpdevice system stored procedure lets you choose between the security of paying attention to ANSI labels or the convenience of ignoring them. In either case, SQL Server still reads/writes the labels.

media_capacity

Is not required when creating dump devices. However, if used in scripts, it is still acceptable to supply this parameter, but SQL Server ignores it. For more information, see contrltype, above.

@@devstatus = skip | noskip

Explicitly defines whether ANSI tape labels are read (noskip) or ignored (skip). Use this local variable when you do not explicitly use the ctrltype or media_capacity parameters.

Remarks

The sp_addumpdevice system stored procedure adds a dump device to the master.dbo.sysdevices table. It can then be referred to logically in the DUMP, DUMP TRANSACTION, and LOAD statements.

Ownership and permission problems can interfere with the use of disk or file dump 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 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). If you are using a non−computer-grade tape, SQL Server backups are restricted to a single tape (a database dump that spans multiple tapes is not allowed).

Examples

A.	Disk Dump Device

This example adds a disk device named MYDISKDUMP, with the physical name C:\DUMP\DUMP1.DAT.

sp_addumpdevice 'disk', 'mydiskdump', 'c:\dump\dump1.dat'

B.	Network Disk Dump Device

This example shows a remote disk device dump. The name under which SQL Server was started must have permissions to that remote file.

sp_addumpdevice 'disk', 'networkdevice',

'\\servername\sharename\path\filename.ext'

C.	Tape Dump Device

This example adds the TAPEDUMP1 device with the physical name \\.\TAPE0.

sp_addumpdevice 'tape', 'tapedump1',

'\\.\tape0'

Permission

Execute permission defaults to the system administrator.

Table Used

master.dbo.sysdevices

See Also

DISK INIT	sp_dropdevice
DUMP	sp_helpdevice
LOAD


sp_adduser System Stored Procedure

Adds a new user to the current database.

Syntax

sp_adduser login_id [, username [, grpname]]

where

login_id

Is the user's login ID as found in the name column of master.dbo.syslogins.

username

Specifies a name for this user in the current database. Omitting this parameter causes the username to default to the user's login ID.

grpname

Identifies an existing group in the database. If you don't specify a group, the user becomes a member of the default group public. If you want to add a user to a group, you must supply a value for the username parameter. (The username can be the same as login_id.)

A user can be a member of only one group. Every user is a member of the default group, public, unless he or she has been explicitly added to some other group with the sp_adduser or sp_changegroup system stored procedure. The group must already exist in the database.

Remarks

The sp_adduser system stored procedure treats the combination of a guest login ID and user guest as a special case. In earlier releases, a non-special guest user could be created within a user-defined database. SQL Server 6.0 prevents this from happening, in the following way:

•	If a login name of guest is specified with the sp_adduser system stored procedure and a guest login exists and the username is not specified as guest, a user with the suid of the login name guest will be added.

sp_adduser guest, dbuser1

•	If the username guest is specified and the login name specified is not guest, an error message is returned, stating the guest user cannot be mapped to a login.

sp_adduser loginid1, guest

•	If a login name of guest is specified and the username specified is guest or not supplied, then the user created within the database will be the special guest user. If the guest user already exists, an error message will be returned.

sp_adduser guest, guest

The database owner executes the sp_adduser system stored procedure to add a login ID to the sysusers table of the current database, enabling the user to access the current database under his or her own name.

Specifying a username parameter gives the new user a name in the database different from his or her login ID on SQL Server. The ability to assign a different name to a user on SQL Server and in a database is provided as a convenience. This is not an alias as provided by the sp_addalias system stored procedure— the user is simply given a different name, not mapped to the identity and permissions of another user as with sp_addalias.

To access a database, a user must be listed in sysusers (by using sp_adduser) or mapped to another user in sysalternates (by using sp_addalias), or there must be a guest entry in sysusers.

Examples

A.	Add a User

The SQL Server login ID Victoria has already been added to SQL Server with sp_addlogin. This example adds Victoria to the database. Victoria will be known in the current database by the username Victoria and belong to the group fort_mudge (previously created with sp_addgroup).

sp_adduser Victoria, Victoria, fort_mudge

B.	Add a Username with the Same Login ID

This example adds Margaret to the database. Her database username is the same as her SQL Server login ID, and she belongs to the default group public.

sp_adduser Margaret

C.	Add a User Who Uses a Different Username

This example adds Haroldq to the database. When Haroldq uses the current database, his name is Harold. He belongs to the fort_mudge group.

sp_adduser Haroldq, Harold, fort_mudge

Permission

Execute permission defaults to the database owner.

Tables Used

master.dbo.syslogins, sysalternates, sysusers

See Also

GRANT	sp_dropgroup
REVOKE	sp_helpuser
sp_addalias	USE
sp_addgroup	xp_grantlogin
sp_changegroup	xp_logininfo
sp_dropalias	xp_revokelogin


sp_altermessage Stored Procedure
sp_altermessage System Stored Procedure

Alters the state of a sysmessages error.

Syntax

sp_altermessage message_id, WITH_LOG, {true | false}

where

message_id

Specifies which sysmessages error or message to alter.

WITH_LOG

Specifies that the sysmessages is to be written to the Windows NT event log when it occurs.

Note  If a message is written to the Windows NT event log, it is also written to the SQL Server error log file.

true | false

Specifies whether the error will be written to the Windows NT event log. If true, the error will be automatically written to the Windows NT event log. If false, the error will not be automatically written to the Windows NT event log but may be written, depending on how the error was raised.

Remarks

The effect of the sp_altermessage system stored procedure 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, then no matter how a user invokes the error it will always be written to the Windows NT event log. Even if RAISERROR is executed without the WITH LOG option, the error will be written to the Windows NT event log.

System messages (such as 605), as well as user messages added by sp_addmessage, can be modified by using sp_altermessage.

Example

This example causes existing message 55001 to be logged to the Windows NT event log.

sp_altermessage 55001, WITH_LOG, TRUE

Permission

Execute permission defaults to the system administrator and can be transferred to other users.

Table Used

sysmessages

See Also

sp_addmessage	sp_dropmessage


sp_bindefault System Stored Procedure

Binds a default to a column or to a user-defined datatype.

Syntax

sp_bindefault defname, objname [, futureonly]

where

defname

Is the name of the default created by the CREATE DEFAULT statement.

objname

Specifies the table and column or the user-defined datatype to which the default is to be bound. If objname is not of the form 'table.column', it is assumed to be a user-defined datatype. (Quotation marks are required around all system stored procedure parameters that have embedded blanks or punctuation.) By default, existing columns of the user-defined datatype inherit the default defname unless a default has been bound directly to the column. A default cannot be bound to a column of type timestamp or a column with the IDENTITY property.

futureonly

Used only when binding a default to a user-defined datatype, this option prevents existing columns of that datatype from inheriting the new default. It is never used when binding a default to a column. If futureonly is specified, any existing default bound to that datatype will be explicitly bound to any existing columns of that datatype that do not already have a default bound to them.

Remarks

First use the CREATE DEFAULT statement to create a default. Then execute the sp_bindefault system stored procedure to bind the default to a column or to a user-defined datatype in the current database. You can bind a new default to a column or to a user-defined datatype with sp_bindefault without unbinding an existing default. The old default is overridden. You cannot bind a default to a SQL Server − supplied datatype.

Existing columns of the user-defined datatype inherit the new default unless they have a default bound directly to them or unless the futureonly option is used. New columns of the user-defined datatype always inherit the default.

The default must be compatible with the datatype of the column. For example, you cannot use "N/A" as a default for a numeric column. If the default is not compatible with the column to which you've bound it, SQL Server returns an error message when it tries to insert the default value (not when you bind it). You cannot bind a default to a column that already has a DEFAULT constraint.

When you bind a default to a column, information is added to the syscolumns table. When you bind a default to a user-defined datatype, information is added to the systypes table.

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 startdate column of the employees table. Whenever a row is added to the employees table and data for the startdate column is not supplied, the column gets the value of the default today.

sp_bindefault today, 'employees.startdate'

B.	Bind a Default to a User-defined Datatype

Assuming that a default named def_ssn and a user-defined datatype named ssn exist, this example binds the default def_ssn to the ssn user-defined datatype. The default is inherited by all columns that are assigned the user-defined datatype ssn when a table is created. Existing columns of type ssn also inherit the default def_ssn unless you specify futureonly (which prevents existing columns of that user-defined datatype from inheriting the default), or unless the column has a default bound directly to it. Defaults bound to columns always take precedence over those bound to datatypes.

sp_bindefault def_ssn, ssn

C.	FUTUREONLY

This example binds the default def_ssn to the user-defined datatype ssn. Because futureonly is specified, no existing columns of type ssn are affected.

sp_bindefault def_ssn, ssn, FUTUREONLY

Permission

Execute permission defaults to the object owner.

Tables Used

syscolumns, sysobjects, systypes

See Also

CREATE DEFAULT	sp_unbindefault
DROP DEFAULT


sp_bindrule System Stored Procedure

Binds a rule to a column or to a user-defined datatype.

Syntax

sp_bindrule rulename, objname [, futureonly]

where

rulename

Is the name of a rule created by the CREATE RULE statement.

objname

Specifies the table and column or the user-defined datatype to which the rule is to be bound. If objname is not of the form 'table.column', it is assumed to be a user-defined datatype. (Quotation marks are required around all system stored procedure parameters that have embedded blanks or punctuation.) By default, existing columns of the user-defined datatype inherit the rule rulename unless a rule has been bound directly to the column.

futureonly

Used only when binding a rule to a user-defined datatype, this option prevents existing columns of a user-defined datatype from inheriting the new rule. If futureonly is specified, any existing rule bound to that datatype will be explicitly bound to any existing columns of that datatype that do not already have a rule bound to them.

Remarks

First use the CREATE RULE statement to create a rule. Then execute the sp_bindrule system stored procedure to bind it to a column or to a user-defined datatype in the current database. You can bind a new rule to a column (although using a CHECK constraint is preferred) or to a user-defined datatype 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 SQL Server − supplied datatype.

The rule is enforced when an INSERT is attempted, not at binding. You can bind a character rule to a column of numeric datatype, even though such an INSERT is illegal.

Existing columns of the user-defined datatype inherit the new rule unless they have a rule bound directly to them or the futureonly option is used. New columns of the user-defined datatype always inherit the rule.

When you bind a rule to a column, information is added to the syscolumns table. When you bind a rule to a user-defined datatype, information is added to the systypes table.

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 startdate column of the employees table. When a row is added to employees, the data for the startdate column is checked against the today rule.

sp_bindrule today, 'employees.startdate'

B.	Bind a Rule to a User-defined Datatype

Assuming the existence of a rule named rule_ssn and a user-defined datatype 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 you specify the futureonly option (which prevents existing columns of type ssn from inheriting the rule) or ssn has a rule bound directly to it. Rules bound to columns always take precedence over those bound to datatypes.

sp_bindrule rule_ssn, ssn

C.	FUTUREONLY

This example binds the rule_ssn rule to the user-defined datatype ssn. Because futureonly is specified, no existing columns of type ssn are affected.

sp_bindrule rule_ssn, ssn, FUTUREONLY

Permission

Execute permission defaults to the object owner.

Tables Used

syscolumns, sysobjects, systypes

See Also

CREATE RULE	sp_unbindrule
DROP RULE


sp_certify_removable System Stored Procedure

For more updated SQL Server 6.5 syntax, see sp_certify_removable.

Verifies that a database is configured properly for distribution on removable media.

Syntax

sp_certify_removable dbname[, AUTO]

where

dbname

Specifies the database to be verified.

AUTO

As necessary, gives ownership of the database and all database objects to the system administrator, and drops any user-created database users and any non-default permissions.

Remarks

If the database is configured properly, the sp_certify_removable system stored procedure sets the database offline and returns information that will be required when the database is later installed using sp_dbinstall. It truncates the transaction log, moves it to the system device, and drops the log device. It returns the physical and logical names and the size, in megabytes, of the system device and the data device(s). Make a note of this information and provide it—along with the distribution disk—to users who will be installing the distributed database.

The system administrator must be owner of the database and all database objects because the system administrator is a known user that exists on all SQL Servers and can be counted on to exist when the database is later distributed and installed.

If you run sp_certify_removable without the AUTO option 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 non-default permissions have been granted, you have two ways to correct those conditions:

•	You can use SQL Server tools and procedures, and then run sp_certify_removable again.

•	You can simply run sp_certify_removable with the AUTO option.

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 information, see the GRANT statement.

Example

This example certifies that the inventory database is ready to be removed.

sp_certify_removable inventory, AUTO

Permission

Only the system administrator can use this stored procedure.

See also

sp_create_removable	sp_dboption
sp_dbinstall	sp_dbremove.


sp_changedbowner System Stored Procedure

Changes the owner of a database.

Syntax

sp_changedbowner login_id [, true]

where

login_id

Is the login ID of the new owner of the current database. The new owner must not already be known as a user or an alias (that is, the new owner must not already be listed in sysusers or sysalternates). Executing sp_changedbowner with the single parameter login_id changes the database ownership to the login_id and drops the aliases of users who could act as the old database owner.

true

Transfers aliases and their permissions to the new database owner.

Remarks

The sp_changedbowner system stored procedure makes login_id the owner of the current database.

The new database owner must already have a login ID on SQL Server but must not have a database name or alias name in the current database. To assign database ownership to such a user, drop the user's database name and alias entries before executing sp_changedbowner.

After the sp_changedbowner system stored procedure is executed, the new owner is known as the database owner inside the database.

To grant permissions to a user who is the new owner, the system administrator must grant the permissions to the database owner, because the user is known inside the database only by that other name.

Example

This example makes the user Albert the owner of the current database.

sp_changedbowner Albert

Permission

Only the system administrator can execute this procedure.

Tables Used

master.dbo.sysdatabases, master.dbo.syslogins, sysalternates, sysusers

See Also

CREATE DATABASE	sp_dropuser
sp_addlogin	sp_helpdb
sp_dropalias


sp_changegroup System Stored Procedure

Changes a user's group.

Syntax

sp_changegroup grpname, username

where

grpname

Is the name of a group that already exists in the current database.

username

Specifies which user to add to the group. The user must already exist in the current database.

Remarks

Groups provide a collective name that is used when granting and revoking permissions. A user can be a member of only one group.

The sp_changegroup system stored procedure adds the specified user to the specified group. The user is dropped from the group he or she belongs to and is added to the one specified by grpname. If you use public as the grpname parameter, it must be enclosed in quotation marks because PUBLIC is an SQL keyword.

New database users can be added to groups at the same time as they are given access to the database by sp_adduser.

Every user is a member of the default group public, if not explicitly added to some other group by sp_adduser or sp_changegroup.

Example

This example makes Albert a member of the developers group. It doesn't matter which group Albert belonged to before.

sp_changegroup developers, Albert

Permission

Execute permission defaults to the database owner.

Table Used

sysusers

See Also

GRANT	sp_adduser
REVOKE	sp_dropgroup
sp_addgroup	sp_helpgroup


sp_configure System Stored Procedure

For more updated SQL Server 6.5 syntax, see sp_configure.

Displays or changes configuration options.

Syntax

sp_configure [config_name [, config_value]]

where

config_name

Specifies a configuration option. SQL Server understands any unique string that is part of the configuration name. This parameter must be enclosed in quotation marks if it contains embedded blanks or is a keyword.

config_value

Is the value for the configuration option.

Remarks

All users can execute the sp_configure system stored procedure with no parameters (SQL Server displays a list of all configuration options and their current values) or with config_name (SQL Server displays the current value for the specified configuration option).

Only the system administrator can execute sp_configure with both parameters and change the configuration option value. After using sp_configure, the system administrator must execute the RECONFIGURE statement to install the changed value. Dynamic options take effect immediately after the RECONFIGURE statement has been run. For all non-dynamic options, SQL Server must be stopped and restarted before the options can take effect. For details, see the RECONFIGURE statement.

The information returned by sp_configure, when executed with no parameters, shows a config_value column and a run_value column. The config_value column contains the value to which the configuration option was set with sp_configure (the value in sysconfigures.value). The run_value column contains the value for that option (the value in syscurconfigs.value) for SQL Server. These values 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 non-dynamic options).

The run_value column contains the value that SQL Server is using. This value changes for dynamic configuration options (listed in the Configuration Option Overview and marked with an asterisk) after the system administrator runs the RECONFIGURE statement. This value specifies changes for static configuration options after you shut down and restart SQL Server. This is the value in syscurconfigs.value.


Configuration Option Overview

Many configuration options are often considered advanced and should be changed only under very special and often rare circumstances. In the following table, advanced options are shown in bold type; dynamic options are marked with an asterisk (*).

config_name	Minimum	Maximum	config_value	run_value
allow updates*	0	1	0	0
backup buffer size*	1	10	1	1
backup threads	0	32	5	5
cursor threshold*	−1	2147483647	100	100
database size	1	10000	2	2
default language	0	9999	0	0
default sortorder id	0	255	52	52
fill factor	0	100	0	0
free buffers*	20	524288	204	204
hash buckets	4999	265003	7993	7993
language in cache	3	100	3	3
LE threshold maximum*	2	500000	200	200
LE threshold minimum*	2	500000	20	20
LE threshold percent*	1	100	0	0
locks	5000	2147483647	5000	5000
logwrite sleep (ms)*	−1	500	0	0
max async IO	1	255	8	8
max lazywrite IO*	1	255	8	8
max worker threads*	10	1024	255	255
media retention	0	365	0	0
memory	1000	1048576	4096	4096
nested triggers*	0	1	1	1
network packet size*	512	32767	4096	4096
open databases	5	32767	20	20
open objects	100	2147483647	500	500
priority boost	0	1	0	0
procedure cache	1	99	30	30
RA cache hit limit*	1	255	4	4
RA cache miss limit*	1	255	3	3
RA delay*	0	500	15	15
RA pre-fetches*	1	1000	3	3
RA slots per thread	1	255	5	5
RA worker threads	0	255	3	3
recovery flags	0	1	0	0
recovery interval*	1	32767	5	5
remote access	0	1	1	1
remote login timeout*	0	2147483647	5	5
remote query timeout*	0	2147483647	0	0
remote sites*	0	256	(null)	10
set working set size	0	1	0	0
show advanced option*	0	1	1	1
SMP concurrency	−1	64	0	1
sort pages*	64	511	64	64
spin counter*	1	2147483647	10000	10
tempdb in ram (MB)	0	2044	0	0
time slice	50	1000	(null)	100
user connections	5	32767	20	20
Advanced options are displayed only when "show advanced option" is set to 1 (the default is 0).


Configuration Option Details

Many configuration options can be grouped and are often changed together.

In the following listings, advanced configuration options are noted in bold type and dynamic options are marked with an asterisk (*).

allow updates*

Specifies whether or not direct updates are allowed against system tables. Can be on (1) or off (0). By default, this option is off (0); system tables can be updated only through system procedures, not through ad hoc updates.

When allow updates is on (1), any user who has appropriate permissions can update the system tables directly with ad hoc updates and can create stored procedures that update the system tables.

Important  Allowing direct updates to the system tables is risky. Updating certain fields in the system tables can prevent SQL Server from running. Stored procedures created while allow updates is on (1) will always be able to update the system tables, even after the option has been turned off.

Because the system tables are critical, it is best to turn on this option only in tightly controlled situations. To guarantee that no other users can access SQL Server while the system tables can be directly updated, restart SQL Server from the Win32 command prompt with the /m option. For more information, see the sqlservr Command-line Executable.

This command starts SQL Server in a single-user mode, which allows only one system administrator to log in and turns on the allow updates configuration option.

The allow updates option is a dynamic option, which means that a new value takes effect as soon as you use the RECONFIGURE WITH OVERRIDE statement. As an added protection, the WITH OVERRIDE clause is always required for this configuration option.

backup buffer size*

Specifies the size of the dump and load buffer (used to increase backup speed). This value determines the size, in 32-page increments, of the backup buffer. For example, a backup buffer size of 5 means that a buffer of 160 pages (5 * 32 pages) will be created. This option, when reconfigured, takes effect immediately.

backup threads

Specifies the number of threads to be reserved for striped dump and load operations. A value of 0 turns off striped dumps. This option does not take effect until the server is stopped and restarted.

cursor threshold*

Specifies the value where keyset generation occurs asynchronously. When cursors generate a keyset for a results set, the optimizer estimates the number of rows that will be returned by that results set. If the optimizer estimates that the number of returned rows is greater than this threshold, the cursor is generated asynchronously. Otherwise, the cursor is generated synchronously. When set to −1, all keysets are generated synchronously. If the cursor threshold is set to 0, all keysets will be generated asynchronously. Normally you would not want to set this value too low, as small results sets are faster to build synchronously.

The accuracy of the optimizer to determine an estimate for the number of rows in a keyset depends on the currency of the statistics for each of the tables in the cursor. For more information on updating table statistics, see the DBCC and the UPDATE STATISTICS statements.

database size

Sets the default number of megabytes allocated to each new user database. The default is 2 MB; however, the minimum allowable database size is 1 MB, which allows databases to exist on removable media such as floppy disks. A database size specified in a CREATE DATABASE statement takes precedence over the value set by this configuration option.

If most of the new databases on your SQL Server require more than 2 MB, you might want to increase this value. You also must increase it if your model database grows larger than 2 MB, because the CREATE DATABASE statement causes SQL Server to copy model when creating a new user database.

Note  The model database is 1 MB by default.

default language

Specifies the ID of the language that is used by the server to display system messages, unless a user has chosen another language from those available on the server. The language us_english always has an ID of 0. Additional languages are assigned unique numbers when they are added.

default sortorder id

Specifies the number of the sort order currently installed as the default on the server.

Note  Do not use the sp_configure system stored procedure to change sort orders. For more information about changing sort orders, see the Microsoft SQL Server Administrators Companion.

fill factor

Determines how full SQL Server makes each page when it is creating a new index on existing data (unless the user specifies some other value using the CREATE INDEX statement). The fill factor percentage affects performance because SQL Server must take time to split pages when they fill up.

The fill factor percentage is used only at the time the index is created and becomes less important as changes to the data are made. The pages are not maintained at any particular level of fullness.

The default for this configuration option is 0; legal values range from 0 through 100. A fill factor of 0 does not mean that pages are 0 percent full. It is treated similarly to a fill factor of 100 in that SQL Server creates clustered indexes with full data pages and nonclustered indexes with full leaf pages. It is different from 100 in that SQL Server leaves a space within the index B-tree. There is seldom a reason to change the default fill factor, especially since you can override it with the CREATE INDEX statement.

If fill factor is set to 100, SQL Server creates both clustered and nonclustered indexes with each page 100 percent full. A fill factor of 100 makes sense only for read-only tables — tables to which no additional data will ever be added.

Smaller fill factor values cause SQL Server to create new indexes with pages that are not full. For example, a fill factor of 10 is a reasonable choice if you are creating an index on a table that you know contains only a small portion of the data that it will eventually hold. Smaller fill factor values cause each index to take more storage space.

free buffers*

Determines the threshold of free buffers available to the system. The minimum value is 20 and the maximum value is equal to one-half the number of buffers available when the server is started. The lazy writer process ensures that the number of free buffers available to the system does not fall below this threshold.

This option is automatically changed by the system whenever the memory option is changed; free buffers will be equal to 5 percent of the available memory. After the memory option is changed, a message will be displayed describing the change to free buffers. After this change, free buffers can be manually reconfigured to any legal value.

hash buckets

Sets the number of buckets used for hashing pages to buffers in memory. If the value specified is not a prime number, the closest prime number is used. For example, specifying 8000 creates 7993 hash buckets (the default). On systems with a large amount of memory, this value can be increased to allow faster access to data residing in data cache. For systems with 160 MB or less, 7993 is an appropriate value. This option does not take effect until the server is stopped and restarted.

language in cache

Indicates the maximum number of languages that can be simultaneously held in the language cache. The default is 3.

Lock Escalation Options

Many configuration options can be grouped and are often changed together.

When queries request a large number of rows from a particular table or tables, SQL Server generates page-level locks. If a query requests a large percentage of the rows from the table (see LE threshold percent), then lock escalation will occur. This makes table scans and operations against a large results set more efficient. The lock escalation options are:

•	LE threshold maximum*

•	LE threshold minimum*

•	LE threshold percent*

LE threshold maximum*

Determines the maximum number of page locks to hold before escalating to a table lock. If the number of page locks is greater than the escalation maximum, a table lock will occur regardless of whether or not the LE threshold percent has been exceeded. The default is 200.

LE threshold minimum*

Determines the minimum number of page locks required before escalating to a table lock. A table lock will occur only if this minimum is reached when the LE threshold percent is exceeded. LE threshold minimum prevents the server from escalating to a table lock for small tables where the LE threshold percentage is reached quickly. The default is 20.

LE threshold percent*

Specifies the percentage of page locks needed on a table before a table lock is requested. The default (0) causes a table lock to occur only when the LE threshold maximum has been reached.

Note  To override these values for a given request, see the optimizer_hints option with the SELECT statement. The HOLDLOCK table lock options include UPDLOCK, TABLOCK, TABLOCKX, and PAGLOCK.

locks

Sets the number of available locks. Locks are not shared the way open databases and database objects are shared. The default is 5000.

Increase this value if SQL Server displays a message saying that you have exceeded the number of available locks. Since each lock consumes memory (32 bytes per lock), increasing this value can make it necessary to increase the amount of memory dedicated to the server.

logwrite sleep (ms)*

Specifies the number of milliseconds that a write to the log will be delayed if the buffer is not full. This increases the chance that more data will be added to the log buffer by other users, so that fewer physical log writes will be needed. Acceptable values for this option are −1 through 500. The special value of −1 means that the log write will not be delayed. The default is 0, which causes the server to wait only if other users are ready to execute.

max async IO

Configures the number of asynchronous I/Os that can be issued. The default is 8. This value should be changed only on systems with databases defined on multiple physical database devices that reside on separate physical disks, or on systems taking advantage of disk striping.

max lazywrite IO*

Tunes the priority of batched asynchronous I/Os performed by the lazy writer. This is comparable to max async IO, which controls batch I/O such as bulk copy and checkpoints, but max lazywrite IO is specific to the lazy writer. This option should be configured only on systems that have multiple hard disks. It is dynamically configurable up to the value specified by max async IO. Do not change this option unless your primary support provider instructs you to do so.

max worker threads*

Configures the number of worker threads that are available to SQL Server processes. SQL Server makes use of the native thread services of the operating system. Instead of one worker thread, there are many. Each network that SQL Server simultaneously supports is supported by one or more threads, another thread handles database checkpoints, and a pool of threads handles all users.

The max worker threads option allows you to control the number of threads allocated to the user pool. When the number of user connections is less than max worker threads, one thread handles each connection. However, if the number of connections exceeds max worker threads, thread pooling occurs. Additionally, if the configured value for worker threads is exceeded, the request is handled by the next worker thread that completes its current task. The default is 255.

media retention

Sets the number of days that you expect to retain each backup medium after it has been used for a database or transaction log dump. The default is 0. Unless you change this value, no warning is issued. A typical value might be 7 (days).

If you try to use the backup medium before the set number of days have passed, SQL Server issues a warning message.

memory

Sets the size of available memory, in 2K units. The default run value is determined by the setup program based on the amount of memory in your computer.

To optimize this number for your system, subtract the memory required for Windows NT (and other system uses, if the computer is not wholly dedicated to SQL Server) from the total physical memory.

Ideally, you want to allocate as much memory as possible to SQL Server without causing the system to page. You can use the Windows NT Performance Monitor to help determine what the threshold is for your system — the Page Faults/sec counter of the Memory Object indicates whether you are generating any page faults. If so, SQL Server is running with too much memory. The threshold varies depending on your system. For example, on a 32-MB system, 16 MB might be appropriate for SQL Server; on a 64-MB system, 48 MB might be appropriate.

The amount of memory specified must be sufficient for the SQL Server static memory needs (kernel overhead, user stack space, and so on), as well as for the procedure cache and the data cache (also called buffer cache).

The memory left over after the SQL Server memory needs are met is divided between the procedure cache and the data cache. The percentage allocated to the procedure cache is set with the procedure cache configuration option.

You can use DBCC MEMUSAGE and statistics from the Windows NT Performance Monitor to help you adjust this value. Change this value only when you add or remove memory, or when you change how you use your system.

When the memory option is reconfigured, it will automatically cause a possible change to the configured free buffers configuration option. The free buffers configuration value will be set to 5 percent of the new memory size.

The maximum value for the memory option is 2 GB. Note, however, that the memory option does not include memory needs for tempdb if you have placed tempdb in RAM using the tempdb in ram (MB) option.

nested triggers*

Controls the use of nested triggers. When this option is 0, triggers will not cascade. Set it to 1 to enable nested (or cascading) triggers. The default is 1.

network packet size*

Sets the server-wide value for the default network packet size. The client application can override this value. On systems using differing network protocols, this option should be set to the size of the most common protocol used. This option can improve network performance when network protocols support larger packets. If reconfigured, the change takes effect immediately. The default is 4096.

open databases

Sets the maximum number of databases that can be open at one time on SQL Server. The default is 20.

open objects

Sets the maximum number of database objects that can be open at one time on SQL Server. The default is 500.

Increase this value if SQL Server displays a message saying that you have exceeded the number of open objects. Because open objects consume memory, increasing this value can make it necessary to increase the amount of memory dedicated to the server.

priority boost

Determines whether or not SQL Server should run at a higher priority than other processes on the same computer. If this option is set to 1, SQL Server will run at a higher priority in the Windows NT scheduler. The default is 0 and should be changed only on Windows NT systems dedicated to SQL Server.

procedure cache

Specifies the percentage of memory allocated to the procedure cache after the SQL Server memory needs are met. The SQL Server memory needs are the sum of memory necessary for locks, user connections, the code itself, and so on. The remaining memory is divided between the procedure cache and the data cache according to the percentage set by this configuration option.

The procedure cache is the area of memory where the most recently used procedures are stored. The procedure cache is also used when a procedure is being created and when a query is being compiled. If SQL Server finds a procedure or a compilation already in the cache, SQL Server does not need to read it from the disk.

The data cache is the area of memory where the most recently used data pages and index pages are stored. If SQL Server finds a data page or index page that has already been called by a user in the cache, SQL Server does not need to read it from the disk.

Information in both caches is stored in least recently used, most recently used (LRU-MRU) fashion.

The default for the procedure cache configuration option is 30, which gives the procedure cache 30 percent of the remaining memory after the SQL Server requirements are met. By default, the data cache gets the other 70 percent.

Since the optimum value for this configuration option is different from application to application, resetting it can improve SQL Server performance. For example, if you run many different procedures or ad hoc queries, your application will use the procedure cache more, so you might want to increase this value. Many applications fall into this category while they are being developed. You might want to set this option to 50 during your development cycle and then reset it to 30 when your application has stabilized.

You can use DBCC MEMUSAGE to help you adjust this value.

Read Ahead Configuration Options

Many configuration options can be grouped and are often changed together.

Read ahead configuration options control "parallel data scan" capabilities, which enable asynchronous read ahead of data when SQL Server determines that pages are being retrieved in sequential order. With read ahead (RA), separate background threads will be used to pre-fetch pages for a given results set. Read ahead is used by queries, DBCC CHECKTABLE, DBCC CHECKDB, DBCC CHECKALLOC, UPDATE STATISTICS, CREATE INDEX, exporting with bulk copy, and the retrieval of text and image data. Read ahead pre-fetches are configured based on extents. The Read Ahead configuration options are:

•	RA cache hit limit*

•	RA cache miss limit*

•	RA delay*

•	RA pre-fetches*

•	RA slots per thread

•	RA worker threads

RA cache hit limit*

Is the number of cache hits that a read-ahead request can have before it is canceled. This is used for detecting situations in which the Read Ahead manager finds everything in cache and is of little help to the query. The default value '4' should suffice for most systems. Do not change this option unless your primary support provider instructs you to do so.

RA cache miss limit*

Is the number of cache misses that occur during a horizontal traversal before read ahead starts for that command. Avoid setting this value lower than 3. Setting the RA cache miss limit to 1 causes a read-ahead request to be made whenever a data page is accessed from disk, and it can lead to thrashing and poor performance. Do not change this option unless your primary support provider instructs you to do so.

RA delay*

Specifies the delay of read ahead, in milliseconds. This is required to account for the latency to "prime" the RA Manager before it starts servicing an initial RA request. The default value '15' should suffice for most systems. For SMP machines, this value should be set to 15.

RA pre-fetches*

Determines how far ahead the read-ahead (RA) manager will read (on an extent basis) before the pre-fetch manager idles. A value of 3 means that for each request posted, the RA manager keeps three extents ahead of the current scan position.

RA slots per thread

Is the number of simultaneous requests each read-ahead (RA) service thread will manage. The number of threads multiplied by the number of slots is equivalent to the total number of concurrent RA scans that the system will support. The default value should be sufficient for most systems. If your system has an efficient IO subsystem, you may be able to increase the number of scans that a single thread can handle.

RA worker threads

Specifies the number of threads used to service read-ahead requests. Each thread will manage a configurable number of structures (see the RA slots per thread option), where each of these structures (slots) represents an individual range scan. This option should be set to the maximum number of concurrent users on the system. A warning will be logged in the error log if the number of threads requesting RA scans exceeds the number of configured RA slots.

recovery flags

Determines what information SQL Server displays in the error log during recovery. Can be 0 or 1. The default is 0, which means that SQL Server writes only the database name and a message stating that recovery is in progress. 1 means that SQL Server displays information about each individual transaction, including whether it was canceled or committed.

recovery interval*

Sets the maximum number of minutes per database that SQL Server needs to complete its recovery procedures in case of a system failure. The default is 5 minutes per database.

SQL Server uses this number and the amount of activity on each database to decide when to do a checkpoint on each database. When SQL Server does a checkpoint, it writes all dirty pages (data pages that have been changed by data modification statements) to the disk. The checkpoint also performs a few other housekeeping tasks, including truncating the transaction log if this option has been set using the sp_dboption system stored procedure. A typical checkpoint takes about 1 second.

You might want to change the recovery interval as your application and its use change. For example, to guarantee that changes are frequently written to the disk, you can shorten the recovery interval when there is a lot of update activity. Shortening the recovery interval causes more frequent checkpoints, which slows the system slightly. On the other hand, setting the recovery interval too high might cause the recovery time to be unacceptably long.

remote access

Controls logins from remote SQL Servers. Can be 0 or 1. The default is 1. Set remote access to 0 to discontinue allowing remote access to or from a server.

remote login timeout*

Specifies the number of seconds to wait before returning from a remote login attempt. A value of 0 will allow an infinite wait.

remote query timeout*

Specifies the number of seconds to wait before returning from processing a remote query. A value of 0 will allow an infinite wait.

remote sites*

Specifies the number of OS/2-based servers allowed to connect remotely.

set working set size

Directs Windows NT to reserve physical memory space for SQL Server equal to the sum of the memory setting and the size of tempdb if it is in RAM.

show advanced option*

Determines whether or not the advanced options should be displayed by the sp_configure system stored procedure. When set to 1, the advanced options are displayed. The default is 0.

SMP concurrency

Controls the number of threads that SQL Server will release to Windows NT for execution which, in effect, limits the number of CPUs used by SQL Server. On a uniprocessor computer, the optimal value is 1. On a symmetric multiprocessor (SMP) computer, the limit depends on whether or not the server is a dedicated SQL Server. If the server is not dedicated, reconfiguring this value can cause poor response time to other applications running on the same machine. If response time for other applications is not an issue, set SMP concurrency to −1, "Dedicated SMP Support," which means that there is no limit.

When SQL Server is installed, SMP concurrency will be set to 0, which means auto configure. In auto configure mode, the limit is set to N−1, where N is the number of processors detected at SQL Server startup. On a uni-processor machine this value will be set to 1. If "Dedicated SMP Support" is chosen, then SMP concurrency will be set to −1.

sort pages*

Specifies the maximum number of pages that will be allocated to sorting per user. On systems that perform large sorts, increasing this number can improve performance. Since additional sort pages will consume memory, increasing this value can make it necessary to increase the amount of memory dedicated to the server.

spin counter*

Specifies the maximum number of attempts a process will perform to obtain a resource. By default, SQL Server will attempt to set this value to 10000. This is the default for multiprocessor machines. On uniprocessor machines, the run value will default to 10.

tempdb in ram (MB)

Accepts a value for the size of the tempdb database, in megabytes. Zero causes tempdb to reside on a disk device; the default is the MASTER device. A non-zero value is the size of the tempdb in RAM. Regardless of whether it exists on disk or in RAM, tempdb is altered in the same way as any other database; however, when tempdb resides in RAM, it can be altered only 10 times without requiring the server to be shut down and restarted.

Altering tempdb while it is in RAM causes each alteration of the database to allocate a new "chunk" of contiguous memory to tempdb. This chunk of memory, although it is contiguous, is not necessarily located next to the existing portion(s) of tempdb in RAM. In order to obtain maximum performance, the server should be stopped and restarted after tempdb is altered.

Important  If tempdb is in RAM at the time of an upgrade, it will subsequently be moved out of RAM. The default disk device(s) must have the minimum amount free (2 MB) to create tempdb. If not, SQL Server startup will fail. To temporarily force a 2-MB tempdb in RAM, use the -f flag on the command line with SQLSERVR.EXE. This will allow the server to start. Once it has started, you must perform one of the following options immediately:

•	Increase the size of a default device

•	Free space on a default device

•	Add a default device

time slice

Sets the number of times that a user process is allowed to pass through a yield point without voluntarily yielding. If the time slice is set too low, SQL Server can spend too much time switching processes. If it is set too high, users can experience long response time.

The default is 100. There is seldom reason to change it.

user connections

Sets the maximum number of simultaneous connections to SQL Server allowed. The actual number of possible connections might be less than this value, depending on your database environment.

The number of user connections allowed depends on your version. For SQL Workstation, the number is 15, and for SQL Server the number is 32,767. However, the actual number is based on practical limits that vary depending on your application and hardware.

Use this statement to get a report on the maximum number of user connections that your system can use:

select @@max_connections

The memory overhead per connection is about 40K.

There is no formula for determining how many connections to allow for each user. Rather, you must estimate this number based on system and user requirements. Users executing DB-Library applications need one connection for each process started with a call to dbopen. On a system with many users, there is more likelihood that connections needed only occasionally can be shared among users.

Permission

Execute permission on sp_configure with no parameters or with only the first parameter defaults to all users. Execute permission for sp_configure with both parameters, used to change a configuration option, defaults to the system administrator. RECONFIGURE permission defaults to the system administrator and is not transferable.

Tables Used

master.dbo, master.dbo.syslanguages, sysconfigures, syscurconfigs, spt_values

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 will display all configuration options.

sp_configure 'show advanced option', 1

go

Configuration option changed. Run the RECONFIGURE command to install.

RECONFIGURE

go

sp_configure

B.	Change a Configuration Option

This example sets the system recovery interval to 3 minutes.

sp_configure 'recovery interval', 3

See Also

RECONFIGURE	sp_defaultlanguage
sp_dboption	sp_droplanguage


sp_create_removable System Stored Procedure

Creates a removable media database. Creates three or more devices (one for the system catalog tables, one the transaction log, and one or more for the data tables) and places the database on those devices. Use this stored procedure to create the database prior to performing database development.

Syntax

sp_create_removable dbname, syslogical, 'sysphysical', syssize,
loglogical, 'logphysical', logsize, datalogical1, 'dataphysical1', datasize1
[... , datalogical16, 'dataphysical16', datasize16]

where

dbname

Is the name of the database that will be created for use on removable media.

syslogical

Is the logical name of the device that will contain the system catalog tables and the transaction log.

sysphysical

Is the physical name, including a fully qualified path, of the device that will hold the system catalog tables and the transaction log.

syssize

Is the size, in megabytes, of the device that will hold the system catalog tables and the transaction log. The minimum syssize is 1.

loglogical

Is the logical name of the device that will contain the transaction log.

logphysical

Is the physical name, including a fully qualified path, of the device that will contain the transaction log.

logsize

Is the size, in megabytes, of the device that will contain the transaction log. The minimum logsize is 1.

datalogical

Is the logical name of a device that will contain the data tables.

There must be from 1 through 16 data devices. In general, you will create more than one data device when the database is expected to be large and will need to be distributed on multiple disks.

dataphysical

Is the physical name, including a fully qualified path, of a device that will contain data tables.

datasize

Is the size, in megabytes, of a device that will contain data tables. The minimum datasize is 1.

Remarks

Only removable media databases should be placed on these devices.

The device created for the transaction log is used only during database development. (When database development is complete you will run the sp_certify_removable system stored procedure. Among other actions, sp_certify_removable will truncate the transaction log, move it to the system device, and drop the log device.)

Example

This example creates the database inventory as a removable database.

sp_create_removable inventory, invsys, 'c:\sql60\data\invsys.dat, 2',
   invlog,'c:\sql60\data\invlog.dat',4

   invdata,'c:\sql60\data\invdata.dat',10,

Permission

Only the system administrator can use this stored procedure.

See also

sp_certify_removable	sp_dboption
sp_dbinstall	sp_dbremove


sp_dbinstall Removable Media Stored Procedures
sp_dbinstall System Stored Procedure

Installs a database and its devices. It must be run once for each device of the database being installed. This system stored procedure copies the system device to the hard disk (placing the system catalog tables and the transaction log on read/write media). You can leave the data device on the distribution media (usually a CD), or you can copy it to the hard disk (but it remains read-only).

Syntax

sp_dbinstall database, logical_dev_name, 'physical_dev_name', size,
'devtype' [,'location']

where

database

Is the name of the removable media database being installed. Any valid database name conforming to the SQL Server rules for identifiers can be used. You are not required to enter the database name that was originally used for this database during development.

logical_dev_name

Is the logical name of the device being installed.

physical_dev_name

Is the physical name, including the fully qualified path, of the device being installed. The path entered here is the path to the device on the distribution media.

size

Is the size, in 1-MB blocks, of the device being installed.

devtype

Indicates the type of device being installed:

SYSTEM

Indicates that the device being installed contains the system catalog tables and the transaction log. The system device must be installed before the data device.

DATA

Indicates that the device being installed contains data tables. The data device must be installed after the system device. Note that even if a data device will be left on the distribution media, it must be installed using this system stored procedure.

If the database contains more than one data device, you must run this system stored procedure once for each device.

location

Indicates the destination location to which the device will be copied from the distribution media. This is usually a destination on the computer's local hard disk. The location is a fully qualified filename, including the drive, directory, and filename of the device. The referenced directories must already exist (sp_dbinstall will not create them).

A location is required for the system device. It is optional for a data device (since a data device can be left on the distribution media).

Remarks

Important  When using sp_dbinstall, all of a database's devices must be installed.

The information required by the sp_dbinstall parameters is provided when the database is verified using sp_certify_removable.

When a database is installed using sp_dbinstall, it is set to offline. Before it can be used it must be placed online by using sp_dboption. After the database has been installed using sp_dbinstall and brought online using sp_dboption, it can be configured to suit local requirements. Users can be added, permissions can be granted, and stored procedures and views can be created. However, after the database is installed, do not attempt to perform inserts, updates, or deletes against the read-only data in the data tables.

Before the database can be used (that is, set online by using sp_dboption) all of its devices must be available. This means that if a database—because of size—has been distributed on several CDs with a different data device on each CD, and if the computer is equipped with only one CD drive, then as each device is installed sp_dbinstall must be provided a location parameter for all but one of the devices, so that all but one of the data devices are copied off the distribution CDs onto the computer's local hard disk. If this is done, only one CD will need to be in the CD drive when the database is used. To eliminate all need for a CD when using the database, all the data devices can be copied.

As an advanced option, if the data device has been moved to read/write media, it can be made read/write by running sp_addsegment against the device. (Adding a segment will make the device writeable.)

You can also use this system stored procedure to install databases and devices from non-removable media.

Example

This example installs the removable media database inventory from the distribution CD, which is located in the computer's CD-ROM drive, drive E. The system device containing the system catalog tables and the transaction log is copied to the computer's hard disk and the data device is left on the distribution media.

sp_dbinstall inventory,invsys,'e:\invsys.dat',2,'SYSTEM',
   'c:\sql60\data\invsys.dat'

EXEC sp_dbinstall inventory,invdata,'e:\invdata.dat',10,'DATA'

Permission

Only the system administrator can use this stored procedure.

Tables Used

sysdatabases, sysdevices, sysusages

See also

sp_certify_removable	sp_dboption
sp_create_removable	sp_dbremove


sp_dboption System Stored Procedure

For more updated SQL Server 6.5 syntax, see sp_dboption.

Displays or changes database options.

Syntax

sp_dboption [dbname, optname, {true | false}]

where

dbname

Specifies the database in which you want to set the option.

optname

Is the name of the option you want to set or turn off. SQL Server understands any unique string that is part of the option name. Enclose the option name with quotation marks if it includes embedded blanks or is a keyword. The available options are:

ANSI null default

Allows the user to control the database default nullability. When not explicitly defined, a user-defined datatype or a column definition will use the default setting for nullability. Nullability is determined by session settings and database settings. SQL Server defaults to NOT NULL. However, the ANSI-standard is NULL. For ANSI compatibility, setting ANSI null default to TRUE changes the database default nullability to NULL.

With this option set to true, all user-defined datatypes or columns not explicitly defined as NOT NULL during a CREATE TABLE or ALTER TABLE statement will default to allowing NULLs. Columns defined with constraints will follow constraint rules regardless of this setting (for example, PRIMARY KEY columns, IDENTITY columns, and columns of type bit cannot be NULL).

Session settings override the default database setting for ANSI null default. For more information, see the SET statement.

dbo use only

Sets a database for use only by the database owner. Active users of the database can continue to access the database, but no new users are allowed. When active users disconnect or change database context (with the USE statement), they will not be allowed access to this database unless this option has been set to false.

no chkpt on recovery

Defines whether or not a checkpoint record is added to the database after it is recovered during a SQL Server startup. If this option is off (false, the default), a checkpoint record is added.

The no chkpt on recovery option is useful when an up-to-date copy of a database is kept. In these situations, there is a "primary" and a "secondary" database. Initially, the primary database is dumped and loaded into the secondary database. Then, at intervals, the transaction log of the primary database is dumped and loaded into the secondary database. If this option is on (true) in the secondary database, no checkpoint record is added to a database after it is recovered, so subsequent transaction log dumps from the primary database can be loaded into it.

offline

Allows a database to be placed online (when set to false, the database is ready to be used) or offline (when set to true, the database is unavailable and cannot be used). This option is primarily used on databases with removable media devices but it can be used on any database.

When a database is placed online, all devices belonging to the specified database are opened (if they are not already open) and marked as non-deferred, and the database is recovered and becomes available for use.

When a database is placed offline, all devices belonging to that database are closed and marked as deferred, except those that contain space belonging to other online databases. Databases placed offline are not recovered automatically at server startup.

Note  A database cannot be placed offline if it has an active user.

published

Allows the database to be published for replication. This option does not publish a database. Instead, it permits the tables of a database to be published.

When set to true, this option enables publishing and adds the user repl_subscriber to the database.

When set to false , it disables publishing, drops all publications, unmarks all transactions that were marked for replication in the transaction log, and removes the database user repl_subscriber.

read only

Defines a database as read only. This option means that users can retrieve data from the database but cannot modify anything. Because a read-only database does not allow data modifications, automatic recovery is skipped at system startup.

select into/bulkcopy

Allows a database to accept non-logged operations. Non-logged operations include: using the UPDATETEXT or WRITETEXT statement, using SELECT INTO into a permanent table, using fast bulk copy (bcp), or performing a table load. This option need not be set to run bcp on a table that has indexes, because tables with indexes are always copied with the slower version of bcp and are logged.

After performing non-logged operations, using the DUMP TRANSACTION statement is prohibited. Issuing DUMP TRANSACTION after making unlogged changes to the database with SELECT INTO or bulk copy produces an error message telling you to use DUMP DATABASE instead. Once all non-logged operations are completed, turn off select into/bulkcopy and issue the DUMP DATABASE statement.

By default, the select into/bulkcopy option is turned off in newly created databases. To change the default situation, set this option in the model database.

Note  Because SELECT is a keyword, you must enclose select into/
bulkcopy in quotation marks to avoid a syntax error.

single user

Restricts database access to a single user. Any user accessing the database when single user is set to true can continue to use the database. A new user will be allowed into this database only if all other users have disconnected or changed to another database. When this option is set, the trunc. log on chkpt. option is not supported. Truncate the log after single user operations are completed.

subscribed

Allows the database to be subscribed for replication. Setting subscribed to true aliases the login ID of repl_publisher to DBO. This allows the distribution process to replicate to this database. Setting subscribed to false removes the alias.

This stored procedure does not subscribe to a database. It permits a database to subscribe to a published database.

trunc. log on chkpt.

Causes the transaction log to be truncated (committed transactions are removed) every time the CHECKPOINT process occurs (usually once per minute). When the database owner runs CHECKPOINT manually, however, the log is not truncated. It may be useful to turn this option on while doing development work, to prevent the log from growing. While the trunc. log on chkpt. option is set, backups of the transaction log are not allowed since dumps from the truncated transaction log dumps cannot be used to recover from media failure. Issuing the DUMP TRANSACTION statement produces an error message instructing you to use the DUMP DATABASE statement instead.

true | false

Specifies how to set the option. Use true if you want to set the option and false if you want to turn off the option.

Remarks

To display the list of available database options, execute sp_dboption with no parameters. To list all of the configured options for a particular database, execute the sp_helpdb system stored procedure. The only option you can set for the master database is trunc. log on chkpt. 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 will be executed in the database for which the option was changed. This will cause the change to take effect immediately.

For additional details on database options, see the Microsoft SQL Server Administrator's Companion.

Permission

Execute permission to display the list of options only (using sp_dboption with no parameters) defaults to all users. Execute permission to change an option (using sp_dboption with parameters) defaults to the system administrator and the database owner of the database for which the option is to be changed.

Examples

A.	sp_dboption with No Parameters

This example displays a list of the database options.

sp_dboption

go

Settable database options:
--------------------------
ANSI null default
dbo use only
no chkpt on recovery
offline
published
read only
select into/bulkcopy
single user
subscribed
trunc. log on chkpt.

B.	Set a Database to Read Only

This example makes the pubs database read only.

sp_dboption pubs, 'read', TRUE

go

CHECKPOINTing database that was changed.

C.	Turn Off an Option

This example makes the pubs database writable again.

sp_dboption pubs, 'read', FALSE

go

CHECKPOINTing database that was changed.

D.	Take a Database Offline

This example takes the sales database offline if there are no users accessing the sales database.

USE master

go

sp_dboption sales, offline, TRUE

go

CHECKPOINTing database that was changed.

Tables Used

master.dbo.spt_values, master.dbo.sysdatabases

See Also

CHECKPOINT	sp_droppublisher
SELECT	sp_dropsubscriber
sp_addpublisher	sp_helpdb
sp_addsubscriber	sp_helpdistributor
sp_changesubscriber	sp_helpserver
sp_configure	sp_helpsubscriberinfo


sp_dbremove System Stored Procedure

Used to remove a database, and optionally, any devices to which it has exclusive use. This system stored procedure is useful primarily with databases created on removable media; however, it can be used on all databases including damaged databases.

Syntax

sp_dbremove database[, dropdev]

where

database

Is the name of the database to be removed.

dropdev

Removes from sysdevices all devices of which that database has exclusive use. It does not delete the .DAT files.

Remarks

This stored procedure removes the entries in sysdatabases and sysusages for the specified database. If the dropdev keyword is included, it also removes from sysdevices all devices of which that database has exclusive use. It does not delete the .DAT files.

If no value is provided, the usage syntax is displayed.

Permission

Execute permission defaults to the system administrator and database owner of the database for which the drop will be performed.

Example

This example removes the sales database and removes from sysdevices all devices used exclusively by sales.

sp_dbremove sales, dropdev

Tables Used

master.dbo.sysalternates, master.dbo.spt_values, master.dbo.sysdatabases, master.dbo.sysprocesses

See Also

ALTER DATABASE	DBCC
CREATE DATABASE


sp_defaultdb System Stored Procedure

Changes a user's default database.

Syntax

sp_defaultdb login_id, defdb

where

login_id

Is the user's login ID.

defdb

Specifies the user's default (home) database (the database to which the user is connected when logging in).

Remarks

A default database can be set by using either sp_defaultdb or sp_addlogin when the user's login ID is initially added to SQL Server.

If no default database has been specified, users are connected to the master database.

After sp_defaultdb is executed, the user is connected to the new defdb the next time he or she logs in. However, this system stored procedure does not automatically give the user access to that database. The database owner must give database access to the user through sp_adduser or sp_addalias, or there must be a guest user specified in the database's sysusers table. A user who does not have access to the database by any of these means will be connected to the master database and an error message will be displayed.

If a user's default database is dropped, the user is connected to master on the next login and an error message is displayed.

The system administrator can change anyone's default database by using sp_defaultdb. Users can change only their own default database.

Example

This example sets pubs as the default database for Victoria.

sp_defaultdb Victoria, pubs

Permission

Execute permission defaults to public for a user's login ID only. Execute permission defaults to the system administrator for any login ID.

Tables Used

master.dbo.sysdatabases, master.dbo.syslogins

See Also

sp_addlogin	sp_password
sp_droplogin	USE


sp_defaultlanguage System Stored Procedure

Changes a user's default language.

Syntax

sp_defaultlanguage login_id [, language]

where

login_id

Is the user's login ID.

language

Specifies the user's default language.

Remarks

A default language can be set by using either sp_defaultlanguage or sp_addlogin when the user's login ID is initially added to SQL Server. If a language is not specified, the user's default language is set to the server's default language.

If a user's default language is dropped from the server, the server's default language is used as the initial language setting and a message is displayed.

The system administrator can change anyone's default language by using sp_defaultlanguage. Users can change only their own default language.

Example

This example sets the default language for Claire to French.

sp_defaultlanguage Claire, french

Permission

Execute permission defaults to public for the user's own login only. Execute permission defaults to the system administrator for any login ID.

Tables Used

master.dbo.syslanguages, master.dbo.syslogins

See Also

SET	sp_droplogin
sp_addlogin	sp_helplanguage


sp_depends System Stored Procedure

Displays information about database object dependencies — the views and procedures that depend on the specified table or view, and the tables and views that are depended on by the specified view or procedure.

Syntax

sp_depends objname

where

objname

Specifies which database object to examine for dependencies. The object can be a table, view, stored procedure, or trigger.

Remarks

Executing sp_depends lists all objects, if any, that depend on objname and all objects, if any, on which objname depends (for example, views depend on one or more tables and can have procedures or other views that depend on them). An object that references another object is considered dependent on that object.

This system stored procedure determines the dependencies by looking at the sysdepends table.

The updated and selected columns in the report from sp_depends are meaningful if the object being reported on is a stored procedure or trigger. The values in these columns indicate whether the stored procedure or trigger updates or selects from that object.

References to objects outside the current database are not reported.

Example

This example lists the database objects that depend on the titles table.

sp_depends titles

Permission

Execute permission defaults to the public group.

Tables Used

master.dbo.sp_values, master.dbo.sysdatabases, sysdepends, sysobjects

See Also

CREATE PROCEDURE	EXECUTE
CREATE TABLE	sp_help
CREATE VIEW


sp_devoption System Stored Procedure

Displays or sets device status. Although primarily used on removable media devices, this procedure can be used for all devices.

This stored procedure is used internally (by other system stored procedures) and is not typically used by users.

Syntax

sp_devoption [devicename [, optname {, true | false}]]

where

devicename

Is a device name.

optname

Is the name of the option you want to turn on or off. Can be:

deferred

When set to true, indicates that the device is not to be automatically opened at server startup time. Setting deferred to true can be useful when you create a new device and will not immediately place a database on it.

readonly

When set to true, indicates that the device is read only.

true | false

Specifies how to set the optname option.

Remarks

If no parameters are specified, a list of the settable options is displayed.

Permission

Execute permission defaults to the system administrator.

Tables Used

master.dbo.sysdatabases, master.dbo.sysusages, master.dbo.spt_values, master.dbo.sysdevices

Examples

A.	Set Device to Not Open at Startup

This example sets the device DEV1 so that it will not be opened automatically at server startup.

sp_devoption DEV1,deferred,true

B.	Set Device to Be Read Only

This example sets the device DEV1 to be read only.

sp_devoption DEV1, readonly, true

See Also

DISK INIT	sp_dropdevice


sp_diskdefault System Stored Procedure

Sets a database device's status to indicate whether the device can be used for database storage when the user does not specify a database device or specifies DEFAULT with the CREATE DATABASE or ALTER DATABASE statements.

Syntax

sp_diskdefault database_device, {defaulton | defaultoff}

where

database_device

Is the logical name of the database device (not a dump device).

defaulton | defaultoff

Indicates whether the specified database device is the default. Use defaulton if the database device can be a default database device. Use defaultoff if the database device cannot be a default database device. The defaulton option will most frequently be used after a database device has been added to the system by the DISK INIT statement. The defaultoff option will most frequently be used to change the default status of the MASTER database device (which is the designated default when SQL Server is initially installed).

Remarks

You can have multiple default devices. They are used in alphabetic order, the order in which they appear in the sysdevices table.

When SQL Server is initially installed, the MASTER database device is the only default database device.

To find out which database devices are default database devices, execute the sp_helpdevice system stored procedure.

Example

In this example, the MASTER database device will no longer be used by the CREATE DATABASE or ALTER DATABASE statements for the default storage of a database.

sp_diskdefault master, defaultoff

Permission

Only the system administrator can use this procedure.

Table Used

master.dbo.sysdevices

See Also

ALTER DATABASE	DISK INIT
CREATE DATABASE	sp_helpdevice


sp_dropalias System Stored Procedure

Removes the alias login ID identity that was established by sp_addalias.

Syntax

sp_dropalias login_id

where

login_id

Is the name (in master.dbo.syslogins) of the user who has an alias.

Remarks

Executing the sp_dropalias system stored procedure deletes an alternate suid mapping for a user from the sysalternates table. When a user's alias is dropped, the user no longer can access the database for which the alias was created.

Example

Assuming that Victoria has an alias (for example, as the database owner) in the current database, this procedure drops her alias from the database.

sp_dropalias Victoria

Permission

Only the database owner can use this procedure.

Table Used

sysalternates

See Also

sp_addalias	sp_dropuser
sp_adduser	sp_helpuser
sp_changedbowner	USE
sp_droplogin


sp_dropdevice System Stored Procedure

Removes a SQL Server database device or dump device.

Syntax

sp_dropdevice logical_name [, DELFILE]

where

logical_name

Is the logical name of the database device or the dump device as listed in master.dbo.sysdevices.name.

DELFILE

Specifies that the physical file should be deleted.

Remarks

The sp_dropdevice system stored procedure drops a database device or dump device from SQL Server, deleting the entry from master.dbo.sysdevices. It frees the file handle and the device number when a database device is dropped. This means that the physical file can be deleted without shutting down SQL Server. To delete the physical file, use the DELFILE option or delete the file from the command line.

Note  You can also immediately use the DISK INIT statement to create a new device with that same device number, logical name, and physical name (if you've deleted the file).

Permission

Execute permission defaults to the system administrator and cannot be transferred.

Tables Used

master.dbo.sysdatabases, master.dbo.sysdevices, master.dbo.sysusages

Example

This example drops the TAPEDUMP1 tape dump device from SQL Server.

sp_dropdevice TAPEDUMP1

See Also

DROP DATABASE	sp_helpdb
sp_addumpdevice	sp_helpdevice


sp_dropextendedproc System Stored Procedure

Drops an extended stored procedure.

Syntax

sp_dropextendedproc function_name

where

function_name

Specifies which extended stored procedure to drop.

Remarks

Executing sp_dropextendedproc drops the extended stored procedure name from the sysobjects table and removes the entry from the syscomments table.

Example

This example drops xp_diskfree.

sp_dropextendedproc xp_diskfree

Permission

Only the system administrator can use this procedure.

Tables Used

syscomments, sysobjects

See Also

sp_addextendedproc	sp_helpextendedproc


sp_dropgroup System Stored Procedure

Removes a group from a database.

Syntax

sp_dropgroup grpname

where

grpname

Specifies which group to drop from the current database.

Remarks

Executing sp_dropgroup drops a group name from a database's sysusers table.

You cannot drop a group that has members. Before you can drop the group, you must execute sp_changegroup for each member.

Example

In this example, the purchasing group has merged with the accounting group. Members of the purchasing group, Martha (username Martha) and George (username George), are moved. Martha is moved to the accounting group, George is moved to the public group. Then the purchasing group is dropped. The group name public is enclosed in single quotation marks because public is a reserved word.

sp_changegroup accounting, Martha

EXEC sp_changegroup 'public', George

EXEC sp_dropgroup purchasing

Permission

Only the database owner can use this procedure.

Tables Used

sysobjects, sysprotects, sysusers

See Also

GRANT	sp_changegroup
REVOKE	sp_dropuser
sp_addgroup	sp_helpgroup
sp_adduser	USE


sp_droplanguage System Stored Procedure

Drops an alternate language from the server and removes its row from master.dbo.syslogins.

Syntax

sp_droplanguage language [, dropmessages]

where

language

Is the language to be dropped.

dropmessages

Drops all SQL Server system messages in language when the language is dropped. A language with associated system messages cannot be dropped without also dropping its messages.

Remarks

Executing the sp_droplanguage system stored procedure also drops a language from the list of available alternate languages by deleting its entry from the master.dbo.syslanguages table.

Examples

A.	Drop a Language

If there are no associated messages, this example drops French from the set of available alternate languages.

sp_droplanguage french

B.	Drop a Language with Messages

If there are associated messages, this example drops French from the set of available alternate languages.

sp_droplanguage french, dropmessages

Permission

Only the system administrator can use this procedure.

Tables Used

master.dbo.syslanguages, master.dbo.sysmessages

See Also

sp_helplanguage


sp_droplogin System Stored Procedure

Removes a SQL Server login ID by deleting the user's entry in master.dbo.syslogins.

Syntax

sp_droplogin login_id

where

login_id

Is the name of the user as listed in master.dbo.syslogins.

Remarks

The sp_droplogin procedure checks only the current database to see if the login ID to be dropped is a user there. You cannot drop a user's login ID if the user is an object owner or user in any database(s).

Example

This example drops the login ID Victoria from SQL Server.

sp_droplogin Victoria

Permission

Only the system administrator can use this procedure.

Tables Used

master.dbo.syslogins, sysusers

See Also

sp_addlogin	sp_dropuser
sp_changedbowner	sp_helpuser
sp_dropalias


sp_dropmessage System Stored Procedure

Drops a specified error message from the sysmessages system table.

Syntax

sp_dropmessage [msg_id]

where

msg_id

Specifies the message to drop. This parameter must be a user-defined message with a msg_id greater than or equal to 50000.

Remarks

If no parameters are supplied, a syntax diagram will be displayed.

Example

This example drops the message (number 50001) from sysmessages.

sp_dropmessage 50001

go

Message dropped.

Permission

Execute permission defaults to the system administrator, who can transfer it to other users.

Table Used

sysmessages

See Also

CREATE TABLE	sp_addmessage
RAISERROR	sp_altermessage


sp_dropremotelogin System Stored Procedure

Removes a remote user login.

Syntax

sp_dropremotelogin remoteserver [, loginame [, remotename]]

where

remoteserver

Specifies which server has the remote login to be dropped.

loginame

Is the local server's username that is associated with the remote server in the sysremotelogins table.

remotename

Is the remote username that gets mapped to loginame when logging in from the remote server.

Remarks

Executing sp_dropremotelogin drops a user login ID from a remote server, deleting the user's entry from master.dbo.sysremotelogins.

To add local server users, use the sp_addlogin system stored procedure. To drop local server users, use the sp_droplogin system stored procedure.

Examples

A.	Drop a Remote Server

This example drops the entry for the remote server ACCOUNTS.

sp_dropremotelogin ACCOUNTS

B.	Drop a Login Mapping

This example drops the entry for mapping remote logins from the remote server ACCOUNTS to the local user named Albert.

sp_dropremotelogin ACCOUNTS, Albert

C.	Drop a Remote User

This example drops the login for the remote user Chris on the remote server ACCOUNTS that was mapped to the local user salesmgr.

sp_dropremotelogin ACCOUNTS, salesmgr, Chris

Permission

Execute permission defaults to the system administrator and cannot be transferred.

Tables Used

master.dbo.sysremotelogins, master.dbo.sysservers

See Also

sp_addlogin	sp_droplogin
sp_addremotelogin	sp_helpremotelogin
sp_addserver	sp_helpserver


sp_dropsegment System Stored Procedure

Drops a segment from a database or unmaps a segment from a database device.

Syntax

sp_dropsegment segname [, logical_name]

where

segname

Is the segment to be dropped.

logical_name

Specifies the database device that you want the segment segname to no longer use. This parameter is optional, except when dropping the SYSTEM, DEFAULT, and LOGSEGMENT system segments from a database device.

Remarks

You cannot drop a segment if it is being referenced by any table or index in the current database.

If you do not supply a logical_name, the segment is dropped from the current database. If you supply a logical_name, the segment is dropped only from the named database device; it remains mapped to any previously specified devices and the segment remains in the database.

Using the sp_placeobject system stored procedure to change future space allocations for a table or an index from one segment to another removes the reference to the original segment. You can drop the original segment name with sp_dropsegment.

For the SYSTEM, DEFAULT, and LOGSEGMENT system segments, specify the device name from which you want the segments dropped.

Examples

A.	Drop a Segment

This example drops the segment INDEXES from the current database.

sp_dropsegment INDEXES

B.	Unmap a Segment

This example unmaps the segment INDEXES from the database device DEV1.

sp_dropsegment INDEXES, DEV1

Permission

Execute permission defaults to the database owner.

Tables Used

sysindexes, syssegments, master.dbo.sysdevices, master.dbo.sysusages

See Also

sp_addsegment	sp_placeobject
sp_helpsegment


sp_dropserver System Stored Procedure

Drops a server from the list of known servers, deleting the entry from the master.dbo.sysservers table.

Syntax

sp_dropserver server_name [, droplogins]

where

server_name

Is the server to be dropped.

droplogins

Indicates that any remote logins for server_name should also be dropped.

Remarks

Running sp_dropserver on a server that has associated entries in the master.dbo.sysremotelogins table results in an error message, stating that you need to drop the remote users before you can drop the server. To drop all remote logins for a server when dropping the server, use the droplogins option.

Example

This example drops the remote server ACCOUNTS.

sp_dropserver ACCOUNTS

Permission

Execute permission defaults to the system administrator and cannot be transferred.

Tables Used

master.dbo.sysremotelogins, master.dbo.sysservers

See Also

sp_addserver	sp_helpremotelogin
sp_dropremotelogin	sp_helpserver


sp_droptype System Stored Procedure

Deletes a user-defined datatype from systypes.

Syntax

sp_droptype typename

where

typename

Is the name of a user-defined datatype that you own.

Remarks

The typename user-defined datatype cannot be dropped if tables or other database objects reference it.

Example

This example drops the user-defined datatype named birthday.

sp_droptype birthday

Permission

Execute permission defaults to the database owner and the datatype owner.

Tables Used

syscolumns, sysobjects, systypes, sysusers

See Also

sp_addtype	sp_rename


sp_dropuser System Stored Procedure

Removes a user from the current database by deleting the entry from the current database's sysusers table.

Syntax

sp_dropuser username

where

username

Is the user to drop.

Remarks

The owner of a database cannot be dropped. If other users are aliased to the user being dropped, their aliases are dropped and they can no longer access the database.

Example

This example drops the user Albert from the current database. He will no longer be able to use the database.

sp_dropuser Albert

Permission

Execute permission defaults to the database owner.

Tables Used

sysalternates, sysobjects, sysprotects, systypes, sysusers

See Also

GRANT	sp_adduser
REVOKE	sp_droplogin
sp_addalias	USE


sp_extendsegment System Stored Procedure

Extends the range of a segment to another database device.

Syntax

sp_extendsegment segname, logical_name

where

segname

Is the name of the existing segment (previously defined by the sp_addsegment system stored procedure).

logical_name

Specifies the database device to be added to the current database device range for segname.

Remarks

Once a segment has been defined, you can put a table or index on it by using the CREATE TABLE and CREATE INDEX statements. If a table or index is created on a particular segment, all subsequent data for that table or index will be located on that segment.

To associate a segment with a database device, the database must have been created or altered with a reference to that device. A database device can have more than one segment associated with it, and a segment can be extended over several database devices.

Extending the log segment to a new device unmaps any existing segments from that device.

Because sp_addsegment and sp_extendsegment do not accept a size parameter, when a segment is created it is mapped to the entire amount of space allocated for the specified database on the specified device. When the database is expanded with ALTER DATABASE, any segments mapped to that device for the database are expanded to all allocated space.

Example

This example extends the range of the segment INDEXES to the database device DEV2.

sp_extendsegment INDEXES, DEV2

Permission

Execute permission defaults to the database owner.

Tables Used

syssegments, master.dbo.sysdevices, master.dbo.sysusages

See Also

ALTER DATABASE	sp_helpdb
CREATE INDEX	sp_helpdevice
CREATE TABLE	sp_helpsegment
sp_addsegment	sp_placeobject
sp_dropsegment


sp_help System Stored Procedure

Reports information about a database object (any object listed in the sysobjects table) or about a SQL Server − supplied or user-defined datatype.

Syntax

sp_help [objname]

where

objname

Is the name of any object in sysobjects or any user-defined datatype in the systypes table. Database names are not acceptable.

Remarks

The sp_help system stored procedure looks for an object in the current database only.

When no objname parameter is specified, sp_help lists object names, owners, and object types for all objects in the current database.

System procedures do not work on temporary tables because a procedure cannot access a temporary object unless the procedure created the object itself during the current session.

Examples

A.	Help on All Objects

This example lists information about each object in sysobjects.

sp_help

B.	Help on a Single Object

This example displays information about the publishers table.

sp_help publishers

Permission

Execute permission defaults to the public group.

Tables Used

master.dbo.spt_values, syscolumns, sysindexes, sysobjects, systypes

See Also

sp_helpgroup	sp_helpsql
sp_helpindex	sp_helpuser
sp_helprotect


sp_helpconstraint System Stored Procedure

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 table_name

where

table_name

Specifies the table about which you want constraint information.

Remarks

Executing sp_help table_name reports all information about the specified table. To see only the constraint information, use sp_helpconstraint.

Permission

Execute permission defaults to the public group.

Tables Used

syscolumns, syscomments, sysconstraints, sysindexes, sysobjects, sysreferences

Example

This example shows all constraints for the employee table.

sp_helpconstraint employee

See Also

ALTER TABLE	sp_help
CREATE TABLE


sp_helpdb System Stored Procedure

Reports information about a specified database or all databases.

Syntax

sp_helpdb [dbname]

where

dbname

Specifies the database about which you want information.

Remarks

When dbname is specified, sp_helpdb reports on that database. When no parameter is supplied, sp_helpdb reports on all databases in master.dbo.sysdatabases.

Examples

A.	Help on a Single Database

This example displays the following information about the pubs database:

sp_helpdb pubs

B.	Help on All Databases

This example displays information about all databases on the SQL Server but does not include the device_fragments, size, and usage columns.

sp_helpdb

Permission

Execute permission defaults to the public group.

Tables Used

master.dbo.spt_values, master.dbo.sysdatabases, master.dbo.sysdevices, master.dbo.syslogins, master.dbo.sysusages

See Also

ALTER DATABASE	sp_dboption
CREATE DATABASE	sp_renamedb
sp_configure


sp_helpdevice System Stored Procedure

Reports information about SQL Server database devices and dump devices.

Syntax

sp_helpdevice [logical_name]

where

logical_name

Is the logical name of the database device or dump device that you want information about.

Remarks

When logical_name is specified, sp_helpdevice displays information about the specified database device or dump device. When no parameter is specified, sp_helpdevice displays information about all database devices and dump devices in master.dbo.sysdevices.

The sysdevices table contains database devices and dump devices. Database devices can be designated as default database devices, which means that they can be used for database storage when a user executes the CREATE DATABASE or ALTER DATABASE statement with no specifier database device name or with the keyword DEFAULT. To make a database device a default database device, execute the sp_diskdefault system procedure.

Database devices are added to the system with the DISK INIT statement. Dump devices are added to the system by the sp_addumpdevice system procedure.

The status column in the sp_helpdevice report contains a number that corresponds to the status description in the description column.

The cntrltype column specifies the controller number of the device. For hard-disk dump devices, the controller number is 2; for diskette dump devices, the controller number is 3 or 4; and for tape devices, the controller number is 5. For database devices, it is 0.

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.

The low and high columns represent virtual page numbers for database devices and disk dump devices.

The high and low columns represent media capacity for diskette dump devices (high − low = number of 2K blocks).

Examples

A.	Help on All Devices

This example reports information about all database devices and dump devices on SQL Server.

sp_helpdevice

B.	Help on a Single Device

This example reports information about the TAPEDUMP device.

sp_helpdevice TAPEDUMP

Permission

Execute permission defaults to the public group.

Tables Used

master.dbo.spt_values, master.dbo.sysdevices

See Also

DISK INIT	sp_diskdefault
DUMP	sp_dropdevice
LOAD	sp_helpdb
sp_addumpdevice	sp_logdevice
sp_configure	sp_who


sp_helpextendedproc System Stored Procedure

Displays the currently defined extended stored procedures and the name of the dynamic-link library to which the function belongs.

Syntax

sp_helpextendedproc [function_name]

where

function_name

Specifies which extended stored procedure to display information about.

Remarks

When function_name is specified, sp_helpextendedproc reports on the specified extended stored procedure. When no parameter is supplied, sp_helpextendedproc reports on all extended stored procedures.

Examples

A.	Help on All Extended Stored Procedures

This example reports on all extended stored procedures.

sp_helpextendedproc

B.	Help on a Single Extended Stored Procedure

This example reports on the xp_cmdshell extended stored procedure.

sp_helpextendedproc xp_cmdshell

Permission

Execute permission defaults to the system administrator and can be transferred.

Table Used

syscomments, sysobjects

See Also

sp_addextendedproc	sp_dropextendedproc


sp_helpgroup System Stored Procedure

Reports information about a group or all groups in the current database.

Syntax

sp_helpgroup [grpname]

where

grpname

Is the name of a group created by sp_addgroup in the current database.

Remarks

When grpname is specified, sp_helpgroup reports on the specified group. If no parameter is supplied, sp_helpgroup reports on all groups in the database.

To get a report on the default group public, enclose the name public in quotation marks because it is a reserved word.

Examples

A.	Help on a Single Group

This example displays information about the hackers group.

sp_helpgroup hackers

B.	Help on All Groups

This example displays information about all groups in the current database.

sp_helpgroup

Permission

Execute permission defaults to the public group.

Table Used

sysusers

See Also

GRANT	sp_dropgroup
REVOKE	sp_helprotect
sp_addgroup	sp_helpuser
sp_changegroup


sp_helpindex System Stored Procedure

Reports information about the indexes on a table.

Syntax

sp_helpindex tabname

where

tabname

Specifies a table in the current database.

Remarks

Executing sp_helpindex lists up to eight indexes on a table.

Example

This example reports on the types of indexes on the sysobjects table.

sp_helpindex sysobjects

index_name	index_description	index_keys
---------------	-----------------	---------------
sysobjects	clustered, unique	id
ncsysobjects	nonclustered, unique	name, uid
Permission

Execute permission defaults to the public group.

Tables Used

master.dbo.spt_values, sysindexes, syssegments

See Also

CREATE INDEX	sp_statistics
DROP INDEX	UPDATE STATISTICS
sp_help


sp_helplanguage System Stored Procedure

Reports information about a particular alternate language or about all languages.

Syntax

sp_helplanguage [language]

where

language

Specifies the alternate language about which information is to be displayed.

Remarks

When language is supplied, sp_helplanguage reports on the specified language. When no parameter is supplied, sp_helplanguage reports on all languages in master.dbo.syslanguages.

Examples

A.	Help on a Single Language

This example displays information about the alternate language French.

sp_helplanguage french

B.	Help on All Languages

This example displays information about all installed alternate languages.

sp_helplanguage

Permission

Execute permission defaults to the public group.

Table Used

master.dbo.syslanguages

See Also

sp_droplanguage	sp_setlangalias


sp_helplog System Stored Procedure

Reports the name of the device that contains the first page of the log in the current database.

Syntax

sp_helplog

Permission

Execute permission defaults to the public group.

Tables Used

sysindexes, master.dbo.sysdevices

See Also

ALTER DATABASE	sp_helpdevice
CREATE DATABASE	sp_logdevice


sp_helpremotelogin System Stored Procedure

Reports information about a particular remote server's logins or about all remote servers' logins.

Syntax

sp_helpremotelogin [remoteserver [, remotename]]

where

remoteserver

Specifies the server about which remote login information is to be displayed.

remotename

Specifies a particular remote user on the remote server.

Examples

A.	Help on a Single Server

This example displays information about all remote users of the remote server ACCOUNTS.

sp_helpremotelogin ACCOUNTS

B.	Help on All Remote Users

This example displays information about all remote users of all remote servers known to the local server.

sp_helpremotelogin

Permission

Execute permission defaults to the public group.

Tables Used

master.dbo.sysremotelogins, master.dbo.sysservers

See Also

sp_addremotelogin	sp_helpserver
sp_dropremotelogin


sp_helprotect System Stored Procedure

For more updated SQL Server 6.5 syntax, see sp_helprotect.

Reports permissions by database object and, optionally, by user for that object.

Syntax

sp_helprotect name [, username]

where

name

Is the name of a table, view, stored procedure, user, or group in the current database.

username

Is a username in the current database.

Remarks

Executing sp_helprotect reports permissions on a database object. If the username parameter is supplied, only that user's permissions on the database object are reported. If name is a user or group and username is also supplied, the permissions for the user or group are listed.

The procedure looks for objects and users in the current database only.

Examples

A.	Permissions for a Table

This example reports the permissions for the titles table.

sp_helprotect titles

B.	Permissions for a User

This example lists all permissions that Judy has in the database.

sp_helprotect Judy

Permission

Execute permission defaults to the public group.

Tables Used

master.dbo.spt_values, syscolumns, sysobjects, sysprotects, sysusers

See Also

GRANT statement	sp_help
REVOKE statement


sp_helpsegment System Stored Procedure

Reports information about a particular segment or about all segments in the current database.

Syntax

sp_helpsegment [segname]

where

segname

Specifies the segment about which you want information. If you omit this parameter, information about all segments in the current database is displayed. If the segname is DEFAULT, you must enclose it in quotation marks because the word DEFAULT is a reserved word.

Remarks

Segments are added to the syssegments table in the current database by using the sp_addsegment system procedure.

Example

This example reports information about the SEGMENT3 segment, including which database tables and indexes use that segment.

sp_helpsegment segment3

Permission

Execute permission defaults to the public group.

Tables Used

master.dbo.sysdevices, master.dbo.sysusages, sysindexes, syssegments

See Also

sp_addsegment	sp_helpdb
sp_dropsegment	sp_helpdevice
sp_extendsegment


sp_helpserver System Stored Procedure

For more updated SQL Server 6.5 syntax, see sp_helpserver.

Reports information about a particular remote or replication server or about all servers of both types.

Syntax

sp_helpserver [server_name]

where

server_name

Specifies the server about which information is to be displayed. When no server_name is supplied, reports about all servers in master.dbo.sysservers.

Remarks

This system stored procedure returns the server's name, network name, status, and ID. Status can be:

dist	Distribution server
dpub	Combination publisher/subscriber
pub	Publication server
rpc	Remote server
sub	Subscription server
A server can have more than one status.

Permission

Execute permissions defaults to the public group.

Tables Used

master.dbo.sp_values, master.dbo.sysservers

Examples

A.	Information About All Servers

This example displays information about all servers (sp_helpserver with no parameters).

sp_helpserver

B.	Information About a Specific Server

This example displays all information about the sales server.

sp_helpserver sales

See Also

sp_addpublisher	sp_dropserver
sp_addserver	sp_dropsubscriber
sp_addsubscriber	sp_helpdistributor
sp_changesubscriber	sp_helpremotelogin
sp_dboption	sp_helpsubscriberinfo
sp_droppublisher	sp_serveroption


sp_helpsort System Stored Procedure

Displays the SQL Server default sort order and character set.

Syntax

sp_helpsort

Remarks

Binary sort order is the default.

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 SQL Server. For more information about sort orders, see Microsoft SQL Server Setup.

Example

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

Sort Order Description

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

Character Set = 2, cp850

Code Page 850 (Multilingual) character set.

Sort Order = 40, bin_cp850

Binary Sort Order for the CodePage 850 Character Set

Characters, in Order

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

Permission

Execute permission defaults to the public group.

Table Used

master.dbo.syscharsets


sp_helpsql System Stored Procedure

Provides syntax for Transact-SQL statements, system procedures, and other special topics.

Syntax

sp_helpsql ['topic']

where

topic

Specifies the topic on which you want help. Help information is available for all Transact-SQL statements, all system procedures, and the following special topics: datatypes, expressions, functions, wildcard characters, mathematical functions, and text functions. You must include quotation marks around topic.

Remarks

Online Help is also available through the SQL Help icon in the SQL Server program group.

You can enter just the first few letters of a topic. If these letters are enough to identify the topic, then Help on the topic is displayed. For example, to get Help on the CREATE TABLE statement, execute the following:

sp_helpsql 'CREATE TAB'

To get help on all topics starting with "CREATE," execute the following:

sp_helpsql 'CREATE'

Examples

A.	Help on a Single Command

This example displays a brief definition of the DISK INIT statement along with its syntax.

sp_helpsql 'disk init'

B.	Help on Functions

This example displays information about SQL Server functions.

sp_helpsql functions

Permission

Execute permission defaults to the public group.


sp_helpstartup System Stored Procedure

Reports a listing of all auto-start stored procedures.

Syntax

sp_helpstartup

Remarks

Executing sp_helprotect reports a list of all stored procedures marked for auto execution (to be run when the server is started).

Example

This example reports information about all auto execution stored procedures.

sp_helpstartup

Permission

Execute permission defaults to the public group. However, only a system administrator can make an auto execution stored procedure.

Table Used

master.dbo.sysobjects

See Also

CREATE PROCEDURE	sp_unmakestartup
sp_makestartup


sp_helptext System Stored Procedure

Prints the text of a rule, a default, or an unencrypted stored procedure, trigger, or view.

Syntax

sp_helptext objname

where

objname

Specifies the object about which the definition is to be displayed. The object must be in the current database.

Remarks

Executing sp_helptext prints out the text that was used to create the object. It looks for the text in the syscomments table of the current database only.

If an object (stored procedure, trigger or view) was created with the ENCRYPTION option, then sp_helptext will display garbled text.

With SQL Server 6.0, sp_helptext no longer displays the count of rows to be returned before it returns those rows.

Example

This example displays the text of the employee_insupd trigger. Since this trigger is in the pubs database, this example must be executed from pubs.

Permission

Execute permission defaults to the public group.

Table Used

syscomments

See Also

CREATE DEFAULT statement	CREATE TRIGGER statement
CREATE PROCEDURE statement	CREATE VIEW statement
CREATE RULE statement	sp_help


sp_helpuser System Stored Procedure

Reports information about the users of a database.

Syntax

sp_helpuser [username]

where

username

Is a user in the current database. If you don't specify a name, the system procedure reports on all users of the current database.

Remarks

If the specified user is not listed in the current database's sysusers table, the procedure checks to see if the user has an alias to another user or is a group name.

Examples

A.	List All Users

This example displays information about all users in the current database.

sp_helpuser

go

Users_name	ID_in_db	Group_name	Login_id	Default_db
----------	--------	----------	---------	----------
ann	4	hackers	ann	master
dbo	1	public	sa	master
guest	2	public	NULL	NULL
judy	3	hackers	judy	master
B.	List Information for a Single User

This example displays information about the database owner.

sp_helpuser dbo

Permission

Execute permission defaults to the public group.

Tables Used

master.dbo.syslogins, sysalternates, sysusers

See Also

GRANT statement	sp_help
REVOKE statement	sp_helpgroup
sp_adduser	USE statement
sp_dropuser


sp_lock System Stored Procedure

Reports information about locks.

Syntax

sp_lock [spid1 [, spid2]]

where

spid1

Is the SQL Server process ID number from master.dbo.sysprocesses. Execute sp_who to get the spid of the lock. If this parameter is not supplied, information about all locks is displayed.

spid2

Identifies another SQL Server process ID number to check for locks.

Remarks

Users can control locking by adding an optimizer hint to the FROM clause of a SELECT statement or by setting the TRANSACTION ISOLATION LEVEL with the SET statement. For syntax and restrictions, see the SELECT and SET statements.

In general, read operations acquire shared locks, and write operations acquire exclusive locks. Update locks are created at the page level and are acquired during the initial portion of an update operation when the pages are being read. Update locks are compatible with shared locks. Later, if the pages are changed, the update locks are promoted to exclusive locks.

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

The locktype column indicates whether the lock is a shared lock (Sh), an exclusive lock (Ex), or an update lock. This column also indicates whether the lock is held on a table (table or intent), a page, or an extent, and whether it is blocking (blk) another process. The blk suffix in the locktype indicates that this process is blocking another process that needs to acquire a lock. As soon as this process finishes, the other process(es) move forward.

When reading sp_lock information, use the OBJECT_NAME( ) function to get a table's name from its ID number. For example:

SELECT object_name(16003088)

Other information can also be displayed based on the spid returned from sp_lock. For information about using the Windows NT Performance Monitor to view information about a specific spid, see the DBCC statement.

Examples

A.	List All Locks

This example displays information about all locks currently held in SQL Server.

sp_lock

B.	List a Single Lock

This example displays information about locks currently held on spid 1.

sp_lock 1

Permission

Execute permission defaults to the public group.

Tables Used

master.dbo.spt_values, master.dbo.syslocks, master.dbo.sysprocesses

See Also

DBCC	SELECT statement
Functions	sp_who
KILL statement


sp_logdevice System Stored Procedure

Puts the syslogs system table, which contains the transaction log, on a separate database device.

Syntax

sp_logdevice dbname, database_device

where

dbname

Specifies which database has the syslogs table to put on a specific database device.

database_device

Is the name of the database device on which to put the syslogs table. This database device must have been referenced in a CREATE DATABASE or ALTER DATABASE statement for dbname. Run sp_helpdevice for a report on existing database devices.

Note  Because sp_logdevice affects only future allocations of space for syslogs, the first pages of your log remain on the same device as your data, leaving them temporarily vulnerable. However, using the LOG ON extension to CREATE DATABASE immediately puts the entire transaction log on a separate device.

Remarks

For better recovery and performance, put most databases and their transaction logs on separate database devices. You can keep small and non-critical databases on the same device as their log. In that case, however, use only the DUMP DATABASE statement (never DUMP TRANSACTION) for backups.

DBCC CHECKALLOC and sp_helplog show some pages for syslogs still allocated on the database device until after the next DUMP TRANSACTION statement. After that, transfer the transaction log to the device named when you executed sp_logdevice.

The size of the database device required for a transaction log varies according to the amount of update activity and the frequency of transaction log dumps. As a rule, allocate to the log device 10−25 percent of the space you allocate to the database itself. It is best to start small, since space allocated to a transaction log device cannot be reclaimed.

To increase the amount of allocated storage space on the transaction log database device, give the logical name of the log database device in the ON clause when you execute the ALTER DATABASE statement. Then execute sp_logdevice to make the newly allocated space available to the log.

The device or segment on which you put syslogs is used only for the syslogs table. If you want to increase the amount of storage space allocated to the rest of the database, specify any database device other than the log database device when you execute the ALTER DATABASE statement.

Use the DISK INIT statement to format a new physical database device on which to store databases and transaction logs.

For further details, see the Microsoft SQL Server Administrator's Companion.

Example

This example shows how sp_logdevice is used after altering a database. In this example the products database is altered by 2 MB and the log is then moved to that 2-MB segment.

ALTER DATABASE products ON logdevice = 2

go

sp_logdevice products, logdevice

Permission

Execute permission defaults to the database owner of the named database.

Tables Used

master.dbo.sysdatabases, master.dbo.sysdevices, master.dbo.sysusages

See Also

ALTER DATABASE	DUMP
CREATE DATABASE	sp_extendsegment
DBCC	sp_helpdevice
DISK INIT


sp_makestartup System Stored Procedure

Sets a stored procedure for auto execution. Auto execution stored procedures are executed every time the server is started.

Syntax

sp_makestartup procedure_name

where

procedure_name

Specifies the name of the procedure to start automatically when the server is started.

Remarks

There is no limit to the number of startup procedures you can have, but be aware that each auto execution procedure consumes one connection. If you need to execute multiple procedures at startup but don't need to execute them in parallel, you can make one procedure the startup procedure and have that procedure call the other procedures. For more information, see the CREATE PROCEDURE statement.

Example

This example makes the update_all_stats procedure an auto execution procedure.

sp_makestartup update_all_stats

Permission

Only the system administrator can use this procedure.

Tables Used

master.dbo.sysobjects, master.dbo.syscolumns

See Also

CREATE PROCEDURE	sp_unmakestartup
sp_helpstartup


sp_monitor System Stored Procedure

Displays statistics about SQL Server.

Syntax

sp_monitor

Remarks

SQL Server keeps track in a series of global variables of how much work it has done. Executing sp_monitor displays the current values of these global variables 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.

These are the columns in the sp_monitor report:

Column	Description
last_run	The time sp_monitor was last run.
current_run	The time sp_monitor is being run.
seconds	The number of elapsed seconds since sp_monitor was run.
cpu_busy	The number of seconds that the server computer's CPU has been doing SQL Server work.
io_busy	The number of seconds that SQL Server has spent doing input and output operations.
idle	The number of seconds that SQL Server has been idle.
packets_received	The number of input packets read by SQL Server.
packets_sent	The number of output packets written by SQL Server.
packet_errors	The number of errors encountered by SQL Server while reading and writing packets.
total_read	The number of reads by SQL Server.
total_write	The number of writes by SQL Server.
total_errors	The number of errors encountered by SQL Server while reading and writing.
connections	The number of logins or attempted logins to SQL Server.
Example

This example reports information about how busy SQL Server has been.

sp_monitor

go

last_run	current_run	seconds
------------------	--------------------	-------------
Mar 29 1993 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)
Permission

Execute permission defaults to the system administrator, who can transfer it to other users.

Table Used

master.dbo.spt_monitor

See Also

sp_who	Variables


sp_password System Stored Procedure

Adds or changes a password for a SQL Server login ID.

Syntax

sp_password old, new [, login_id]

where

old

Is the user's old password, which is encrypted in master.dbo.syslogins. The default password for all users is NULL. The system administrator can specify NULL for this parameter no matter what the user's old password was. However, if the system administrator gives any value besides NULL, SQL Server checks the value against master.dbo.syslogins and rejects it if it is wrong.

new

Is the user's new password.

login_id

Is an option that only the system administrator can use to change any user's password.

Remarks

Any user can use sp_password to change his or her own password. Only the system administrator can change someone else's password (using the login_id parameter).

The old parameter is checked against the existing password for the user login_id (unless the user executing the procedure is the system administrator and the old parameter is NULL) and must match for the password to be changed. Passwords are encrypted in master.dbo.syslogins.password.

If front-end programs require the same password on remote servers as on the local server, a user must change his or her password on all the remote servers before changing the local password. The sp_password procedure should be executed as a call to a remote stored procedure on each remote server.

Permission

Execute permission defaults to the public group. Each member of public has permission to change only his or her own password. The system administrator can change any user's password.

Table Used

master.dbo.syslogins

Examples

A.	SA Can Change Password Without Knowing the Former Password

In this example, the system administrator has changed Victoria's password to ok. Notice that NULL is not enclosed in quotation marks.

sp_password NULL, ok, Victoria

B.	A User Changes Her Password

In this example, the user Victoria changes her password from ok to coffee.

sp_password ok, coffee

See Also

sp_addlogin	xp_grantlogin
sp_adduser	xp_logininfo
sp_defaultdb	xp_revokelogin


sp_placeobject System Stored Procedure

Puts future space allocations for a table or index on a particular segment.

Syntax

sp_placeobject segname, objname

where

segname

Specifies the segment where the table or index is to be located.

objname

Specifies the table or index whose subsequent space allocation is to be put on the segment segname.

Remarks

You cannot change the location of future space allocations for system tables.

Putting a table or index on a particular segment does not affect the location of any existing table or index data. It affects only future space allocation. By changing the segment used by a table or index, the data can be spread across multiple segments.

If a table or index is created with the CREATE TABLE or CREATE INDEX statement, you can specify a segment. If no segment is specified, the data will go on the DEFAULT segment.

When sp_placeobject is used to split a table or index across more than one disk fragment, the diagnostic DBCC statement reports on the data located on the fragments in use for storage before sp_placeobject was executed. These messages can be ignored.

A table with text or image columns has an additional entry in the sysindexes table for the text chain, with the name column set to the name of the table preceded by the letter t and an indid of 255. You can use sp_placeobject to store the text chain on a separate device, giving both the table name and the name of the text chain from sysindexes.

Example

This example causes all subsequent space allocation for the index named employee_nc on the table employee to be placed on the segment named INDEXES.

sp_placeobject indexes, 'employee.employee_nc'

EXEC sp_placeobject textseg, 'mytab.tmytab'

Permission

Execute permission defaults to the table owner, database owner, and system administrator.

Tables Used

sysindexes, sysobjects, syssegments

See Also

DBCC	sp_help
sp_addsegment	sp_helpindex
sp_dropsegment	sp_helpsegment
sp_extendsegment


sp_processmail System Stored Procedure

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 SQL Server. It uses the xp_sendmail extended stored procedure to return the results set back to the message sender.

Syntax

sp_processmail [@subject = subject] [[,] @filetype = filetype]
[[,] @separator = separator] [[,] @set_user = user] [[,] @dbuse = dbname]

where

@subject = subject

Specifies the subject line of mail messages to interpret as queries for SQL Server. When specified, sp_processmail will process only messages that have this subject. By default, SQL Server processes all mail messages as though they were queries.

@filetype = filetype

Specifies the file extension to be used when sending the results set file back to the message sender. The default is .TXT.

@separator = separator

Specifies the column separator (field terminator) for each column of the results set (this information is passed to the xp_sendmail extended stored procedure to return the results set back to the message sender). The default is 'TAB', which is a special case for the tab character to be used between columns.

@set_user = user

Specifies the security context in which the query should be run. The default is 'guest' (the guest user).

@dbuse = dbname

Specifies the database context in which the query should be run. The default is the master database.

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 the SQL Executive to schedule an sp_processmail task. This will process mail at the specified frequency and record an informational message with the number of queries processed in the task history.

Results are sent as an attached file. The complete filename sent consists of "SQL" followed by a random string of numbers and then the specified extension (@filetype), for example, SQL356.TXT.

Important  To get an appropriate icon attached to the mail message, make sure that the file type is associated properly. Create a file association by using the Windows NT File Manager. To associate the appropriate application with the file from the File Manager File menu, choose Associate. For example, to return .CSV files to a client as Excel files, associate the .CSV extension with the Microsoft Excel program. Any existing associations (for example, .TXT files are associated with NOTEPAD.EXE) will be handled correctly. If the mail recipient has the same association, he or she can double-click on the icon (in the returned mail message) and automatically load the application.

Errors received when the query is processed will be returned to the message sender through the message text. When the results set is returned to the client, xp_sendmail is called with the @echo_error parameter set to 'true'. The messages sent also include a row count (number of rows affected) by the query.

If desired, different sp_processmail tasks 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 @dbuse = 'pubs'. Different database queries and groupings could have other formatting structures. For example, distribution tasks could have @subject = 'SQL:distribution' and @dbuse = 'distribution'. Any of these can be scheduled tasks with the SQL Executive. For more information on scheduling events, see the Microsoft SQL Server Administrator's Companion.

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 don't delete the message after processing, (issue the xp_readmail a second time with @peek set to 'false').

•	Send the query results in the body of the e-mail message by calling the xp_sendmail extended stored procedure with @attach_results 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.

Example

This example processes all messages in the pubs database with results sets returned to the client in CSV (comma separated values) format.

sp_processmail @filetype = 'CSV', @separator = ',', @dbuse = 'pubs'

Permission

Permission to use this procedure defaults to the system administrator.

See Also

sp_addtask	xp_readmail
xp_deletemail	xp_sendmail
xp_findnextmsg


sp_recompile System Stored Procedure

Causes each stored procedure and trigger that uses the specified table to be recompiled the next time the stored procedure and triggers are run.

Syntax

sp_recompile tabname

where

tabname

Specifies a table in the current database.

Remarks

The queries used by stored procedures and triggers are optimized only once, when they are compiled. As you add indexes or make other changes to your database that affect its statistics, your compiled stored procedures and triggers may lose efficiency. By recompiling the stored procedures and triggers that act on a table, you can reoptimize the queries for greatest efficiency.

The sp_recompile system procedure looks for a table in the current database only. It cannot be used on system tables.

Example

This example causes each trigger and stored procedure that uses the titles table to be recompiled the next time it is run.

sp_recompile titles

Permission

Execute permission defaults to the public group.

Table Used

sysobjects


sp_remoteoption System Stored Procedure

Displays or changes remote login options.

Syntax

sp_remoteoption [remoteserver, loginame, remotename, optname, {true | false}]

where

remoteserver

Specifies the remote server that has the remote login to which the option should apply.

loginame

Is the login name that identifies the remote login for the remoteserver, loginame, remotename combination.

remotename

Is the remote username that identifies the remote login for the remoteserver, loginame, remotename combination.

optname

Is the option you want to set or turn off. Currently, there is only one option, trusted, which means that the local server accepts remote logins from other servers without verifying user access for the particular remote login. The default is untrusted (trusted set to false), which results in password verification. SQL Server understands any unique string that is part of the option name. Use quotation marks around the option name if it includes embedded blanks.

true | false

Specifies whether to set the option. Choose true if you want to set the option, false if you want to turn it off.

Remarks

To display a list of the remote login options, execute sp_remoteoption with no parameters.

Only the system administrator can set or turn off particular server options. For details on remote login options, see the Microsoft SQL Server Administrator's Companion.

Examples

A.	List Options

This example lists the remote login options:

sp_remoteoption

go

Settable remotelogin options.

remotelogin_option

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

trusted

B.	Trusted Logins

This example defines the remote login from the remote server ACCOUNTS to be trusted (the password will not be checked).

sp_remoteoption ACCOUNTS, salesmgr, chris, trusted, TRUE

C.	Untrusted Logins

This example defines the remote login from the remote server ACCOUNTS to be untrusted (the password will be checked).

sp_remoteoption ACCOUNTS, salesmgr, chris, trusted, FALSE

Permission

Execute permission without parameters (display options only) defaults to the public group. Only the system administrator can use sp_remoteoption with parameters (to change an option).

Tables Used

master.dbo.sp_values, master.dbo.sysremotelogins, master.dbo.syssrvers

See Also

sp_helpremotelogin


sp_rename System Stored Procedure

Changes the name of a user-created object in the current database.

Syntax

sp_rename objname, newname [, COLUMN | INDEX ]

where

objname

Is the original name of the user object (table, view, column, stored procedure, trigger, default, or rule) or datatype. If the object to be renamed is a column in a table, objname must be in the form 'table.column'. If the object to be renamed is an index, objname must be in the form 'table.index'. The table name is not included in newname. You can rename an object in the current database only, and only if you own it. This rule holds for all users, including the system administrator and database owner. Users can change the names only of those objects they own. The database owner or system administrator can change the name of any user's objects by using SETUSER. For details, see the SETUSER statement.

newname

Is the new name of the object or datatype. Names of objects and datatypes must follow the rules for identifiers. When the table name is required in objname, it is excluded from newname.

COLUMN | INDEX

Specifies whether the object being renamed is a column or an index. Specifying this parameter resolves any possible conflict that can occur when column names and index names are identical.

Remarks

You can change the name of an object or datatype in the current database only. The names of most system datatypes 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.

Examples

A.	Rename a Table

This example renames the titles table books.

sp_rename titles, books

B.	Rename a Column

This example renames the title column in the books table name.

sp_rename 'books.title', name, COLUMN

Permission

Execute permission defaults to the object owner.

Tables Used

syscolumns, sysindexes, sysobjects, systypes

See Also

ALTER TABLE	CREATE VIEW
CREATE DEFAULT	Datatypes
CREATE PROCEDURE	sp_addtype
CREATE RULE	sp_depends
CREATE TABLE	sp_renamedb
CREATE TRIGGER


sp_renamedb System Stored Procedure

Changes the name of a database.

Syntax

sp_renamedb oldname, newname

where

oldname

Is the original name of the database.

newname

Is the new name of the database. Names of objects and datatypes must follow the rules for identifiers.

Remarks

Only the system administrator can change the name of a database. The system administrator must put a database in single-user mode by using sp_dboption before renaming it, and must restore it to multi-user mode afterward.

Example

This example changes the name of the accounting database to financial.

sp_renamedb accounting, financial

Permission

Execute permission defaults to the system administrator.

Table Used

master.dbo.sysdatabases

See Also

CREATE DATABASE	sp_depends
sp_changedbowner	sp_helpdb
sp_dboption	sp_rename


sp_serveroption System Stored Procedure

For more updated SQL Server 6.5 syntax, see sp_serveroption.

Sets server options.

Syntax

sp_serveroption [server_name, optname, {true | false}]

where

server_name

Specifies the server for which you want to set the option.

optname

Is the type of server. Can be:

dist	Distribution server
dpub	Combination publisher/subscriber
pub	Publication server
rpc	Remote server
sub	Subscription server
The default is rpc.

true | false

Specifies whether to set the option. Choose true if you want to set the option, false if you want to turn it off.

Remarks

To display a list of the server options, execute sp_serveroption with no parameters.

Examples

A.	List Options

This example lists the server options.

sp_serveroption

go

Settable server options.

server_option

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

dist

dpub

pub

rpc

sub

B.	Set an Option

This example sets the server as a combination publisher/subscriber server.

sp_serveroption ACCOUNTS, dpub, TRUE

Permission

Only the system administrator can use sp_serveroption to set server options.

Tables Used

master.dbo.sp_values, master.dbo.sysserver

See Also

sp_addpublisher	sp_helpserver
sp_droppublisher.


sp_setlangalias System Stored Procedure

Assigns or changes the alias for an alternate language.

Syntax

sp_setlangalias language, alias

where

language

Is the name of the language.

alias

Is the new local alias for the alternate language.

Remarks

The alias replaces the current value of the syslanguages.alias for the original language.

The new alias can be used in place of the original language by the SET LANGUAGE statement.

Example

This example assigns the alias name français to the original language name French.

sp_setlangalias français, french

Permission

Execute permission defaults to the system administrator.

Table Used

master.dbo.syslanguages

See Also

SET	sp_helplanguage
sp_droplanguage


sp_spaceused System Stored Procedure

Displays the number of rows, the disk space reserved, and the disk space used by a table in a database, or displaces the disk space reserved and used by an entire database.

Syntax

sp_spaceused [objname] [[,] @updateusage = {true | false}]

where

objname

Specifies the name of the table for which space usage information (reserved and allocated space) is requested.

@updateusage

Specifies 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). Setting this option to true could take a significant amount of time. If preferred, DBCC UPDATEUSAGE can be run separately. See the remarks for more information.

Remarks

Executing 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 no table (objname) is given, sp_spaceused reports on the space used by the entire current database.

After you drop an index, sp_spaceused reports inaccurate information. This is a known limitation. However, sp_spaceused provides a quick, rough estimate. If you notice incorrect values when you execute sp_spaceused, run DBCC UPDATEUSAGE to correct the inaccuracies. Because this statement takes some time to run on large tables or databases use it only when you suspect incorrect values being returned or when other users are not active.

Examples

A.	Space Information About a Table

This example reports on 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.

sp_spaceused titles

go

name     rows   reserved    data     index_size     unused
-------- ------ ----------- -------- -------------- -------------
titles   18     48 KB       6 KB     8 KB           34 KB

B.	Updated Space Information About a Complete Database

This example shows a summary of space used in the current database with the optional @updateusage.

sp_spaceused @updateusage = 'TRUE'

go

DBCC UPDATEUSAGE: messages are printed...
DBCC execution completed. If DBCC printed error messages, see your System Administrator.

database_name                  database_size      unallocated space
------------------------------ ------------------ ------------------
pubs                           3.00 MB            1.69 MB

reserved          data             index_size        unused
----------------- ---------------- ----------------- ---------------
1344 KB           300 KB           116 KB            928 KB

Permission

Execute permission defaults to the public group.

Tables Used

master..sysusages, sysindexes, sysobjects

See Also

CREATE INDEX	DROP TABLE
CREATE TABLE	sp_help
DROP INDEX	sp_helpindex


sp_unbindefault System Stored Procedure

Unbinds (removes) a default from a column or from a user-defined datatype in the current database.

Syntax

sp_unbindefault objname [, futureonly]

where

objname

Specifies the table and column or the user-defined datatype from which the default is to be unbound. If the parameter is not of the form 'table.column', then objname is recognized as a user-defined datatype. When unbinding a default from a user-defined datatype, any columns of that datatype that have the same default as the user datatype are also unbound. Columns of that datatype with defaults bound directly to them are unaffected.

futureonly

Used only when unbinding a default from a user-defined datatype, this option prevents existing columns of that datatype from losing this default. It is never used when unbinding a default from a column.

Remarks

Columns of the user-defined datatype lose their current default unless their default has previously been changed or the futureonly option is used.

To display the text of a default, execute sp_helptext with the default name as the parameter.

When you unbind a default, the information about the binding is removed from the syscolumns table if the default was bound to a column, and from the systypes table if the default was bound to a user-defined datatype.

Examples

A.	Unbind a Default from a Column

This example unbinds the default from the startdate column of the employees table.

sp_unbindefault 'employees.startdate'

B.	Unbind a Default from a User-defined Datatype

This example unbinds the default from the user-defined datatype ssn and all columns of that type. It unbinds existing and future columns of that type.

sp_unbindefault ssn

C.	Use futureonly

This example unbinds future uses of the user datatype ssn, but existing columns of type ssn are unaffected.

sp_unbindefault ssn, FUTUREONLY

Permission

Execute permission defaults to the specified object owner.

Tables Used

syscolumns, sysobjects, systypes

See Also

CREATE DEFAULT	sp_bindefault
DROP DEFAULT	sp_helptext


sp_unbindrule System Stored Procedure

Unbinds a rule from a column or a user-defined datatype in the current database.

Syntax

sp_unbindrule objname [, futureonly]

where

objname

Specifies the table and column or the user-defined datatype from which the rule is to be unbound. If the parameter is not of the form 'table.column', objname is recognized as a user-defined datatype. When unbinding a rule from a user-defined datatype, any columns of that datatype that have the same rule as the user datatype are also unbound. Columns of that datatype with rules bound directly to them are unaffected.

futureonly

Used only when unbinding a rule from a user-defined datatype, this option prevents existing columns of that datatype from losing this rule. It is never used when unbinding a rule from a column.

Remarks

The rule is unbound from all existing columns of the user-defined datatype unless their default has previously been changed or the futureonly option is used.

To display the text of a rule, execute sp_helptext with the rule name as the parameter.

When you unbind a rule, 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 datatype.

Examples

A.	Unbind a Rule from a Column

This example unbinds the rule from the startdate column of the employees table.

sp_unbindrule 'employees.startdate'

B.	Unbind a Rule from a User-defined Datatype

This example unbinds the rule from the user-defined datatype ssn. It unbinds the rule from existing and future columns of that type.

sp_unbindrule ssn

C.	Use futureonly

This example unbinds the rule from the user-defined datatype ssn without affecting existing ssn columns.

sp_unbindrule ssn, FUTUREONLY

Permission

Execute permission defaults to the object owner.

Tables Used

syscolumns, sysobjects, systypes

See Also

CREATE RULE	sp_bindrule
DROP RULE	sp_helptext


sp_unmakestartup System Stored Procedure

Discontinues auto execution of the stored procedure.

Syntax

sp_unmakestartup procedure_name

where

procedure_name

Specifies the name of the procedure that should no longer automatically execute when the server is started.

Example

This example unmarks the update_all_stats procedure from being an auto execution procedure.

sp_unmakestartup update_all_stats

Permission

Only the system administrator can use this procedure.

Tables Used

master.dbo.sysobjects

See Also

CREATE PROCEDURE	sp_makestartup
sp_helpstartup


sp_who System Stored Procedure

For more updated SQL Server 6.5 syntax, see sp_who.

Reports information about current SQL Server users and processes.

Syntax

sp_who [login_id | 'spid']

where

login_id

Is the user's login ID on SQL Server. If no name is specified, the procedure reports on all active users of SQL Server.

spid

Specifies a specific process. You can supply a process number as a parameter if you enclose it in quotation marks (SQL Server expects a char type).

Remarks

This system stored procedure reports information about a specified user, a specified SQL Server process, or all users currently running a process on SQL Server. Executing sp_who without parameters reports which users are running what processes in all databases.

Examples

A.	List All Current Processes

This example shows how to view all current processes by executing sp_who without parameters. The blk column contains the system process ID of a blocking process; this value references the spid column of this table (self-referencing). A blocking process (which may have an exclusive lock) is one that is holding resources that another process needs. In this example, process 11 (a SELECT on a table) is blocked by process 10 (an uncommitted transaction).

sp_who

go

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   Mary     WKSTA1    0     pubs       AWAITING COMMAND
11     runnable   Joe      WKSTA5    10    pubs       SELECT

B.	List a Specific User's Process

This example shows how to view information about a single current user by loginame or spid.

sp_who Mary

Or

sp_who '10'

Permission

Execute permission defaults to the public group.

Table Used

master.dbo.sysprocesses

See Also

KILL	sp_lock


Subqueries

You can nest a SELECT statement inside a SELECT, INSERT, UPDATE, or DELETE statement, another subquery, or anywhere an expression is allowed. However, the expression that includes the subquery must return true or false. Usually a subquery is nested inside the WHERE or HAVING clause of an outer SELECT, INSERT, UPDATE, DELETE, or another subquery. Many SQL statements that include subqueries can also be formulated as joins.

Syntax

A subquery can be used in these contexts:

expression comparison_operator [ANY | ALL | SOME] (subquery)

expression [NOT] IN (subquery)

[NOT] EXISTS (subquery)

A subquery has the following restricted SELECT syntax:

(SELECT [ALL | DISTINCT] subquery_select_list
[FROM {table_name | view_name}[optimizer_hints]
[[, {table_name2 | view_name2}[optimizer_hints]
[..., {table_name16 | view_name16}[optimizer_hints]]]
[WHERE clause]
[GROUP BY clause]
[HAVING clause])

where

expression

Is a standard expression. For details, see the Expressions and Search Conditions topics.

comparison_operator

Is a standard comparison operator. For details, see the Operators topic.

ANY | SOME

Are synonymous. When used, the expression evaluates to true if the comparison is true for at least one row of subquery. The expression evaluates to false if the comparison returns no rows or if the comparison is false for all rows in the subquery. Otherwise, the expression is unknown.

ALL

When used the expression evaluates to true if the comparison returns no rows or if the comparison is true for all rows in the subquery. The expression evaluates to false if the comparison is false for at least one of the rows in the subquery. Otherwise, the expression is unknown.

DISTINCT

Includes only unique rows in the results. Cannot be used with subqueries that include a GROUP BY clause.

subquery_select_list

Is a restricted select list for use with subqueries introduced with IN or a comparison operator. It consists of one expression. If a column name is used in the WHERE clause of the outer statement, a column name in the subquery select list must be join-compatible with it.

The select list must consist of only one column name except for the EXISTS subquery, in which case an asterisk (*) is usually used in place of the single column name. Do not specify more than one column name or a column of text and image datatype; these are not allowed in subqueries.

Examples

A.	Simple Subqueries

Note that the syntax for EXISTS is somewhat different from the syntax for the other keywords; it does not take an expression between WHERE and itself. In the following examples, the queries, which are semantically equivalent, illustrate the difference.

SELECT DISTINCT pub_name

FROM publishers

WHERE EXISTS

(SELECT *

FROM titles

WHERE pub_id = publishers.pub_id

AND type = 'business')

Or

SELECT distinct pub_name

FROM publishers

WHERE pub_id IN

(SELECT pub_id

FROM titles

WHERE type = 'business')

B.	Correlated Subquery

A correlated (or repeating) subquery depends on the outer query for its values. It is executed repeatedly, once for each row that might be selected by the outer query. Here is an example:

SELECT DISTINCT au_lname, au_fname

FROM authors

WHERE 100 IN

(SELECT royaltyper

FROM titleauthor

WHERE titleauthor.au_id = authors.au_id)

The 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 SQL Server examines different rows in authors.

C.	Correlated Subquery with GROUP BY and HAVING Greater Than ALL

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.

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)

D.	Multiple Correlated Subqueries

This example finds the names of authors who have participated in writing at least one popular computing book.

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

See Also

DELETE	INSERT
EXECUTE	SELECT
Expressions	UPDATE
Functions


System Tables

System tables are tables used to store information about the system (the system catalog) or an individual database (the database catalog). The system catalog consists of system tables found only in the master database. The database catalog consists of system tables found in every database.

In SQL Server 6.0, the addition of replication and the SQL Executive has added new system tables based on the type of database used in replication and scheduling of events.

The system tables have been categorized by the types of related information:

•	Database Catalog

•	System Catalog

•	Replication Tables

•	SQL Executive


System Tables-Database Catalog

The following system tables are found within every user-defined or system database, including the master database:

Table	Description
sysalternates	Contains one row for each SQL Server user mapped to a user of the current database.
sysarticles	Contains a row for each of the articles posted by the publication server.
syscolumns	Contains one row for every column in every table and view, and a row for each parameter in a stored procedure.
syscomments	Contains entries for each view, rule, default, trigger, and stored procedure.
sysconstraints	Contains one row for each PRIMARY KEY, FOREIGN KEY, CHECK, DEFAULT, and UNIQUE constraint.
sysdepends	Contains one row for each procedure, view, or table that is referenced by a procedure, view, or trigger.
sysindexes	Contains one row for each clustered index and one row for each nonclustered index. These indexes are the result of a CREATE INDEX statement or the CREATE TABLE statement with a PRIMARY KEY or UNIQUE constraint. Additionally, sysindexes contains one row for each table that has no clustered index and one row for each table that contains text or image columns.
syslogs	Contains the transaction log and is used by SQL Server for recovery and roll forward — it is for internal use only.
sysobjects	Contains one row for each database object and (in tempdb only) temporary object.
sysprocedures	Contains entries for each view, default, rule, trigger, and stored procedure.
sysprotects	Contains user permissions information — entries for each GRANT and REVOKE statement that has been executed.
syspublications	Contains a row for each of the publications posted by the publication server.
sysreferences	Contains one row for each FOREIGN KEY constraint.
syssegments	Contains one row for each segment (named collection of disk pieces).
syssubscriptions	Associates the IDs of each publication event with the IDs of all subscription servers expecting to receive the data.
systypes	Contains one row for each system-supplied and each user-defined datatype.
sysusers	Contains one row for each user allowed to use the database and one row for each group.
The section that follows these tables lists all tables in alphabetical order and provides detailed information.


sysalternates (all databases)

Contains one row for each SQL Server user mapped to a user (or with an alias) of the current database. When a user tries to access a database, SQL Server looks for a valid uid entry in sysusers. If one is not found, it looks in sysalternates.suid. If the user's suid is found there, the user is treated as the database user whose suid is listed in sysalternates.altsuid.

Column	Datatype	Description
suid	smallint	Server user ID of the user being mapped.
altsuid	smallint	Server user ID of the user to whom another user is mapped.
Index

sysalternates clustered, unique on suid

Referenced by Stored Procedures

sp_addalias	sp_dropalias	sp_dropuser
sp_adduser	sp_droplogin	sp_helpuser
sp_changedbowner


sysarticles (new - all databases)
sysarticles (all databases)

Has a row for each of the articles posted by the publishing server.

Column	Datatype	Description
artid	int	An identity column providing a unique ID number for the article.
columns	varbinary(32)	The columns in the tables that are being published.
creation_script	varchar(127)	The schema script for the article.
del_cmd	varchar(255)	Command to execute upon delete, else construct from the log.
description	varchar(255)	Descriptive entry for the article.
dest_table	varchar(30)	Name of the destination table.
filter	int	The stored procedure ID, used for horizontal partitioning.
filter_clause	text	The WHERE clause of the article, used for horizontal filtering.
ins_cmd	varchar(255)	Command to execute upon insert, else construct from the log.
name	varchar(30)	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	A pre-creation command for drop table, delete table, or truncate: 0 None  1 Drop  2 Delete  3 Truncate
status	tinyint	Bitmap used to describe a property of the column or the parameter:  0x08  The column allows null values. 0x40  The parameter is an OUTPUT parameter. 0x80  The column is an identity column.
sync_objid	int	The ID of the table or view that represents the article definition.
type	tinyint	The 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	varchar(255)	Command to execute upon update, or else construct from the log.
Index

unc1sysarticles nonclustered, unique on artid, pubid

Referenced by Stored Procedures

sp_addarticle	sp_droparticle	sp_helparticlecolumns
sp_addsubscription	sp_droppublication	sp_helppublication
sp_articlecolumn	sp_dropsubscription	sp_helpsubscription
sp_changearticle	sp_enumfullsubscribers	sp_subscribe
sp_changesubscription	sp_helparticle	sp_unsubscribe
sp_changesubstatus


syscolumns (all databases)

For more updated SQL Server 6.5 syntax, see syscolumns System Table.

Contains one row for every column in every table and view, and a row for each parameter in a stored procedure.

Column	Datatype	Description
id	int	ID of the table to which this column belongs or of the stored procedure with which this parameter is associated.
number	smallint	Subprocedure number when the procedure is grouped (0 for nonprocedure entries).
colid	tinyint	Column ID.
status	tinyint	Bitmap used to describe a property of the column or the parameter:  0x08   The column allows null values. 0x40   The parameter is an OUTPUT parameter. 0x80   The column is an identity column.
type	tinyint	Physical storage type; copied from systypes.
length	tinyint	Physical length of data; copied from systypes or supplied by the user.
offset	smallint	Offset into the row where this column appears; if negative, variable-length column.
usertype	smallint	User type ID; copied from systypes.
cdefault	int	ID of the stored procedure that generates the default value for this column.
domain	int	ID of the stored procedure that contains the rule for this column.
name	varchar(30)	Column name.
printfmt	varchar(255)	Reserved.
prec	tinyint	Level of precision for this column.
scale	tinyint	Scale for this column.
Index

syscolumns clustered, unique on id, number, colid

Referenced by Stored Procedures

sp_articlecolumn	sp_help	sp_special_columns
sp_bindefault	sp_helparticle	sp_sproc_columns
sp_bindrule	sp_helparticlecolumns	sp_statistics
sp_column_privileges	sp_helprotect	sp_tables
sp_columns	sp_pkeys	sp_unbindefault
sp_droptype	sp_rename	sp_unbindrule
sp_fkeys


syscomments (all databases)

Contains entries for each view, rule, default, trigger, CHECK constraint, DEFAULT constraint, and stored procedure. The text field contains the original SQL definition statements. Since text is often longer than 255 characters, entries often span rows. Each object can occupy as many as 255 rows.

Column	Datatype	Description
id	int	Object ID to which this text applies.
number	smallint	Number within procedure grouping, if grouped. 0 for nonprocedure entries.
colid	tinyint	Row sequence number for object definitions longer than 255 characters.
texttype	smallint	0 User-supplied comment (users can add entries that  describe an object or column) 1 System-supplied comment (for views, rules, defaults,  triggers, and stored procedures) 4 Encrypted comments (applies to procedures, triggers  and views)
language	smallint	Reserved.
text	varchar(255)	Actual text of the SQL definition statement.
Index

syscomments clustered, unique on id, number, colid, texttype

Referenced by Stored Procedures

sp_helpconstraint	sp_helpextendedproc	sp_helptext


sysconstraints (new - all databases)
sysconstraints (all databases)

Contains mappings of constraints to the objects that own the constraints.

Column	Datatype	Description
constid	int	Constraint ID.
id	int	ID of the table that owns the constraint.
colid	tinyint	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.
Index

csysconstraints clustered located on id, colid

unc1sysconstraints nonclustered, unique on constid


sysdepends (all databases)

Contains one row for each procedure, view, or table that is referenced by a procedure, view, or trigger.

Column	Datatype	Description
id	int	Object ID.
number	smallint	Procedure number.
depid	int	Dependent object ID.
depnumber	smallint	Dependent procedure number.
depdbid	smallint	Reserved.
depsiteid	smallint	Reserved.
status	smallint	Internal status information.
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.
Index

sysdepends clustered, ignore duplicate key, unique on id, number, depid, depnumber, depdbid, depsiteid

Referenced by Stored Procedures

sp_depends	sp_rename


sysindexes (all databases)

For more updated SQL Server 6.5 syntax, see sysindexes System Table.

Contains one row for each clustered index and one row for each nonclustered index. These indexes are the result of a CREATE INDEX statement or the CREATE TABLE statement with a PRIMARY KEY or UNIQUE constraint. Additionally, sysindexes contains one row for each table that has no clustered index and one row for each table that contains text or image columns.

Column	Datatype	Description
name	varchar(30)	Name of table (for indid = 0 or 255). Otherwise, name of index.
id	int	ID of table (for indid = 0 or 255). Otherwise, ID of table to which the index belongs.
indid	smallint	ID of index: 0 Table 1 Clustered index >1 Nonclustered 255 Entry for tables that have text or  image data
dpages	int	For indid = 0 or indid = 1, dpages is the count of used data-only pages. For indid = 255, rows is set to 0. Otherwise, dpages is the count of leaf-level index pages.
reserved	int	For indid = 0 or indid = 1, reserved is the total of pages allocated for all indexes on the table and the data pages. For indid = 255, reserved is the total pages allocated for text or image data. Otherwise, reserved is the total count of pages allocated only for this index.
used	int	For indid = 0 or indid = 1, used is the total count of pages used for all indexes on the table and the data pages. For indid = 255, used is the total pages used for text or image data. Otherwise, used is the total count of pages used only for this index.
rows	int	The data-level row count based on indid = 0 or indid = 1. This value is repeated for  indid > 1. For indid = 255, rows is set to 0.
first	int	Pointer to first data or leaf page.
root	int	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.
distribution	int	Pointer to distribution page (if entry is an index).
OrigFillFactor	tinyint	The 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.
segment	smallint	Number of segment in which this object resides.
status	smallint	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
rowpage	smallint	Maximum count of rows per page.
minlen	smallint	Minimum size of a row.
maxlen	smallint	Maximum size of a row.
maxirow	smallint	Maximum size of a nonleaf index row.
keycnt	smallint	Number of keys.
keys1	varbinary(255)	Description of key columns (if entry is an index).
keys2	varbinary(255)	Description of key columns (if entry is an index).
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.
Index

sysindexes clustered, unique on id, indid

Referenced by Stored Procedures

sp_dropsegment	sp_helplog	sp_rename
sp_fkeys	sp_helpsegment	sp_spaceused
sp_helpconstraint	sp_pkeys	sp_special_columns
sp_helpindex	sp_placeobject	sp_statistics


syslogs (all databases)

Contains the transaction log. It is used by SQL Server for recovery and roll forward. It is for internal use only.

You cannot delete from, insert into, or update syslogs.

Column	Datatype	Description
xactid	binary(6)	Transaction ID
op	tinyint	Update-operation number
Index

This table does not have any indexes.


sysobjects (all databases)

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	Datatype	Description
name	varchar(30)	Object name.
id	int	Object ID.
uid	smallint	User ID of owner object.
type	char(2)	One of the following object types:  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 Stored procedure for replication S System table  TR Trigger U User table V View X Extended stored procedure
userstat	smallint	Application-dependent type information.
sysstat	smallint	Internal-status information.
indexdel	smallint	Index delete count (incremented if an index is deleted).
schema	smallint	Count of changes in schema of a given object (incremented if a rule or default is added).
refdate	datetime	Reserved for future use.
crdate	datetime	Indicates the date that the object was created.
version	datetime	Reserved for future use.
deltrig	int	Stored-procedure ID of a delete trigger.
instrig	int	Stored-procedure ID of an insert trigger.
updtrig	int	Stored-procedure ID of an update trigger.
seltrig	int	Reserved.
category	int	Used for publication, constraints, and identity.
cache	smallint	Reserved.
Index

sysobjects clustered, unique on id

ncsysobjects nonclustered, unique on name, uid

Referenced by Stored Procedures

sp_addarticle	sp_droptype	sp_rename
sp_bindefault	sp_dropuser	sp_replica
sp_bindrule	sp_fkeys	sp_spaceused
sp_changearticle	sp_help	sp_sproc_columns
sp_changesubstatus	sp_helparticle	sp_statistics
sp_column_privileges	sp_helpconstraint	sp_stored_procedures
sp_columns	sp_helpextendedproc	sp_table_privileges
sp_depends	sp_helprotect	sp_tables
sp_droparticle	sp_pkeys	sp_unbindefault
sp_dropgroup	sp_placeobject	sp_unbindrule


sysprocedures (all databases)

Contains entries for each view, default, rule, trigger, CHECK constraint, DEFAULT constraint, and stored procedure. The plan or sequence tree for each object is stored in binary form. If the sequence tree doesn't fit in one entry, it is put into more than one row. The sequence field identifies the sub-rows.

Column	Datatype	Description
type	smallint	Object type:  1 Entry describes a plan (reserved) 2 Entry describes a tree
id	int	Object ID.
sequence	smallint	Sequence number if more than one row is used to describe this object.
status	smallint	Internal system status.
number	smallint	Subprocedure number when the procedure is grouped (0 for nonprocedure entries).
Index

sysprocedures clustered, unique on id, number, type, sequence

Referenced by Stored Procedures

sp_sproc_columns	sp_stored_procedures


sysprotects (all databases)

For more updated SQL Server 6.5 syntax, see sysprotects System Table.

Contains user permissions information — entries for each GRANT and REVOKE statement that has been executed.

Column	Datatype	Description
id	int	ID of object to which this permission applies.
uid	smallint	ID of user or group to which this permission applies.
action	tinyint	One of the following 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 DUMP DATABASE 233 CREATE DEFAULT 235 DUMP TRANSACTION 236 CREATE RULE
protecttype	tinyint	Either 205 (grant) or 206 (revoke).
columns	varbinary(32)	Bitmap of columns to which this SELECT or UPDATE permission applies. Bit 0 indicates all columns; bit 1 means permission applies to that column; NULL means no information.
Index

sysprotects clustered on id, uid, action

Referenced by Stored Procedures

sp_column_privileges	sp_helprotect	sp_table_privileges
sp_dropgroup	sp_stored_procedures	sp_tables
sp_dropuser


syspublications (new - all databases)
syspublications (all databases)

Contains a row for each of the publications posted by the publishing server.

Column	Datatype	Description
description	varchar(255)	Descriptive entry for the publication.
name	varchar(30)	Unique name associated with the publication.
pubid	int	An identity column providing a unique ID number for the publication.
repl_freq	tinyint	0 indicates transaction based; 1 indicates scheduled table refresh.
restricted	bit	Sets the security option for the publication. 1 indicates restricted; 0 indicates unrestricted. 0 is the default.
status	tinyint	0 indicates log-based; 1 indicates not log-based; default is log-based, 0 is the default.
sync_method	tinyint	0 indicates native bcp; 1 indicates char bcp.
taskid	int	Scheduled task ID.
Index

unc1syspublications nonclustered, unique on pubid

unc2syspublications nonclustered, unique on name

Referenced by Stored Procedures

sp_addarticle	sp_changesubstatus	sp_helparticle
sp_addpublication	sp_dboption	sp_helparticlecolumns
sp_addsubscription	sp_droparticle	sp_helppublication
sp_articlecolumn	sp_droppublication	sp_helpsubscription
sp_changearticle	sp_dropsubscription	sp_subscribe
sp_changepublication	sp_enumfullsubscribers	sp_unsubscribe
sp_changesubscription


sysreferences (new - all databases)
sysreferences (all databases)

Contains mappings of FOREIGN KEY constraint definitions.

Column	Datatype	Description
constid	int	Constraint ID
fkeyid	int	ID of referencing table
fkeydbid	smallint	Reserved
rkeyid	int	ID of referenced table
rkeydbid	smallint	Reserved
rkeyindid	smallint	Reserved
keycnt	smallint	Number of columns in key
fkey1	tinyint	Column ID of referencing column
fkey2	tinyint	Column ID of referencing column
fkey3	tinyint	Column ID of referencing column
fkey4	tinyint	Column ID of referencing column
fkey5	tinyint	Column ID of referencing column
fkey6	tinyint	Column ID of referencing column
fkey7	tinyint	Column ID of referencing column
fkey8	tinyint	Column ID of referencing column
fkey9	tinyint	Column ID of referencing column
fkey10	tinyint	Column ID of referencing column
fkey11	tinyint	Column ID of referencing column
fkey12	tinyint	Column ID of referencing column
fkey13	tinyint	Column ID of referencing column
fkey14	tinyint	Column ID of referencing column
fkey15	tinyint	Column ID of referencing column
fkey16	tinyint	Column ID of referencing column
rkey1	tinyint	Column ID of referenced column
rkey2	tinyint	Column ID of referenced column
rkey3	tinyint	Column ID of referenced column
rkey4	tinyint	Column ID of referenced column
rkey5	tinyint	Column ID of referenced column
rkey6	tinyint	Column ID of referenced column
rkey7	tinyint	Column ID of referenced column
rkey8	tinyint	Column ID of referenced column
rkey9	tinyint	Column ID of referenced column
rkey10	tinyint	Column ID of referenced column
rkey11	tinyint	Column ID of referenced column
rkey12	tinyint	Column ID of referenced column
rkey13	tinyint	Column ID of referenced column
rkey14	tinyint	Column ID of referenced column
rkey15	tinyint	Column ID of referenced column
rkey16	tinyint	Column ID of referenced column
Index

ucsysreferences clustered unique on constid

nc1sysreferences nonclustered fkeyid

nc2sysreferences nonclustered rkeyid

Referenced by Stored Procedures

sp_fkeys	sp_helpconstraint


syssegments (all databases)

Contains one row for each segment (named collection of disk fragments). When SQL Server is installed, this table contains three entries: segment 0 (system) for system tables, segment 1 (default) for other objects, and 2 (log segment) for the transaction log (the syslogs table). All entries in sysusages contain both of these segments and their maps.

Column	Datatype	Description
segment	smallint	Segment number
name	varchar(30)	Segment name, used internally
status	smallint	Default segment
Index

This table does not have any indexes.

Referenced by Stored Procedures

sp_addsegment	sp_helpdb	sp_helpsegment
sp_dropsegment	sp_helpindex	sp_placeobject
sp_extendsegment


syssubscriptions (new - all databases)
syssubscriptions (all databases)

Associates the IDs of published articles with the IDs of all subscription servers expecting to receive the data.

Column	Datatype	Description
artid	int	Unique ID of an article
srvid	smallint	Server ID of the subscription server
dest_db	varchar(30)	Name of the destination database
status	tinyint	Status: 0 Inactive 1 Subscribed 2 Active
sync_type	tinyint	Type 8 synchronization: 0 Manual  1 Automatic 2 None
timestamp	timestamp	Initial time of subscription
Index

unc1syssubscriptions nonclustered, unique on artid, srvid

Referenced by Stored Procedures

sp_addsubscription	sp_droppublication	sp_helppublication
sp_changesubscription	sp_dropsubscription	sp_helpsubscription
sp_changesubstatus	sp_enumfullsubscribers	sp_subscribe
sp_droparticle	sp_helparticle	sp_unsubscribe


systypes (all databases)

Contains one row for each system-supplied and each user-defined datatype. Domains (defined by rules) and defaults are given if they exist. The rows that describe system-supplied datatypes cannot be altered. The system-supplied datatypes and their ID numbers (the contents of the name and type fields, respectively) are as follows:

Column	Datatype	Description
uid	smallint	User ID of datatype creator.
usertype	smallint	User type ID.
variable	bit	Variable-length datatype is 1, otherwise, 0.
allownulls	bit	Indicates the default nullability for this datatype. If nullability is specified with the CREATE or ALTER TABLE statement then that value will override the default nullability for this datatype.
type	tinyint	Physical storage datatype.
length	tinyint	Physical length of datatype.
tdefault	int	ID of stored procedure that generates default for this datatype.
domain	int	ID of stored procedure that contains integrity checks for this datatype.
name	varchar(30)	Datatype name.
printfmt	varchar(255)	Reserved.
prec	tinyint	Level of precision for this datatype.
scale	tinyint	Scale for this datatype. Scale is based on precision.
Index

systypes clustered, unique on name

ncsystypes nonclustered, unique on usertype

Referenced by Stored Procedures

sp_addtype	sp_droptype	sp_special_columns
sp_bindefault	sp_dropuser	sp_sproc_columns
sp_bindrule	sp_help	sp_unbindefault
sp_columns	sp_rename	sp_unbindrule
sp_datatype_info


sysusers (all databases)

Contains one row for each user allowed to use the database and one row for each group.

When SQL Server is initially installed, master..sysusers contains three entries: dbo, with an suid of 1 and a uid of 1; guest, with a suid of −1 and uid of 2; and public, with an suid of −2 and a uid of 0. The sysusers table in the model database (and thus in all user databases) initially contains two entries: dbo and public.

The guest user provides access to the database to users not explicitly listed in sysusers, with a restricted set of permissions. The guest entry in master means that any user with an account on SQL Server (that is, with an entry in syslogins) can access master.

The public user refers to all users. The keyword PUBLIC is used with the GRANT and REVOKE statements to signify that permission is granted to or taken away from all users.

Column	Datatype	Description
suid	smallint	Server user ID, copied from syslogins. A suid of 1 is the system administrator, −1 is a guest account.
uid	smallint	User ID, unique in this database. A uid 1 is the database owner.
gid	smallint	Group ID to which this user belongs. If uid = gid, this entry defines a group. The public group has a suid equal to −2. All other groups have a suid equal to −gid.
name	varchar(30)	Username or group name, unique in this database.
environ	varchar(255)	Reserved.
Index

sysusers clustered, unique on suid

ncsysusers1 nonclustered, unique on name

ncsysusers2 nonclustered, unique on uid

Referenced by Stored Procedures

sp_addalias	sp_depends	sp_helpgroup
sp_addgroup	sp_dropgroup	sp_helprotect
sp_adduser	sp_droplogin	sp_helpuser
sp_changedbowner	sp_droptype	sp_stored_procedures
sp_changegroup	sp_dropuser	sp_table_privileges
sp_column_privileges	sp_helparticle	sp_tables
sp_dboption


System Tables-System Catalog

These system tables are found only within the master database:

Table	Description
syscharsets	Contains one row for each character set and sort order defined for use by SQL Server.
sysconfigures	Contains one row for each user-settable configuration option.
syscurconfigs	Contains an entry for each of the configuration options, as in sysconfigures, but contains the current values and four entries that describe the configuration structure.
sysdatabases	Contains one row for each database on SQL Server.
sysdevices	Contains one row for each disk dump device, diskette dump device, tape dump device, and database device.
syslanguages	Contains one row for each language known to SQL Server. Although U.S. English is omitted, it is always available to SQL Server.
syslocks	Contains information about active locks.
syslogins	Contains one row for each valid SQL Server user account.
sysmessages	Contains one row for each system error or warning that can be returned by SQL Server.
sysprocesses	Contains information about SQL Server processes.
sysremotelogins	Contains one row for each remote user who is allowed to call remote stored procedures on this SQL Server.
sysservers	Contains one row for each remote SQL Server on which this SQL Server can call remote stored procedures.
sysusages	Contains one row for each disk-allocation piece assigned to a database.


syscharsets (master database only)

Contains one row for each character set and sort order defined for use by 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	Datatype	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 that sort orders and character sets cannot share the same ID number. ID numbers 0 through 200 are reserved.
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 sort order is built on. It is assumed that a character set row with this ID exists in this table.
status	smallint	Internal system status information bits.
name	varchar(30)	Unique name for the character set or sort order. This field must contain only the letters A−Z or a−z, digits 0 − 9, and underscores(_). It must begin with a letter.
description	varchar(255)	Optional description of the features of the character set or sort order.
definition	image	Internal definition of the character set or sort order. The structure of the data in this field depends on the type.
Index

csyscharsets clustered, unique on id

ncsyscharsets nonclustered, unique located on name

Referenced by Stored Procedures

sp_helpsort


sysconfigures (master database only)

Contains one row for each configuration option that can be set by a user. The sysconfigures table contains the configuration options that were defined before the latest SQL Server startup, plus any dynamic configuration options that were set since the latest SQL Server startup.

Column	Datatype	Description
config	smallint	Configuration variable number
value	int	User-modifiable value for the variable (being used by SQL Server only if RECONFIGURE has been executed)
comment	varchar(255)	Explanation of the configuration option
status	smallint	Bitmap indicating the status for the option: 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.)
Index

sysconfigures clustered, unique on config

Referenced by Stored Procedures

sp_configure


syscurconfigs (master database only)

This table contains an entry for each of the configuration options, as does sysconfigures, but syscurconfigs contains the current values. In addition, it contains four entries that describe the configuration structure. The syscurconfigs table is built dynamically when queried by a user. For details, see the sysconfigures topic.

Referenced by Stored Procedures

sp_configure	sp_helpsort


sysdatabases (master database only)

Contains one row for each database on SQL Server. When SQL Server is initially installed, sysdatabases contains entries for the master database, the model database, and the tempdb database. The status column values are additive when more than one option is set or database condition applies.

Column	Datatype	Description
name	varchar(30)	Name of the database.
dbid	smallint	Database ID.
suid	smallint	Server user ID of database creator.
mode	smallint	Used internally for locking a database while it is being created.
status	smallint	Status bits, some of which can be set by the user with the sp_dboption system stored procedure  (READ ONLY, DBO USE ONLY, SINGLE USER, and so on): 2 Database is in transition 4 select into/bulkcopy; set with  sp_dboption 8 trunc. log on chkpt; set with  sp_dboption 16 no chkpt on recovery; set with  sp_dboption 32 Crashed while the database was  being loaded; instructs recovery not to  proceed 64 Database not recovered yet 128 Database is in recovery 256 Database is suspect; cannot be opened  or used in its present state 1024 read only; set with sp_dboption 2048 dbo use only; set with sp_dboption 4096 single user; set with sp_dboption 8192 Database being checkpointed 16384 ANSI null default; set with sp_dboption 32768 Emergency mode
version	smallint	Internal version number of the SQL Server code with which the database was created.
logptr	int	Pointer to the transaction log.
crdate	datetime	Creation date.
dumptrdate	datetime	Date of the last DUMP TRANSACTION.
category	int	Used for publication and subscription databases.
Index

sysdatabases clustered, unique on name

ncsysdatabases nonclustered, unique on dbid

Referenced by Stored Procedures

sp_addlogin	sp_dboption	sp_helpdb
sp_addpublication	sp_defaultdb	sp_logdevice
sp_changearticle	sp_devoption	sp_renamedb
sp_changedbowner	sp_dropdevice	sp_spaceused
sp_changepublication	sp_droplogin	sp_tables
sp_databases


sysdevices (master database only)

Contains one row for each disk dump device, diskette dump device, tape dump device, and database device. When SQL Server is installed initially, sysdevices has four entries: one for the MASTER database device (for databases), one for a disk dump device, and two for diskette dump devices.

Column	Datatype	Description
low	int	First virtual page number on a database device (not used for dump devices).
high	int	Last virtual page number on a database device (not used for dump devices).
status	smallint	Bitmap indicating the type of device:  1 Default disk  2 Physical disk  4 Logical disk  8 Skip header  16 Dump device  32 Serial writes  64 Device mirrored  128 Reads mirrored (reserved)  256 Half-mirror only (reserved)  512 Mirror enabled 4096 Read Only 8192 Deferred
cntrltype	smallint	Controller type: 0 Non CD-ROM database device 2 Disk dump device 3 − 4 Diskette dump device 5 Tape dump device 6 Named pipe device
name	varchar(30)	Logical name of the dump device or database device.
phyname	varchar(127)	Name of the physical device.
mirrorname	varchar(127)	Name of the mirror device.
stripeset	varchar(30)	Reserved for future use.
Index

sysdevices clustered, unique on name

Referenced by Stored Procedures

sp_addsegment	sp_devoption	sp_helpdb
sp_addumpdevice	sp_diskdefault	sp_helpdevice
sp_configure	sp_dropdevice	sp_helplog
sp_dbinstall	sp_dropsegment	sp_helpsegment
sp_dbremove	sp_extendsegment	sp_logdevice


syslanguages (master database only)

Contains one row for each language known to SQL Server. Although U.S. English is not in syslanguages, it is always available to SQL Server.

Column	Datatype	Description
langid	smallint	Unique language ID
dateformat	char(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	SQL Server version of last upgrade for this language
name	varchar(30)	Official language name (for example, français)
alias	varchar(30)	Alternate language name (for example, french)
months	varchar(251)	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(119)	Comma-separated list of short-month names, in order from January through December, with each name containing as many as 9 characters
days	varchar(216)	Comma-separated list of day names, in order from Monday through Sunday, with each name containing as many as 30 characters
Index

csyslanguages clustered, unique on langid

nc1syslanguages nonclustered, unique on name

nc2syslanguages nonclustered, unique on alias

Referenced by Stored Procedures

sp_configure	sp_helplanguage	sp_setlangalias
sp_droplanguage


syslocks (master database only)

Contains information about active locks. The syslocks system table is not a standard table. Rather, it is built dynamically when queried by a user. Updates to syslocks are not allowed. The type values are additive when more than one lock is in effect.

Column	Datatype	Description
id	int	Table ID
dbid	smallint	Database ID
page	int	Page number
type	smallint	Type of lock:  1 Exclusive table lock 2 Shared table lock 3 Exclusive intent lock (will do page locking on  indicated pages) 4 Shared intent lock 5 Exclusive page lock 6 Shared page lock 7 Update page lock (changes to exclusive lock if  page is actually modified) 8 Exclusive extent lock 9 Update extent lock 11 Next extent lock 12 Previous extent lock Any of the above lock types can appear with 256 (0x100) added to them, indicating that the lock is blocking another user. 257 Blocking exclusive table lock 265 Blocking update extent lock
spid	smallint	ID of process that holds the lock
Index

This table does not have any indexes.

Referenced by Stored Procedures

sp_lock


syslogins (master database only)

Contains one row for each valid SQL Server user account. When SQL Server is installed initially, syslogins contains one entry, in which the name is sa, the suid is 1, and the password is NULL. It also contains an entry named probe with a NULL password. The login probe and the user probe exist for the two-phase commit process.

Column	Datatype	Description
suid	smallint	Server user ID
status	smallint	Reserved
accdate	datetime	Reserved
totcpu	int	Reserved
totio	int	Reserved
spacelimit	int	Reserved
timelimit	int	Reserved
resultlimit	int	Reserved
dbname	varchar(30)	Name of user's default database when connection is established
name	varchar(30)	Login ID of user
password	varchar(30)	Encrypted password of user (may be NULL)
language	varchar(30)	User's default language (NULL for us_english)
Index

syslogins clustered, unique on suid

ncsyslogins nonclustered, unique on name

Referenced by Stored Procedures

sp_addalias	sp_changedbowner	sp_helpdb
sp_addlogin	sp_defaultdb	sp_helpuser
sp_addremotelogin	sp_defaultlanguage	sp_password
sp_adduser	sp_droplogin


sysmessages (master database only)

Contains one row for each system error or warning that can be returned by SQL Server. SQL Server displays the error description on the user's screen.

Column	Datatype	Description
error	int	Unique error number
severity	smallint	Severity level of the error
dlevel	smallint	Reserved. For internal use only.
description	varchar(255)	Explanation of the error with placeholders for parameters
langid	smallint	Language
Index

sysmessages clustered on error, dlevel

ncsysmessages nonclustered, unique on error, dlevel, langid

Referenced by Stored Procedures

sp_addmessage	sp_droplanguage	sp_dropmessage


sysprocesses (master database only)

For more updated SQL Server 6.5 syntax, see sysprocesses System Table.

Contains information about SQL Server processes. The sysprocesses system table is not a standard table. Rather, it is built dynamically when queried by a user. Updates to sysprocesses are not allowed. Use the KILL statement to cancel a process.

Column	Datatype	Description
spid	smallint	Process ID
kpid	smallint	Windows NT thread ID
status	char(10)	Process ID status (for example, runnable, sleeping, and so on)
suid	smallint	Server user ID of user who executed command
hostname	char(10)	Name of workstation
program_name	char(16)	Name of application program
hostprocess	char(8)	Workstation process ID number
cmd	char(16)	Command currently being executed
cpu	int	Cumulative CPU time for process
physical_io	int	Cumulative disk reads and writes for process
memusage	int	Number of 2K pages of the procedure cache that are currently allocated to the process
blocked	smallint	Process ID of blocking process, if any
waittype	binary	Reserved
dbid	smallint	Database ID
uid	smallint	ID of user who executed command
gid	smallint	Group ID of user who executed command
Index

This table does not have any indexes.

Referenced by Stored Procedures

sp_dboption	sp_who


sysremotelogins (master database only)

Contains one row for each remote user who is allowed to call remote stored procedures on this SQL Server.

Column	Datatype	Description
remoteserverid	smallint	Remote server identification
remoteusername	varchar(30)	User's login name on a remote server
suid	smallint	Local server user ID
status	smallint	Bitmap of options
Index

csysremotelogins clustered, unique on remoteserverid, remoteusername

Referenced by Stored Procedures

sp_addremotelogin	sp_dropremotelogin	sp_dropsubscriber
sp_addsubscriber	sp_dropserver	sp_remoteoption


sysservers (master database only)

Contains one row for each remote SQL Server on which this SQL Server can call remote stored procedures.

Column	Datatype	Description
srvid	smallint	ID number (for local use only) of the remote server
srvstatus	smallint	Bitmap of options
srvname	varchar(30)	Name of the server
srvnetname	varchar(32)	Reserved (currently the same as srvname)
topologyx	int	Used by the SQL Enterprise Manager server topology diagram
topologyy	int	Used by the SQL Enterprise Manager server topology diagram
Index

csysservers clustered, unique on srvid

ncsysservers nonclustered, unique on srvname

Referenced by Stored Procedures

sp_addpublisher	sp_dropremotelogin	sp_helpremotelogin
sp_addremotelogin	sp_dropserver	sp_helpserver
sp_addserver	sp_dropsubscriber	sp_helpsubscriberinfo
sp_addsubscriber	sp_dropsubscription	sp_helpsubscription
sp_addsubscription	sp_enumfullsubscribers	sp_remoteoption
sp_changesubscriber	sp_helparticle	sp_serveroption
sp_changesubscription	sp_helpdistributor	sp_subscribe
sp_changesubstatus	sp_helppublication	sp_unsubscribe
sp_droppublisher


sysusages (master database only)

Contains one row for each disk-allocation piece assigned to a database. Each database contains a specified number of database (logical) page numbers. Each disk piece includes segments 0 and 1.

When the CREATE DATABASE statement is executed, SQL Server scans the disk(s) to find available disk-allocation pieces. One or more contiguous disk-allocation pieces are assigned to the database, and the mapping is recorded in sysusages.

Column	Datatype	Description
dbid	smallint	Database ID
segmap	int	Bitmap of possible segment assignments
lstart	int	First database (logical) page number
size	int	Number of contiguous database (logical) pages
vstart	int	Starting virtual page number
Index

sysusages clustered, unique on dbid, lstart

ncsysusages nonclustered, unique on vstart

Referenced by Stored Procedures

sp_addsegment	sp_dropsegment	sp_helpsegment
sp_databases	sp_extendsegment	sp_logdevice
sp_dbinstall	sp_helpdb	sp_remove
sp_devoption	sp_helplog	sp_spaceused
sp_dropdevice


System Tables-Replication Tables

Publication databases use the following tables (part of the database catalog) for replication purposes:

Table	Description
sysarticles	Has a row for each of the articles posted by the publication server.
sysobjects	Has a category field set by replication for each object marked for replication. This is set when an article is created and when an article is initially subscribed to.
syspublications	Has a row for each of the publications posted by the publication server.
syssubscriptions	Associates the IDs of published articles with the IDs of all subscription servers expecting to receive the data.
Destination databases maintain replication information in the MSlast_job_info table:

Table	Description
MSlast_job_info_	Contains the job ID of the last job (from a batch) that was successfully applied. (A job is a complete transaction from the transaction log of the publication database.) Also, if present, contains information about an article that has paused distribution while waiting for manual synchronization.
Distribution databases contain the following tables dedicated to replication:

Table	Description
MSjob_commands	Contains one entry for each command associated with a transaction in the MSjobs table. One transaction can contain many commands.
MSjob_subscriptions	Associates a subscriber with a particular article. (This is actually subscriber-side information that is maintained in the distribution database.)
MSjobs	Contains the actual transactions. There is one entry for every transaction stored in the distribution database.
MSsubscriber_info	Contains information used by SQL Executive for passing jobs.
MSsubscriber_jobs	Associates each subscriber with the command that subscriber needs to receive.
MSsubscriber_status	Contains status information for the individual batches of transactions sent to subscribers.
All servers participating in replication keep some replication-related data in the system catalog found in the master database:

Table	Description
sysservers	Used by both the publication and subscription servers. The srvstatus column has status bits set for RPC, PUBLISH, SUBSCRIBE, and DISTRIBUTE.  A publication server uses all four options to register the subscribing servers that can receive its publications. A subscription server uses only the RPC option to register the publication servers that it authorizes to send it publications.  The options can be reviewed by running sp_helpserver and viewing the status column.
sysdatabases	Used by the publication server. When set up for replication, the category column defines whether a database is permitted to publish.
For more information about the tables used by replication, see the specific table, listed separately.


MSjob_commands (new - distribution database only)
MSjob_commands (distribution database only)

Distribution database table. Contains one entry for each command associated with a transaction in the MSjobs table. One transaction can contain many commands.

Column	Datatype	Description
publisher_id	smallint	The local server ID of the publishing server.
publisher_db	varchar(30)	The name of the published database.
job_id	int	The job ID.
command_id	int	The command ID.
art_id	int	The article ID.
incomplete	bit	Indicates whether this is the full command, or if the command is broken into separate entries.
command	varchar(255)	The actual command or command fragment.
Index

ucMSjob_commands clustered, unique on publisher_db, publisher_id, job_id, command_id

Referenced by Stored Procedures

sp_replcleanup


MSjob_subscriptions (new - distribution database only)
MSjob_subscriptions (distribution database only)

Distribution database table. Associates a subscriber with a particular article. (This is actually subscriber-side information maintained in the distribution database.)

Column	Datatype	Description
publisher	varchar(30)	The name of the publishing server.
publisher_id	smallint	The local server ID of the publishing server.
publisher_db	varchar(30)	The name of the published database.
subscriber	varchar(30)	The name of the subscriber.
subscriber_id	smallint	The local server ID of the subscribing server.
art_id	int	The article ID.
subscriber_db	varchar(30)	The name of the database on the subscribing server.
status	tinyint	Status: 0 Inactive 1 Subscribed 2 Active
ts	binary(8)	The timestamp of the published subscription.
status	tinyint	Reserved.
Index

ucMSsubscriptions clustered, unique on publisher_db, publisher_id, art_id, subscriber_id


MSjobs (new - distribution database only)
MSjobs (distribution database only)

Distribution database table. Contains the actual transactions. There is one entry for every transaction that is stored in the distribution database.

Column	Datatype	Description
publisher_id	smallint	The local server ID of the publishing server.
publisher_db	varchar(30)	The name of the published database.
job_id	int	The job ID.
type	tinyint	The transaction type: 0 SQL command 1 Noop command 2 SQL script 3 Native bcp command 4 Character bcp command 5 Manual sync
xactid_page	int	If the event is log based, the page of the transaction.
xactid_row	smallint	If the event is log based, the row of the transaction.
xactid_ts	binary(8)	The timestamp of the transaction.
entry_time	datetime	The time the row was added to the table.
Index

ucMSjobs clustered, unique on publisher_db, publisher_id, job_id

Referenced by Stored Procedures

sp_replcleanup


MSlast_job_info (new - destination database only)
MSlast_job_info (destination database only)

Destination database table. Contains the job ID of the last job (from a batch) that was successfully applied. (A job is a complete transaction from the transaction log of the publishing database.) Also, if present, contains the name of a job that has paused distribution while waiting for manual synchronization.

Column	Datatype	Description
publisher	varchar(30)	The name of the publishing server associated with the job ID.
publisher_db	varchar(30)	The name of the published database.
job_id	int	The job ID of the last job (from a batch) that was successfully applied.
publication	varchar(30)	The source publication.
article	varchar(30)	The source article.
description	varchar(100)	A description provided by the distribution process.
Index

This table does not have any indexes.

Referenced by Stored Procedures

sp_replsync


MSsubscriber_info (new - distribution database only)
MSsubscriber_info (distribution database only)

For more updated SQL Server 6.5 syntax, see MSsubscriber_info Table.

Distribution database table. Contains information used by SQL Executive for passing jobs.

Column	Datatype	Description
publisher	varchar(30)	The name of the publisher.
subscriber	varchar(30)	The name of the subscriber.
type	tinyint	The subscriber type. 0 indicates SQL Server 6.0 subscriber. 1 indicates an ODBC data source.
login	varchar(30)	Allows NULL.
password	varchar(30)	Allows NULL.
commit_batch_size	int	The number of transactions executed on the subscriber before a commit is issued.
status_batch_size	int	The number of transactions before the status state is updated.
flush_frequency	int	The minimum time, in hours, that transactions will be retained within the distribution database after they have been distributed.
frequency_type	int	The primary frequency of this task. One time, On demand, Daily, and so on.
frequency_interval	int	The interval of frequency_type.
frequency_relative_interval	int	The relative interval for day of the month when the freqtype is monthly (32).
frequency_recurrence_factor	int	The recurrence factor based on the frequency_type.
frequency_subday	int	The reschedule occurrence based on frequency_interval. Once, every second, every minute, every hour.
frequency_subday_interval	int	The amount of time per frequency_subday when it is a unit of time.
active_start_time_of_day	int	The time of day when this task is active.
active_end_time_of_day	int	The time of day this task is no longer active.
active_start_date	int	The date and time after which this task may be scheduled.
active_end_date	int	The date and time after which this task may no longer be scheduled.
retryattempts	int	The number of retry attempts when a task execution fails.
retrydelay	int	The delay, in minutes, between retry attempts.
Index

ucMSsubscriber_info clustered, unique on publisher, subscriber


MSsubscriber_jobs (new - distribution database only)
MSsubscriber_jobs (distribution database only)

Distribution database table. Associates each subscriber with the command that subscriber needs to receive.

Column	Datatype	Description
job_id	int	The job ID.
publisher_id	smallint	The local server ID of the publishing server.
publisher_db	varchar(30)	The name of the published database.
subscriber_id	smallint	The subscriber ID.
subscriber_db	varchar(30)	The name of the database on the subscribing server.
command_id	int	The ID of the command.
Index

ucMSsubscriber_jobs clustered, unique on publisher_db, publisher_id, subscriber_db, subscriber_id, job_id, command_id

Referenced by Stored Procedures

sp_replcleanup	sp_MSkill_job


MSsubscriber_status (new - distribution database only)
MSsubscriber_status (distribution database only)

Distribution database table. Contains status information for the individual batches of transactions sent to subscribers.

Column	Datatype	Description
publisher_id	smallint	The local server ID of the publishing server.
publisher_db	varchar(30)	The name of the published database.
job_id	int	The job ID.
subscriber_db	varchar(30)	The name of the database on the subscribing server.
subscriber_id	smallint	The local server ID of the subscribing server.
completion_time	datetime	The time the row was inserted.
status	int	The completion status.
delivery_latency	int	In seconds, the time between a job being inserted in the distribution database and being executed against the subscriber.
delivered_jobs	int	The number of jobs still in the distribution database that have already been executed against the destination database.
delivery_rate	int	The number of jobs per second that were executed in the last batch sent to that subscription server.
Index

ucMSsubscriber_status clustered, unique on publisher_db, publisher_id, subscriber_db, subscriber_id, job_id

Referenced by Stored Procedures

sp_MSsubscriber_status	sp_replcleanup


System Tables-SQL Executive Tables

SQL Executive handles event scheduling and alert management for any SQL Server process, such as replication. All scheduling information is stored within the msdb database.

The msdb database uses the following tables for scheduling purposes:

Table	Description
sysalerts	Contains one row for each alert.
syshistory	Contains one row for each task that has occurred.
sysnotifications	Contains one row for each notification.
sysoperators	Contains one row for each operator.
systasks	Contains one row for every scheduled task.


sysalerts

Contains one row for each alert. An alert is a message sent in response to some event that has occurred; an alert can "forward" messages outside of the SQL Server environment. An alert can be EMAIL and/or PAGER, and it can also generate a task.

Column	Datatype	Description
id	int	The alert ID.
name	varchar(60)	The alert name.
event_source	varchar(30)	The source of the event:  SQL Server.
event_categoryname	varchar(30)	Reserved for future use.
event_id	varchar(20)	The ID of the event (from the event log) that triggers this alert.
message_id	int	User-defined message ID or reference to sysmessages message that triggers this alert.
severity	int	The severity that triggers this alert.
enabled	tinyint	The status of the alert: 0  Disabled 1  Enabled
delay_between_notifications	int	The wait period, in seconds, between notifications for this alert.
last_occurrence_date	int	The last occurrence (date) of the alert.
last_occurrence_time	int	The last occurrence (time of day) of the alert.
last_response_date	int	The last notification (date) of the alert.
last_response_time	int	The last notification (time of day) of the alert.
notification_message	varchar(255)	Additional information sent with the alert.
include_event_description	tinyint	Bitmask representing whether the event description is sent by either or both: 1  EMAIL 2  PAGER
database_name	varchar(30)	The database in which this alert must occur to trigger this alert.
event_description_keyword	varchar(100)	The pattern the error must match in order for the alert to trigger.
occurrence_count	int	The number of occurrences for this alert.
count_reset_date	int	The day (date) that this count will be reset to 0.
count_reset_time	int	The time of day that this count will be reset to 0.
task_id	int	The ID of the task that is executed when this alert occurs.
has_email_notification	int	The number of operators who receive e-mail notification when this alert occurs.
has_pager_notification	int	The number of operators who receive pager notification when this alert occurs.
Index

ByName clustered, unique on name
ByID nonclustered, unique on id

Referenced by Stored Procedures

sp_addalert	sp_dropnotification	sp_updatealert
sp_addnotification	sp_helpnotification	sp_updatenotification
sp_dropalert


syshistory

Contains one row for each scheduled event, alert, or task that has occurred.

Column	Datatype	Description
id	int	The ID of the history entry.
eventid	int	Reserved for future use.
messageid	int	The ID of the message sent.
severity	int	The severity of the message sent.
taskid	int	The ID of the task executed.
source	varchar(30)	The source of the event.
category	varchar(30)	The category of event.
runstatus	int	The completion type: Success, Failure, Aborted, or Skipped.
rundate	int	The date the event was completed.
runtime	int	The time of day the event was completed.
runduration	int	The amount of time needed to complete the task.
reviewstatus	varchar(32)	Reserved for future use.
emailoperatorid	int	The ID of the operator to whom e-mail was sent.
retries	int	The number of retry attempts for a task.
comments	varchar(255)	The description of the outcome of the task, if any. This is usually error information.
timesskipped	int	The number of times the task was skipped because of a server or SQL Executive problem.
Index

ucsyshistory clustered, unique on id

Referenced by Stored Procedures

sp_droptask	sp_helphistory	sp_purgehistory


sysnotifications

Has a row for each notification.

Column	Datatype	Description
alert_id	int	The ID of the alert.
operator_id	int	The operator ID to whom this notification should be sent.
notification_method	tinyint	The method of notification (EMAIL, PAGER, BOTH).
Index

ByAlertIDAndOperator clustered, unique on alert_id, operator_id

Referenced by Stored Procedures

sp_addnotification	sp_dropnotification	sp_updatenotification
sp_dropalert	sp_dropoperator


sysoperators

Contains one row for each operator.

Column	Datatype	Description
id	int	The ID of the operator.
name	varchar(50)	The name of the operator.
enabled	tinyint	The status of alert notifications (Boolean). If 1, this operator can receive notifications when an alert occurs.
email_address	varchar(100)	The e-mail address for this operator.
last_email_date	int	The date this operator last received an e-mail alert notification.
last_email_time	int	The time of day this operator last received an e-mail alert notification.
pager_address	varchar(100)	The pager address for this operator.
last_pager_date	int	The date this operator last received a pager alert notification.
last_pager_time	int	The time of day this operator last received a pager alert notification.
weekday_pager_start_time	int	The 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	The 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	The time of day on Saturday after which this operator is available to receive a pager alert notification.
saturday_pager_end_time	int	The time of day on Saturday after which this operator is not available to receive a pager alert notification.
sunday_pager_start_time	int	The time of day on Sunday after which this operator is available to receive a pager alert notification.
sunday_pager_end_time	int	The time of day on Sunday after which this operator is not available to receive a pager alert notification.
pager_days	tinyint	Bitmask. The days of the week during which this operator is available to receive a pager alert notification.
Index

ByName clustered, unique on name
ByID nonclustered, unique on id

Referenced by Stored Procedures

sp_addnotification	sp_helphistory	sp_schedulerrefresh
sp_addoperator	sp_helpnotification	sp_updatenotification
sp_dropnotification	sp_helpoperator	sp_updateoperator
sp_dropoperator	sp_helptask	sp_verifytask


systasks

Contains one row for every scheduled task. Each task may be generated or executed in response to an alert. Tasks execute in the specified subsystem: replication (Distribution, LogReader, Sync), Transact-SQL (TSQL), or command-line executables (CmdExec).

Column	Datatype	Description
id	int	The ID of the task.
name	varchar(100)	The name of the task.
subsystem	varchar(30)	The subsystem used for a task: Distribution, LogReader, Sync, TSQL, or CmdExec.
server	varchar(30)	The server on which this task is executed.
username	varchar(30)	The username under which this task should be executed.
ownerloginid	smallint(2)	The login ID of the task creator.
databasename	varchar(30)	The database in which this task should be executed.
enabled	tinyint	The status of this task. (Boolean.)
freqtype	int	The primary frequency of this task. One time, On demand, Daily, and so on.
freqinterval	int	The interval of freqtype.
freqsubtype	int	The reschedule occurrence based on freqinterval. Once, every second, every minute, every hour.
freqsubinterval	int	The amount of time per freqsubtype when it's a unit of time.
freqrelativeinterval	int	The relative interval for day of month when the freqtype is monthly (32).
freqrecurrencefactor	int	The recurrence factor based on the freqtype.
activestartdate	int	The date and time after which this task may be scheduled.
activeenddate	int	The date and time after which this task may no longer be scheduled.
activestarttimeofday	int	The time of day when this task is active.
activeendtimeofday	int	The time of day this task is active.
lastrundate	int	The date this task was last executed.
lastruntime	int	The time of day this task was last executed.
nextrundate	int	The date this task is scheduled to be executed next.
nextruntime	int	The time of day this task is scheduled to be executed next.
runpriority	int	The Windows NT thread priority to use when executing this task.
emailoperatorid	int	The ID of the operator to whom e-mail is sent.
retryattempts	int	The number of retry attempts when a task execution fails.
retrydelay	int	The delay, in minutes, between retry attempts.
datecreated	datetime	The date and time this task was created.
datemodified	datetime	This date and time this task was last modified.
command	varchar(255)	Command to execute based on the subsystem.
lastruncompletionlevel	int	The task completion status of the last execution of this task.
lastrunduration	int	The duration of the last execution of this task.
lastrunretries	int	The number of retry attempts during the previous execution of this task.
loghistcompletionlevel	int	The task completion status which causes task history information to be logged.
emailcompletionlevel	int	The task completion status which causes notification of the operator by e-mail.
description	varchar(255)	Description of the task.
tagadditionalinfo	varchar(96)	Temporary storage space contained in this object. Used by replication.
tagobjectid	int	The ID of the object using temporary storage space. Used by replication.
tagobjecttype	int	The type of object using temporary storage space. Used by replication.
Index

ucsystasks clustered, unique on name
uncsystasks nonclustered, unique on id

Referenced by Stored Procedures

sp_addalert	sp_helphistory	sp_updatealert
sp_addtask	sp_helptask	sp_updatetask
sp_droptask	sp_purgehistory


Text and Image Manipulation

Text and image data consists of character or binary data stored and managed as a linked list of 2K data pages that appear as if they were stored in a table row. A text or image datatype contains a pointer (assigned at initialization) to the first data page or value fragment for that entry, and thus to the entire text or image value.

In SQL Server, this type of storage (variable number of 2K pages stored in a linked list) is fundamentally different from other datatypes. Because of this, text and image data is also manipulated differently. To assist in manipulating text and image data, SQL Server provides a variety of functions and statements. For more information on the text and image datatypes, see the Datatypes topic.

These are the text and image functions:

•	TEXTPTR

•	TEXTVALID

For details about these functions, see the Functions topic.

These are the text and image statements:

•	READTEXT

•	UPDATETEXT

•	WRITETEXT

The following functions and statement are also useful with text and image data:

•	PATINDEX

•	DATALENGTH

•	SET TEXTSIZE

For information about PATINDEX and DATALENGTH, see the Functions topic. For information about the TEXTSIZE session setting, see the SET statement.

The following sections detail each of the text and image manipulation statements.


READTEXT Statement

Reads text and image values, starting from a specified offset and reading a specified number of bytes.

Syntax

READTEXT [[database.]owner.]table_name.column_name
text_ptr offset size [HOLDLOCK]

where

[database.]owner.]table_name.column_name

Specifies a table and column. Both names must be included, but the database name and owner name are optional.

text_ptr

Is a valid text pointer.

offset

Specifies the number of bytes to skip before starting to read the text or image data.

size

Specifies the number of bytes of data to read. If size is 0, 4K 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

READTEXT is used with a text_ptr. The value of text_ptr can be obtained using the TEXTPTR function. The TEXTPTR function returns a pointer to the text or image column in the specified row or to the text or image column in the last row returned by the query if more than one row is returned. Since the TEXTPTR function 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.

The value in the global variable @@TEXTSIZE, which is the limit on the number of bytes of data to be returned, supersedes the size specified for READTEXT if it is less than the specified size for READTEXT. For details on how to set the session setting for TEXTSIZE, see the SET statement.

Permission

Users must have SELECT permission on the table to use READTEXT. READTEXT permission is transferred when SELECT permission is transferred.


UPDATETEXT
UPDATETEXT Statement

Updates an existing text or image field. WRITETEXT updates and replaces an entire text or image field. UPDATETEXT is more flexible because it changes only a portion of a text or image value in place.

Syntax

UPDATETEXT
[[database.]owner.]table_name.dest_column_name dest_text_ptr
{NULL | insert_offset} {NULL | delete_length} [WITH LOG]
[inserted_data |
[{[database.]owner.]table_name.src_column_name src_text_ptr}]

where

table_name.dest_column_name

Specifies the table and text or image column to be updated. The database name and owner name are optional.

dest_text_ptr

Is a text pointer value (returned by the TEXTPTR function) that points to the text or image data to be updated.

insert_offset

Is the zero-based starting position, specified as the number of bytes (from the start of the existing text or image value) to skip before inserting the new data. The existing text or image data beginning at this zero-based starting position will be shifted to the right to make room for the new data. A value of 0 means that the new data will be inserted at the beginning of the existing data value. A value of NULL means that the new data will be appended to the existing data value.

delete_length

Is the number of bytes to delete from the existing text or image value, starting at the insert_offset position. A value of 0 means that no data will be deleted. A value of NULL means that all data from the insert_offset position to the end of the existing text or image value will be deleted.

WITH LOG

Specifies that the inserted text or image data will be 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 details, see the sp_dboption system stored procedure.

inserted_data

Is the data to be inserted into the existing text or image value at the insert_offset location. This is a single char, varchar, binary, varbinary, text, or image constant.

table_name.src_column_name

Specifies the table and text or image column that can be used as the source of the inserted data.

src_text_ptr

Is a text pointer value (returned by the TEXTPTR function) that points to a text or image value that can be used as the source of the inserted data.

Remarks

The UPDATETEXT statement can be used to replace existing data, delete existing data, or insert new data. Newly inserted data can be a single inserted_data constant, or a table name, column name, or text pointer.

To delete existing data and then insert new data, specify a non-null insert_offset value, a non-zero delete_length value, and the new data to be inserted.

To delete only existing data, specify a non-null insert_offset value and a non-zero delete_length. Do not specify any new data to be inserted.

To insert new data, specify the desired insert_offset value, a delete_length of 0, and the new data to be inserted.


WRITETEXT Statement

Permits nonlogged, interactive updating of an existing text or image field. This statement completely overwrites any existing data in the column it affects. By default, WRITETEXT statements are not logged so that the transaction log won't fill up with the large amounts of data that often make up these datatypes.

Syntax

WRITETEXT [[database.]owner.]table_name.column_name text_ptr
[WITH LOG] data

where

table_name.column_name

Specifies the text column and table to be updated. The database name and owner name are optional.

text_ptr

Is a value that stores the pointer to the text or image data.

WITH LOG

Logs the inserted text or image data, which aids media recovery. Because text data quickly increases the size of the transaction log, be sure that the transaction log resides on a separate database device.

Remarks

The WRITETEXT statement completely overwrites any existing data in the column it affects. Use WRITETEXT to replace text data and UPDATETEXT to modify text data. UPDATETEXT is more flexible because it changes only a portion of a text of image value rather than the entire value.

By default, WRITETEXT is a nonlogged operation. This means that text or image data is not logged when it is written into the database. To use WRITETEXT in its default, nonlogged state, the system administrator must use the sp_dboption system stored procedure to set select into/bulkcopy, which allows nonlogged data to be inserted.

For WRITETEXT to work, the column must already contain a valid text pointer. There are two ways to create a text pointer:

•	Insert actual data into the text or image column

•	Update the column with data or a NULL

Because an initialized text column uses 2K of storage, even to store a couple of words, SQL Server saves space by not initializing text columns when explicit or implicit null values are placed in text columns with INSERT.

The maximum length of text that can be inserted interactively with WRITETEXT is approximately 120K for text and image data.

You cannot use WRITETEXT on text and image columns in views.

The DB-Library functions dbwritetext and dbmoretext and the ODBC function SQLPutData are faster and use less dynamic memory than WRITETEXT. These functions can insert up to 2 gigabytes of text data.

Caution  After using the WRITETEXT statement, you must execute DUMP DATABASE. After nonlogged operations occur within a database, the DUMP TRANSACTION statement cannot be performed. For details, see the DUMP statement.

Text and Image
Examples

A.	READTEXT Statement

This example selects the second through twenty-sixth characters of the pr_info column in the pub_info table.

DECLARE @@ptrval varbinary(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'

READTEXT pub_info.pr_info @@ptrval 1 25

B.	Use WRITETEXT to Change Text Data

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.

DECLARE @@ptrval varbinary(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 puglication this makes NMB the hottest new publisher of the year!'

Note that publication is spelled incorrectly (puglication) in this example. In example C, this value is corrected with UPDATETEXT.

C.	Use UPDATETEXT to Modify Text Data

This example puts the text pointer into the local variable @@ptrval, and then uses UPDATETEXT to update the spelling error in example B.

DECLARE @@ptrval varbinary(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

See Also

Datatypes	SELECT
DECLARE	SET
DELETE	UPDATE
INSERT


Trace Flags

For more information about how SQL Server 6.5 affects existing database systems and for updated SQL Server 6.5 syntax, see Trace Flags.

Trace Flags are used to temporarily set a specific server characteristic. Trace flags can be activated through two methods: by using the DBCC statement and with the -T option with the sqlservr command-line executable. When set, trace flags are in effect only until reset (for options set with the DBCC statement) or until the server is stopped and restarted. For details, see the Utilities topic and the DBCC statement. For details on troubleshooting and setting and using trace flags, see the Microsoft SQL Server Administrator's Companion.

The following table summarizes the trace flags available in SQL Server 6.0. These trace flags are provided primarily for backward compatibility. In general, trace flags should be used to temporarily work around a problem until a permanent solution is put in place. Trace flags are not a part of the supported feature set, and future compatibility or continued use is not assured.

These are the trace flags available in SQL Server 6.0:

Trace flag	Description
− 1	Sets trace flags for all client connections, rather than for a single client connection. Because trace flags set using the -T command-line option (with sqlservr) automatically apply to all connections, this trace flag is used only when setting trace flags using DBCC TRACEON and DBCC TRACEOFF. For details, see the sqlservr command-line executable and DBCC statement.
106	Disables line number information for syntax errors.
107	Interprets numbers with a decimal point as float instead of decimal. For details, see the Datatypes topic.
204	Generally, allows non−ANSI-standard behavior for various features: • Allows queries that contain aggregates or a GROUP BY clause to  have items in the select list that are not in the GROUP BY clause and  are not aggregate functions. ANSI-standard SQL does not allow this. • Ignores trailing blanks in the LIKE pattern. For details, see the Search Conditions and Wildcard Characters topics.
206	Provides backward compatibility for the SETUSER statement. For details, see the SETUSER statement.
243	Provides backward compatibility for nullability behavior. When set, SQL Server has the same nullability violation behavior as that of a 4.2 server: • Processing of the entire batch will be terminated if the nullability error  (inserting NULL into a NOT NULL field) can be detected at compile  time • Processing of the offending row will be skipped but the command will  continue if the nullability violation is detected at run time The behavior of SQL Server 6.0 is now more consistent — all nullability checks are made at run time and a nullability violation results in the command terminating but the batch/transaction continuing to process.
302	Prints information about whether the statistics page is used, the actual selectivity (if available), and what SQL Server estimated the physical and logical I/O would be for the indexes. Index selection information is also available in a more readable format using SET SHOWPLAN ON, as described with the SET statement. Trace flag 302 should be used with trace flag 310 to show the actual join ordering.
310	Prints information about join order.
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.
652	Disables read ahead for the server.
653	Disables read ahead for the current connection.
1200	Prints lock information (the process ID and type of lock requested).
1204	Returns the type of locks participating in the deadlock and the current command affected.
1205	Returns more detailed information on the command being executed at the time of a deadlock.
1609	Turns on the unpacking and checking of RPC information with the execution of the sp_sqlexec extended stored procedure in Open Data Services. Use this flag only when applications depend on the old behavior. The application should be changed to use EXECUTE sql_string rather than sp_sqlexec. For details, see the EXECUTE statement.
3502	Prints a message to the log at the start and end of each checkpoint.
3205	By default, if a tape drive supports hardware compression, the DUMP statement will use it. With this trace flag, you can disable hardware compression for tape drives. This might be useful when you want to exchange tapes with other sites or tape drives that do not support compression.
3503	Indicates whether the checkpoint at the end of automatic recovery was skipped for a database (this applies only to READ ONLY databases). For details, see the sp_dboption system stored procedure.
3604	Sends trace output to the client. ( ) This trace flag is 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 line, the output will also appear on the screen.)
3607	Skips automatic recovery for all databases.
3608	Skips automatic recovery for all databases except the master database.
3609	Skips the creation of the tempdb database. Use this trace flag if the device or devices on which tempdb resides are problematic or problems exist in the model database.
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 NOCOUNT, but when set as a trace flag every client session is handled this way. For details, see the SET statement.
4022	Skips the execution of all startup stored procedures. For more information, see the CREATE PROCEDURE statement and the sp_makestartup system stored procedure.
4030	Prints both a byte and ASCII representation of the receive buffer. This trace flag is usually used when you need to see what queries a client is sending to SQL Server. You might use this trace flag if you experience a protection violation and need to determine which statement caused it. Typically, you would set this flag globally or use SQL Enterprise Manager. You can also use DBCC INPUTBUFFER. For details, see the DBCC statement.
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. For details, see the DBCC statement.
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 need to see what queries a client is sending to SQL Server.
See also

Datatypes	SET
DBCC	sqlservr Command-line Executable


Transactions

A transaction is a single unit of work. Any single SQL statement is considered to be a single unit of work whether it affects only a single row or multiple rows within a table. In SQL Server, a transaction is implicit (due to the nature of the statements executed) or explicit (as defined by the user). An explicit transaction is a grouping of SQL statements surrounded by the transaction delimiters: BEGIN TRANSACTION, COMMIT TRANSACTION, and optionally, one of the following statements. In creating explicitly defined transactions, the following statements are used:

•	BEGIN TRANSACTION

•	COMMIT TRANSACTION

•	ROLLBACK TRANSACTION

•	SAVE TRANSACTION

All transactions must be enclosed within BEGIN TRANSACTION...COMMIT TRANSACTION statements. The outermost pair actually creates and commits the transaction; the inner pairs track the nesting level. When a nested transaction is encountered, the global variable @@TRANCOUNT is incremented.

Naming nested transactions with a transaction_name has little effect on the outermost transaction. Only the first (outermost) transaction name is registered with the system, and a rollback to any other name (other than a valid savepoint name) generates an error. None of the statements executed before the rollback are rolled back when this error occurs. No portion of the transaction is committed until the outermost COMMIT TRANSACTION is issued. Normally, this apparent transaction nesting occurs as stored procedures or triggers with BEGIN...COMMIT pairs call each other.

Although transactions can be nested, they have little effect on the behavior of ROLLBACK TRANSACTION statements, except for generating errors if not handled properly. The syntax allows stored procedures and triggers to be called from within transactions if they contain BEGIN TRANSACTION and COMMIT TRANSACTION statements.

Grouping a large number of Transact-SQL statements into one long-running transaction can negatively affect recovery time and cause concurrency problems. If SQL Server fails during such a transaction, recovery time can increase because SQL Server must first undo the transaction. Wherever possible, it is wise to break transactions into smaller transactions. Make sure each transaction is well-defined within a single batch. To minimize possible concurrency conflicts, transactions should not span multiple batches nor wait for user input.

In stored procedures and triggers, the number of BEGIN TRANSACTION statements must match the number of COMMIT TRANSACTION statements. A procedure or trigger that contains unpaired BEGIN TRANSACTION and COMMIT TRANSACTION statements produces an error message when it is executed.

Transaction Rules

To define a transaction, place Transact-SQL statements and/or stored procedures between the statements BEGIN TRANSACTION and COMMIT TRANSACTION. Within a user-defined (or explicit) transaction, there are some important rules to follow:

•	Do not use the following statements inside a user-defined transaction:

ALTER DATABASE	DISK INIT	LOAD TRANSACTION
CREATE DATABASE	DROP <objname>	RECONFIGURE
CREATE INDEX	DUMP TRANSACTION	SELECT INTO
CREATE PROCEDURE	GRANT or REVOKE	TRUNCATE TABLE
CREATE TABLE	LOAD DATABASE	UPDATE STATISTICS
CREATE VIEW
•	If they create a temporary table, you cannot use a system stored procedure inside a user-defined transaction.

Note  Additionally, you cannot use the sp_dboption system stored procedure to set database options or use any system procedures that change the master database inside user-defined transactions.

•	To cancel all or part of a transaction (to a previously defined savepoint), use the statement ROLLBACK TRANSACTION transaction_name. The transaction's statements or procedures that have changed the database are undone. The ROLLBACK TRANSACTION statement must appear within a transaction. You cannot roll back a transaction after COMMIT TRANSACTION has been entered.

•	Calls to remote stored procedures are executed independently of any transaction in which they're included.

Important  Statements executed with calls to remote stored procedures are not rolled back with ROLLBACK TRANSACTION, and they do not depend on COMMIT TRANSACTION to be executed. In other words, statements executed on a remote server through remote stored procedures happen outside the scope of the local user-defined transaction.

No explicit permission is necessary to define a transaction. By default, all users can define a transaction. All statements used within a transaction follow their specific permission rules.


BEGIN TRANSACTION Statement

Marks the starting point of a user-specified transaction.

Syntax

BEGIN TRANsaction [transaction_name]

where

transaction_name

Is the name assigned to the transaction. The transaction_name must conform to the rules for identifiers. Use transaction names only on the outermost pair of nested BEGIN... COMMIT or BEGIN...ROLLBACK statements.

Remarks

Naming multiple 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 when this error occurs.


COMMIT TRANSACTION Statement

Marks the end of a user-defined transaction.

Syntax

COMMIT TRANsaction [transaction_name]

where

transaction_name

Is the name assigned to the transaction. The transaction_name must conform to the rules for identifiers. Use transaction names only on the outermost pair of nested BEGIN... COMMIT or BEGIN...ROLLBACK statements.

Remarks

The ROLLBACK TRANSACTION statement must appear within a transaction. You cannot roll back a transaction after a COMMIT TRANSACTION statement is executed.


ROLLBACK TRANSACTION Statement

Rolls back a user-specified transaction to the last savepoint inside a transaction or to the beginning of a transaction.

Syntax

ROLLBACK TRANsaction [transaction_name | savepoint_name]

where

transaction_name

Is the name assigned to the transaction. The transaction_name must conform to the rules for identifiers. Use transaction names only on the outermost pair of nested BEGIN... COMMIT or BEGIN...ROLLBACK statements.

savepoint_name

Is the name assigned to the savepoint. The savepoint_name must conform to the rules for identifiers. Use savepoint names only when a conditional rollback should affect only part of the transaction.

Remarks

ROLLBACK TRANSACTION, without a savepoint_name or transaction_name, will roll back to the beginning of the transaction. When nesting transactions, a ROLLBACK TRANSACTION statement, without a transaction_name or savepoint_name, always rolls back statements to the outermost BEGIN TRANSACTION statement and cancels the transaction. All the transaction's statements or procedures are undone. A transaction cannot be rolled back after a COMMIT TRANSACTION statement is executed.

Within a transaction, duplicate savepoint_names are allowed, but when used with ROLLBACK TRANSACTION, only the first instance of a savepoint_name is used.

In triggers or stored procedures, ROLLBACK TRANSACTION statements, without a savepoint_name or transaction_name, roll back all statements to the first BEGIN TRANSACTION in the batch that called the procedure or fired the trigger. A ROLLBACK TRANSACTION statement in a stored procedure or trigger that rolls back past more than one BEGIN TRANSACTION statement produces an error message indicating the number of nesting levels affected. This message (level 16) does not affect subsequent processing.

The rollback also affects all data modification statements issued from within the trigger. The statements executed as a result of the trigger firing and the transaction that attempted the data modification against the table are treated as an atomic unit by the rollback. Remember that the entire transaction is terminated if the rollback is issued from within a trigger. Also note that upon entering the trigger, the global variable @@TRANCOUNT is incremented, in spite of the lack of a BEGIN TRANSACTION statement. (The system treats a trigger as an implied 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 "undo" the modification attempted (that fired the trigger), and 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, use the RAISERROR statement or the PRINT statement. The RAISERROR statement is the preferred method for sending errors.


SAVE TRANSACTION Statement

Sets a savepoint within a transaction.

Syntax

SAVE TRANsaction savepoint_name

where

savepoint_name

Specifies the name assigned to the savepoint. Savepoint names must conform to the rules for identifiers.

Remarks

A user can set a savepoint, or marker, within a transaction. It defines a location to which a transaction can return if part of the transaction might be conditionally canceled. If a transaction is rolled back to a savepoint, it must proceed to completion (with more SQL statements if needed and a COMMIT TRANSACTION statement), or it must be canceled altogether (by rolling it back to its beginning). To cancel an entire transaction, use the form ROLLBACK TRANSACTION transaction_name. All the transaction's statements or procedures are undone.

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


Transaction Example

In this example, you will change the royalty split for the two authors of The Gourmet Microwave. Since 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% 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
CREATE PROCEDURE	SELECT
CREATE TRIGGER	UPDATE
DELETE


TRUNCATE TABLE Statement

Removes all rows from a table without logging the individual row deletes. This allows TRUNCATE TABLE to be efficient and quick, but unrecoverable.

Syntax

TRUNCATE TABLE [[database.]owner.]table_name

Remarks

TRUNCATE TABLE removes all rows from a table, but the table structure and all indexes (although empty of data) continue to exist until you issue a DROP TABLE statement. Defined constraints, rules and defaults bound to the columns, and triggers remain in effect. Additionally, an identity column will be reset to the original seed. If you do not want to reset the identity value for a column, use the DELETE statement without a WHERE clause instead of the TRUNCATE TABLE statement.

The TRUNCATE TABLE works similarly to the DELETE statement but is faster than DELETE. The DELETE statement removes rows one at a time and logs each deleted row as a transaction. TRUNCATE TABLE deallocates whole pages of data and makes fewer log entries. TRUNCATE TABLE guarantees that all rows are removed from the table and cannot be rolled back. DELETE can be rolled back. Both the DELETE and TRUNCATE TABLE statements reclaim the space occupied by the data and its associated indexes.

You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint; instead, use the DELETE statement without a WHERE clause. Because TRUNCATE TABLE is not logged, it cannot activate a trigger.

Note  Because TRUNCATE TABLE deallocates the distribution pages for all indexes, run UPDATE STATISTICS after adding new rows to the table.

Example

This example removes all data from the authors table.

TRUNCATE TABLE authors

Permission

TRUNCATE TABLE permission defaults to the table owner and is not transferable.

See Also

DELETE	DROP TABLE


UNION Operator

In SQL Server 6.5, new behavior is introduced for the UNION Operator due to ANSI-NULL handling. For more information, see ANSI-standard Null Handling.

Combines the results of two or more queries into a single results set consisting of all the rows belonging to all queries in the union.

Syntax

SELECT select_list [INTO clause]
[FROM clause]
[WHERE clause]
[GROUP BY clause]
[HAVING clause]
[UNION [ALL]
SELECT select_list
[FROM clause]
[WHERE clause]
[GROUP BY clause]
[HAVING clause]...]
[ORDER BY clause]
[COMPUTE clause]

where

INTO

Creates a new table based on the columns specified in the select list and the rows chosen in the WHERE clause. The first query in the Transact-SQL statement is the only one that can contain an INTO clause.

UNION

Is a set operation that requires two operands.

ALL

Incorporates all rows into the results, including duplicates.

Remarks

Because UNION is a binary operation, you must add parentheses to an expression involving more than two queries to specify evaluation order. The default evaluation order of a Transact-SQL statement containing UNION operators is left to right. By default duplicate rows are eliminated; however, using UNION with the ALL keyword returns all rows, including duplicates.

The first query in the UNION statement can contain an INTO clause that creates a table to hold the final results set. The INTO statement must be in the first query or an error message will be returned.

GROUP BY and HAVING clauses can be used only within individual queries and cannot be used to affect the final results set. ORDER BY and COMPUTE clauses are allowed only at the end of the UNION statement to define the order of the final results or to compute summary values.

The UNION operator cannot appear within a CREATE VIEW statement or within a subquery. You cannot specify the FOR BROWSE option in queries with the UNION operator.

The UNION operator can appear within an INSERT-SELECT statement. For example:

INSERT INTO salesall

SELECT * FROM sales

UNION

SELECT * FROM saleseast

All select lists in a Transact-SQL statement must have the same number of expressions (such as column names, arithmetic expressions, and aggregate functions). For example, the following statement is invalid because the first select list is longer than the second:

SELECT au_id, title_id, au_ord FROM titleauthor

UNION

SELECT stor_id, date FROM sales

Corresponding columns in the individual queries of a UNION statement must occur in the same order, because UNION compares the columns one to one in the order given in the individual queries.

The descriptions of the columns that are part of a UNION operation do not have to be identical. The following table shows the rules for comparing the datatypes and options of corresponding (ith) columns.

Datatype of ith column	Datatype of ith column of results table
Not datatype-compatible (data conversion not handled implicitly by 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 datatypes (for example, smallint, int, float, money).	Datatype 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 datatype 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.
Examples

A.	Simple UNION

The results set in this example includes the contents of the stor_id and stor_name columns of both the stores and storeseast tables.

SELECT stor_id, stor_name FROM stores

UNION

SELECT stor_id, stor_name FROM storeseast

B.	Selecting INTO with UNION

In this example, the INTO clause in the first query specifies that the table called results hold the final results set of the union of the designated columns of the publishers, stores, and storeseast tables.

SELECT pub_id, pub_name, city INTO results FROM publishers

UNION

SELECT stor_id, stor_name, city FROM stores

UNION

SELECT stor_id, stor_name, city FROM storeseast

C.	UNION of Two SELECT Statements with ORDER BY

The order of certain parameters used with the UNION clause is important. This example illustrates the incorrect and correct usage of UNION in two SELECT statements in which a column is to be renamed in the output.

/* INCORRECT */

SELECT city FROM storeseast

ORDER BY cities

UNION

SELECT cities = city FROM stores

/* CORRECT */

SELECT cities = city FROM storeseast

UNION

SELECT city FROM stores

ORDER BY cities

See Also

Select


UPDATE Statement

For more updated SQL Server 6.5 syntax, see UPDATE Statement.

Changes data in existing rows, either by adding new data or by modifying existing data.

Syntax

UPDATE {table_name | view_name}
SET [{table_name | view_name}]
{column_list
| variable_list
| variable_and_column_list}
[, {column_list2
| variable_list2
| variable_and_column_list2}
...	[, {column_listN
| variable_listN
| variable_and_column_listN}]]
[WHERE clause]

where

table_name | view_name =

[[database_name.]owner.]{table_name | view_name}

Specifies the name of the table or view used in the UPDATE statement. If the table or view is not in the current database, use a fully qualified table_name or view_name (database_name.owner.object_name).

SET

Is a required keyword used to introduce the list of column or variable clauses to be updated. When more than one column name and value pair are listed, separate the names with commas.

column_list =

column_name = {expression | DEFAULT | NULL}

variable_list =

variable_name = {expression | NULL}

column_name

Specifies a column from the table (table_name) or view (view_name).

expression

Is a column_name, constant, function (aggregate functions are not allowed), or any combination of column_names, constants, and functions connected by an operator(s), or a subquery. For details, see the Expressions topic.

DEFAULT

Inserts the default value for that column. For a column defined with the timestamp datatype, the next value will be inserted. If a default does not exist for the column and the column allows NULLs, NULL will be inserted.

DEFAULT is not valid for an identity column; columns with the IDENTITY property should not be explicitly updated. For more information, see the CREATE TABLE statement.

variable_and_column_list =

variable_name = column_name = {expression | NULL}

Sets local variables as well as columns. This syntax provides the same functionality as an UPDATE statement followed by a SELECT statement in an explicitly defined transaction. Because the combination of selecting and updating is performed during a single UPDATE statement, the transaction is implicit and locks are held for a shorter period of time. For sample syntax, see "Setting Variables and Columns," later in this topic.

WHERE clause =

WHERE {search_conditions | CURRENT OF cursor_name}

Is used to perform a searched update (using search_conditions) or a positioned update (using CURRENT OF cursor_name). When no WHERE clause is given in the UPDATE statement, all rows in the table are modified.

search_conditions

Specifies the criteria for a searched update. A search_condition can include an expression, a subquery, a constant, and so on. For details on valid search_conditions, see the Search Conditions topic.

The IDENTITYCOL keyword can be used in the place of a column_name that has the IDENTITY property. For more information, see the CREATE TABLE statement.

CURRENT OF cursor_name

Specifies the criteria for a positioned update against the current row within the specified cursor_name. Cursor operations affect only the single row on which the cursor is positioned. For details about cursors, see the Cursors topic.

Remarks

Use the UPDATE statement to change single rows, groups of rows, or all rows in a table. UPDATE specifies which row(s) to change and provides the new data. When updating rows, these rules apply:

•	Updating a column with an empty string (' ') into a varchar or text column inserts a single space. All char columns are right-padded to the defined length.

All trailing spaces are removed from data inserted into varchar columns, except in strings that contain only spaces. These strings are truncated to a single space.

•	If a column being updated violates a constraint or rule, or if it is the wrong datatype, the update does not take place and an error message is returned.

Constraints are defined with the CREATE TABLE or ALTER TABLE statement. Rules are created with the CREATE RULE statement and bound with the sp_bindrule system stored procedure.

•	Modifying a text column with UPDATE initializes it, assigns a valid text pointer to it, and allocates at least one 2K data page (even if updating the column with NULL). For details about updating text or image fields, see the Text and Image Manipulation topic.

Note  The UPDATE statement is logged; if you are replacing or modifying large blocks of text or image data, use the WRITETEXT or UPDATETEXT statement instead of the UPDATE statement. The WRITETEXT and UPDATETEXT statements (by default) are not logged. For details, see the Text and Image Manipulation topic.

•	An UPDATE statement must follow the rules for a batch. For details, see the Batches topic.

Rules for an Update-In-Place

In SQL Server 6.0, various techniques are used to determine whether or not an UPDATE can be performed "in-place." When an "update-in-place" occurs, the overall performance of the UPDATE statement is improved because the update is direct (only the row modifications to the page are logged). The decision as to whether or not an update-in-place can occur is based on the following requirements. If these requirements are not true, a deferred update will take place. A deferred update is a delete followed by an insert.

•	The UPDATE cannot affect the column(s) that participates in a clustered index.

•	The table cannot have an UPDATE trigger.

•	The table cannot be marked for replication.

•	For single-row updates:

•	The updated column(s) can be variable length, but the new total row size must fit on the same page as the old row.

•	The updated column(s) can participate in a nonunique nonclustered index only if the index key is a fixed-width column.

•	The updated column(s) can participate in a unique nonclustered index only if the index key is fixed-width and the WHERE clause criteria must have an exact match (based on an unique index match—the index could be the same as the updated column).

•	The new row cannot include differing bytes by more than 50 percent of the original row size, and the total number of discontiguous differing bytes is not more than 24.

•	For multirow updates:

•	The updated column must be fixed length.

•	The updated column cannot participate in a unique nonclustered index.

•	The updated column can participate in a nonunique nonclustered index only if the column is a fixed-width column (the index used to find rows cannot be the same as the updated column).

•	The table cannot include a column with the timestamp datatype.

To see the update strategy used (DIRECT or DEFERRED), set the SHOWPLAN session setting. For details, see the SET statement.

Transact-SQL Extension for the UPDATE Statement

In addition to the syntax shown earlier, Transact-SQL includes a feature that allows you to select data from a table or tables and update corresponding data in the first named table. The functionality provided is similar to that of using a correlated subquery as a search_condition in the WHERE clause of a standard UPDATE.

Transact−SQL extension syntax:

UPDATE {table_name | view_name}
SET [{table_name | view_name}]
{column_list
| variable_list
| variable_and_column_list}
[, {column_list2
| variable_list2
| variable_and_column_list2}
...	[, {column_listN
| variable_listN
| variable_and_column_listN}]]
[FROM {table_name | view_name}
[, {table_name | view_name}]...]
[..., {table_name16 | view_name16}]]
[WHERE clause]

where

FROM

Lets you name more than one table or view to use with a WHERE clause to specify which rows to update. The additional FROM clause allows you to update rows from one table based on data stored in other tables, giving you similar functionality to a correlated subquery (SELECT statement in the WHERE clause).

For an example of the differences between correlated subqueries and this Transact-SQL extension, see the examples later in this section.

Setting Variables and Columns

In earlier releases of SQL Server, it was impossible to verify both the new and old values of a modified column. Values returned from the SELECT statement could not be guaranteed at the time of the UPDATE unless an explicitly defined transaction using HOLDLOCK was defined.

In earlier releases:

BEGIN TRANSACTION
SELECT variable_name = column_name1
FROM table_name
WHERE column_name2 = expression
HOLDLOCK
UPDATE table_name
SET column_name1 = expression
WHERE column_name2 = expression
COMMIT TRANSACTION

In SQL Server 6.0:

UPDATE table_name
SET column_name1 = expression, variable_name = column_name1
WHERE column_name2 = expression

In this single update (an implicit transaction), the locks are held only until the update completes (no need to hold them for both an UPDATE and a SELECT).

Permission

UPDATE permission defaults to the table owner, who can transfer it to other users.

Examples

A.	UPDATE Statement with Only the SET Clause

These examples show how all rows can be affected if a WHERE clause is eliminated from an UPDATE statement.

In this example, if all the publishing houses in the publishers table move their head offices to Atlanta, Georgia, this is how the publishers table could be 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 column values in an update. This example doubles all prices in the titles table:

UPDATE titles

SET price = price * 2

B.	UPDATE Statement with a WHERE Clause

The WHERE clause specifies which rows are to be updated. 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, here is 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.	UPDATE Statement with a Nested SELECT Statement

To modify the ytd_sales column to reflect the most recent sales recorded in the sales table, this example assumes that only one set of sales is recorded for a given title on a given date and that updates are current.

UPDATE titles

SET ytd_sales = ytd_sales + qty

FROM titles, sales

WHERE titles.title_id = sales.title_id

AND sales.date = (SELECT MAX(sales.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), then 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 where 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.date IN (SELECT MAX(date) FROM sales))

FROM titles, sales

See Also

CREATE INDEX	DELETE
CREATE TABLE	INSERT
CREATE TRIGGER	Text and Image Manipulation
Cursors	UPDATE


UPDATE STATISTICS Statement

Updates information about the distribution of key values in specified indexes.

Syntax

UPDATE STATISTICS [[database.]owner.]table_name [index_name]

where

table_name

Specifies the table with which the index is associated. The table_name parameter is required because Transact-SQL does not require index names to be unique in a database.

index_name

Specifies the index to be updated. If an index name 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 the sp_helpindex system stored procedure with the table name.

Remarks

SQL Server keeps statistics about the distribution of the key values in each index and uses these statistics in decisions about which index(es) to use in query processing. The optimization of your queries depends on the accuracy of the distribution steps. If there is significant change in the key values in your index, rerun UPDATE STATISTICS on that index. If a great deal of data in an indexed column has been added, changed, or removed (that is, if you suspect that the distribution of key values has changed) or the table has been truncated using the TRUNCATE TABLE statement and then repopulated, use the UPDATE STATISTICS statement.

UPDATE STATISTICS is run automatically when you create or re-create an index on a table that already contains data. However, to see when the statistics were last updated, use the STATS_DATE system function or the DBCC SHOW_STATISTICS option. For syntax and usage, see the Functions topic and the DBCC statement.

Permission

UPDATE STATISTICS permission defaults to the table owner and is not transferable.

Examples

A.	Update All Statistics for a Single Table

This single command will update the distribution statistics for all indexes on the authors table.

UPDATE STATISTICS authors

B.	Update Only the Statistics for a Single Index

To update only the distribution information for one index on a table, specify the index after the table name.

UPDATE STATISTICS authors au_id_ind

C.	Use Cursors to Run UPDATE STATISTICS on All Tables

In this example, the update_all_stats procedure will first create a cursor, tnames_cursor, and then populate the cursor with all rows from sysobjects of type 'U' = User-defined table. After retrieving all table names, this procedure will run UPDATE STATISTICS against each of the tables.

CREATE PROCEDURE update_all_stats

AS

/*

This procedure will run UPDATE STATISTICS against

all user-defined tables within this database.

*/

DECLARE @tablename varchar(30)

DECLARE @tablename_header varchar(75)

DECLARE tnames_cursor CURSOR FOR SELECT name FROM sysobjects
WHERE type = 'U'

OPEN tnames_cursor

FETCH NEXT FROM tnames_cursor INTO @tablename

WHILE (@@fetch_status <> -1)

BEGIN

IF (@@fetch_status <> -2)

BEGIN

SELECT @@tablename_header = "Updating " +

RTRIM(UPPER(@@tablename))

PRINT @@tablename_header

EXEC ("UPDATE STATISTICS " + @@tablename )

END

FETCH NEXT FROM tnames_cursor INTO @@tablename

END

PRINT " "

PRINT " "

SELECT @@tablename_header = "*************  NO MORE TABLES"

+ "  *************"

PRINT @@tablename_header

PRINT " "

PRINT "Statistics have been updated for all tables."

DEALLOCATE tnames_cursor

go

update_all_stats

go

Updating AUTHORS
Updating DISCOUNTS
Updating EMPLOYEE
Updating JOBS
Updating PUB_INFO
Updating PUBLISHERS
Updating ROYSCHED
Updating SALES
Updating STORES
Updating TITLEAUTHOR
Updating TITLES

*************  NO MORE TABLES  *************

Statistics have been updated for all tables.

See Also

CREATE INDEX	EXECUTE
Cursors	sp_helpindex
DBCC	System Functions


USE Statement

In SQL Server 6.5, when the USE statement is used in a batch, dynamic execution of the USE statement retrieves a different database name than if the USE statement was not in a batch.

Changes the database context.

Syntax

USE database_name

where

database_name

Specifies the database to which the user context will be switched.

Remarks

The execution of a USE statement takes effect immediately. This statement is executed both at compile and execution time, so statements that appear after the USE statement in a batch will be executed in the specified database.

It is likely that you will be connected automatically to the master database when you log in to SQL Server. Unless a default database has been set up for your login ID, you must execute the USE statement to change from master to another database.

You must be a known user in the database to which you're changing. If you are not known in the database, SQL Server displays a message. The owner of the database must give you access by executing the sp_adduser system stored procedure.

Users not recognized by name within the destination database can still be allowed access if a guest user exists in that database. A database owner can add the special guest user to any user database by using the sp_adduser system stored procedure. By default, the guest user is added to the master database during installation.

Permission

Permission is assigned when the database owner assigns permission by executing the sp_adduser system stored procedure.

See Also

CREATE DATABASE	sp_addalias
DROP DATABASE	sp_adduser
EXECUTE	sp_defaultdb


Utilities and Executables

SQL Server 6.0 provides a number of utilities that enhance the capabilities of the server and ease usability. The utilities included offer either a command-line or graphical user interface and usually have a specific function. The utilities can be categorized by how they are used.

Command-line Utilities and Executables

These are the utilities executed from the command-line:

Utility program	Executable	Description
bcp*	BCP.EXE	Used for command-line transfers either to or from SQL Server and an operating-system file.
Check Upgrade	CHKUPG.EXE	Used by SQL Setup during an upgrade to check the compatibility of existing user-defined databases. This program can be run standalone to provide information about database keywords and possible upgrade issues. For details, see Microsoft SQL Server Setup.
console*	CONSOLE.EXE	Used with the Transact-SQL DUMP statement to back up databases to diskette dump devices.
isql*	ISQL.EXE	Allows you to enter Transact-SQL statements and system procedures from an interactive command-line prompt. It is also used to run Transact−SQL scripts.
Language Installation	LANGINST.EXE	Used by SQL Setup to install additional language information, such as localized messages and country information.
makepipe* and readpipe*	MAKEPIPE.EXE and READPIPE.EXE	Determine the validity and integrity of the network named-pipe services. Always used together.
Sort Order Installation	CHARSET.EXE	Used by SQL Setup to install character set and order information.
SQL Alerter	SQLALRTR.EXE	Used to integrate the alert engine with the Windows NT Performance Monitor alerter. For details on alert management, see the Microsoft SQL Server Administrator's Companion.
SQL Executive	SQLEXEC.EXE	Used for scheduling alerts and replication. For details, see the Microsoft SQL Server Administrator's Companion.
sqlservr*	SQLSERVR.EXE	The SQL Server executable itself. This program can be started from the command line with special options used for troubleshooting and/or temporarily changing SQL Server behavior.
*  The utilities marked with an asterisk (*) may need to be run standalone. They are detailed in the following sections.
Graphical Utilities

These graphical utilities are provided for ease of use. Each of these utilities provides online Help. For details, start these utilities from the icon in the Microsoft SQL Server 6.0 program group in Program Manager and use the online Help system.

Utility program	Executable	Description
ISQL/w	ISQLW.EXE	A graphical query tool that provides a way to analyze the plan of a query, view statistics information, and manage multiple queries in different windows simultaneously.
SQL Client Configuration Utility	WINDBVER.EXE	Used for managing the client configuration for DB-Library, various Net-Libraries and/or custom named pipes.
SQL Enterprise Manager	SQLEW.EXE	Used for complete SQL Server enterprise management, including: managing servers, databases, objects, alerts, scheduled tasks, replication and queries.
SQL Security Manager	SQSECMGR.EXE	Used for managing SQL Server integrated login security.
SQL Service Manager	SQLMGR.EXE	Used for starting, stopping, and pausing/continuing SQL Server activity.
SQL Setup	SETUP.EXE	Used initially for installation. Also used for upgrades, installing additional components, changing selected configuration options, and removing an installation.
SQL Transfer Manager	SQLXFR.EXE	Used for managing data or object transfers between Microsoft SQL Server and other SQL Server platforms to SQL Server 6.0.


bcp Command-line Utility

Copies a database table to or from an operating-system file in a user-specified format.

Syntax

bcp [[database_name.]owner.]table_name {in | out} datafile
[/m maxerrors] [/f formatfile] [/e errfile]
[/F firstrow] [/L lastrow] [/b batchsize]
[/n] [/c] [/E]
[/t field_term] [/r row_term]
[/i inputfile] [/o outputfile]
/U login_id [/P password] [/S servername] [/v] [/a packet_size]

where

database_name

Specifies the database. If the table being copied is in your default database, this parameter is optional.

owner

Is the owner's name. This name is optional if you own the table being copied. This parameter is optional. If no owner is specified and you do not own a table of that name, the program will not execute.

table_name

Specifies which database table to copy.

in | out

Specifies the direction of the copy. The in option copies from a file into the database table; the out option copies to a file from the database table.

datafile

Is the full path of an operating-system file when copying a table to or from a hard-disk file or a single diskette. The path can have from 1 through 255 characters. When copying a table to or from multiple diskettes, datafile is a drive specifier only (such as A:).

/m maxerrors

Is the maximum number of errors that can occur before the copy is canceled. Each row that cannot be rebuilt by bcp is ignored and counted as one error. If this option is not included, the default is 10.

/f formatfile

Is the full path of a file with stored responses from a previous use of bcp on the same table; creation of the format file is optional. Use this option when you have already created a format file that you want to use when copying in or out. After you answer format questions, bcp asks whether you want to save your answers in a format file. The default filename is BCP.FMT. The bcp utility can refer to a format file when copying data so that you do not have to duplicate your previous format responses interactively. If this option is not used, bcp queries you for format information.

/e errfile

Is the full path of an error file where bcp stores any rows that it was unable to transfer from the file to the database. Error messages from the bcp utility go to the user's workstation. If this option is not used, no error file is created.

/F firstrow

Specifies the number of the first row to copy (the default is the first row).

/L lastrow

Specifies the number of the last row to copy (the default is the last row).

/b batchsize

Specifies the number of rows per batch of data copied (the default copies all the rows in one batch).

/n

Performs the copy operation using the data's native (database) datatypes as the default. This option does not prompt for each field; it uses the default values.

/c

Performs the copy operation with a character datatype as the default. This option does not prompt for each field; it uses char as the default storage type, no prefixes, \t (tab) as the default field separator, and \n (new line) as the default row terminator.

/E

Is used when identity values are present within the table to be imported.

When importing data, an identity column is temporarily assigned an identity value of 0. As the rows are inserted into the table, SQL Server assigns unique values based on the seed and increment values specified during table creation. Use the /E flag when identity values already exist in the file. If SQL Server−generated identity values are preferred, place only non-identity columns in the file.

/t field_term

Is the default field terminator.

/r row_term

Is the default row terminator.

/i inputfile

Is the name of a file that redirects input to bcp.

/o outputfile

Is the name of a file that receives output redirected from bcp.

/U login_id

Is a login ID.

/P password

Is a user-specified password. If this option is not used, bcp prompts for a password. If this option is used at the end of the command line without any password, bcp uses the default password (NULL).

/S servername

Specifies which SQL Server to connect to. The servername is the name of the server computer on the network. This option is required when you are executing bcp from a remote computer on the network.

/v

Reports the current DB-Library version number.

/a packet_size

Is the number of bytes, per network packet, sent to and from the server. A server configuration option can be set using SQL Enterprise Manager (or the sp_configure system stored procedure). However, this option can be overridden on an individual basis with the bcp /a option. The valid values for packet_size are 512 through 65535. The server default is 4096; the default value for the Windows NT − based version of bcp is 4096. The default value for MS-DOS is 512, although larger sizes can be requested.

Increased packet size may enhance performance on bulk copy operations. Microsoft testing indicates that 4096 to 8192 is typically the fastest setting for bulk copy operations. If a larger packet is requested but cannot be granted, the client will default to 512. The performance statistics generated at the end of a bcp run will show the actual packet size used.


console Command-line Utility

Displays backup and restore messages when dumping or loading to or from diskette dump devices. The console command-line utility is used by the person responsible for dumping and loading a database.

Syntax

console [/S servername] [/P pipename]

where

/S servername

Specifies which SQL Server to connect to. The servername is the name of the server computer on the network. This option is required when you are executing console from a remote computer on the network.

/P pipename

Specifies the pipe that the server was started with.

Remarks

The console program must be running before a DUMP or LOAD statement can proceed for diskette dump devices.

The console program prompts the operator for information related to mounting and unmounting diskettes. Since the console workstation (which can be any screen group) displays prompts and messages for the operator, run it in a window on the same Windows NT − based workstation that is running SQL Server. Most console messages are self-explanatory. To stop a dump or load to a diskette, press N in response to any prompt to mount a new diskette.

If two diskettes (that is, two dumps/loads) are being used at once, only one console is needed. The program prints messages one at a time, waiting for a response before displaying the next prompt. For this reason, the messages include the name of the physical drive to which they pertain.

Make sure that the diskette you are using is formatted and not write-protected.

The console utility uses named pipes. If you want to use console on an alternate pipe, you must set up the connection using the SQL Client Configuration Utility.

For details, see the Microsoft SQL Server Administrator's Companion.

Note  If the console utility has been started and appears to be unusable, wait for 1 minute and try to use it again. (SQL Server may be in the process of fixing a broken console connection).


isql Command-line Utility

For more updated SQL Server 6.5 syntax, see ISQLPASSWORD.

Allows you to enter SQL statements and system procedures.

Syntax

isql /U login_id [/e] [/E] [/p] [/n] [/d dbname] [/q "query"] [/Q "query"]
[/c cmdend] [/h headers] [/w columnwidth] [/s colseparator]
[/t timeout] [/m errorlevel] [/L] [/?] [/r {0 | 1}]
[/H wksta_name] [/P password]
[/S servername] [/i inputfile] [/o outputfile] [/a packet_size]

where

/U login_id

Is the user login ID. Login IDs are case-sensitive.

/e

Echoes input.

/E

Uses a trusted connection instead of requesting a password.

/p

Prints performance statistics.

/n

Removes numbering and the prompt symbol (>) from input lines.

/d dbname

Issues a USE dbname statement when isql is started.

/q "query"

Executes a query when isql starts. (Note, the query statement should not include GO). If you issue a query from a batch file, you can use %variables. Environment %variables% also work. For example:

SET table = sysobjects
isql /q "Select * from %table%"

Use double quotation marks around the query and single quotation marks around anything embedded in the query.

/Q "query"

Executes a query and immediately exits isql. Use double quotation marks around the query and single quotation marks around anything embedded in the query.

/c cmdend

Specifies the command terminator. By default, commands are terminated and sent to SQL Server by entering GO on a line by itself. When you reset the command terminator, do not use SQL reserved words or characters that have special meaning to the operating system, whether preceded by a backslash or not.

/h headers

Specifies the number of rows to print between column headings. The default is to print headings only once for each set of query results. Use −1 to specify that no headers will be printed. If using −1, there must be no space between the parameter and the setting (/h−1, not /h -1).

/w columnwidth

Allows the user to set the screen width for output. The default is 80 characters. When an output line has reached its maximum screen width, it is broken into multiple lines.

/s colseparator

Specifies the column-separator character, which is blank by default. To use characters that have special meaning to the operating system (for example, | ; & < >), precede the character with a backslash (\).

/t timeout

Specifies the number of seconds before a command times out. If no timeout is specified, a command runs indefinitely; the default timeout for logging in to isql is 8 seconds.

/m errorlevel

Customizes the display of error messages. The message number, state, and error level are displayed for errors of the specified severity level or higher. Nothing is displayed for errors of levels lower than the specified level. Use −1 to specify that all headers are returned with messages, even informational messages. If using −1, there must be no space between the parameter and the setting (/m−1, not /m -1).

/L

Lists the locally configured servers and the names of the servers broadcasting on the network.

/?

Displays the syntax summary of isql switches.

/r {0 | 1}

Redirects message output to stderr. If you don't specify a parameter, or if you specify 0, only error-level message severity (severity 17 or higher) is redirected. If you specify 1, all message output (including "print") is redirected.

/H wksta_name

Is a workstation name, changing the value in the dynamic system table sysprocesses, if the user logs in from a computer different from the usual login computer. If no workstation name is specified, the current computer name is assumed.

/P password

Is a user-specified password. If the /P option is not used, isql prompts for a password. If the /P option is used at the end of the command line without any password, isql uses the default password NULL. Passwords are case-sensitive.

/S servername

Specifies which SQL Server to connect to. The servername is the name of the server computer on the network. This option is required if you are executing isql from a remote computer on the network.

/i inputfile

Identifies the file that contains a batch of SQL statements or stored procedures. The less-than symbol (<) can be used in place of /i.

/o outputfile

Identifies the file that receives output from isql. The greater-than symbol (>) can be used in place of /o.

/a packet_size

Allows you to request a different size packet. The valid values for packet_size are 512 through 65535. The default value for the Windows NT − based version of isql is 8192; otherwise, the default value is 512 for MS-DOS, although larger sizes can be requested with that version as well. Increased packet size can enhance performance on larger script execution where the amount of SQL statements between GO statements is substantial. Microsoft testing indicates that 8192 is typically the fastest setting for bulk copy operations. A larger packet size can be requested, but will default to 512 if the request cannot be granted.

Remarks

The isql utility is started directly from the operating system with the case-sensitive options listed here. Once started, isql accepts SQL commands and sends them to SQL Server interactively. The results are formatted and printed on the standard output device (the screen). Use QUIT or EXIT to exit from isql.

If you do not specify a username when you start isql, SQL Server checks for the environment variables — for example, isqluser=(user) or isqlserver=(server), and uses those. If no environment variables are set, the workstation username is used. If you do not specify a server, the name of the workstation is used.

If neither the /U or /P options are used, SQL Server uses the currently logged in user account and will not prompt for a password. This is useful when using integrated or mixed security. For details about security, see the Microsoft SQL Server Administrator's Companion.

In addition to using Transact−SQL statements within isql, use the following commands:

Command	Description
GO	Executes a command.
RESET	Clears any statements you have entered.
ED	Calls the editor.
!! command	Executes an operating-system command.
QUIT or EXIT( )	Exits from isql.
CTRL+C	Terminates a query without exiting from isql.
The command terminators, GO (by default), RESET, ED, !!, EXIT, QUIT, and CTRL+C, are recognized only if they appear at the beginning of a line, immediately following the isql prompt. Anything entered on the same line after these keywords is disregarded by isql.

Terminate a command by typing a line beginning with a command terminator. You can follow the command terminator with an integer to specify how many times the command should be run. For example, to execute this command 100 times, type:

SELECT x = 1

go 100

The results are printed once, at the end of execution.

With isql, there is a limit of 1000 characters per line. Large statements should be spread across multiple lines.

The user can call an editor on the current query buffer by typing ED as the first word on a line. Operating-system commands can also be executed by starting a line with two exclamation points (!!) followed by the command. The editor is defined in the EDITOR environment variable. The default editor is "edit" for MS-DOS and Windows NT. You can specify a different editor by setting the EDITOR environment variable. For example, to make the default editor Notepad, at the operating-system prompt, type:

SET EDITOR=notepad

The command recall facilities of DOSKEY can be used to recall and modify previously entered isql statements on a Windows NT − based computer. The existing query buffer can be cleared by typing RESET on a line by itself. It causes any pending input to be discarded.

When running stored procedures, isql prints a blank line between each set of results in a batch. In addition, the "0 rows affected" message does not appear when it doesn't apply to the statement executed.

To use isql interactively, type the isql command (and any of the options) at the operating-system prompt.

You can read in a file containing a query (such as STORES.QRY) for execution by isql by typing a command similar to this:

isql /U alma /P /i stores.qry

The file must include a command terminator(s). The results are displayed on the user's workstation.

You can read in a file containing a query (such as TITLES.QRY) and direct the results to another file by typing a command similar to this:

isql /U alma /P /i titles.qry /o titles.res

When using isql interactively, you can read an operating-system file into the command buffer with :r filename. Do not include a command terminator in the file; enter the terminator interactively once you have finished editing.

You can include comments in a Transact-SQL statement submitted to SQL Server by isql. Two types of commenting styles are allowed. For more information, see the Comments topic.

For example:

SELECT au_lname, au_fname

 -- Retrieve authors' last and first names.

FROM authors a, titles t, titleauthor ta

WHERE a.au_id = ta.au_id

AND t.title_id = ta.title_id

/* This is a three-way join that links authors

** to the books they have written. */

Note  Do not include a GO command within a comment. A GO command within a comment produces an error message.

You can return the result of an integer SELECT as the return value from isql. The first column of the first result row is converted to a 4-byte integer (long). MS-DOS passes the low byte to the parent process or operating-system error level. Windows NT passes the entire 4-byte integer. The syntax is:

EXIT(query)

For example:

EXIT(SELECT @@rowcount)

EXIT(SELECT 5)

You can also include the exit parameter as part of a batch file. For example:

isql /Q "EXIT(SELECT COUNT(*) FROM '%1')"

The isql utility passes everything between the parentheses ( ) to the server exactly as entered. The EXIT( ) statement can span lines. If a stored system procedure selects a set and returns a value, only the selection is returned. The EXIT( ) statement with nothing between the parentheses executes everything preceding it in the batch and then exits with no return value.

There are four exit formats:

•	EXIT

Does not execute the batch; quits immediately and returns no value.

•	EXIT( )

Executes the batch, and then quits and returns no value.

•	EXIT(query)

Executes the batch, including the query, and then quits, returning the results of the query.

•	Using the RAISERROR statement with a severity of 127. If RAISERROR is used within an isql script and a severity of 127 is raised, isql will terminate and return the message ID back to the client. For example,

RAISERROR(50001, 10, 127)

This error will cause the isql script to terminate and the message ID 50001 will be returned to the to the client.

The return values − 1 to − 99 are reserved by SQL Server; isql defines the following values:

 − 100: Error encountered prior to selecting return value.

 − 101: No rows found when selecting return value.

 − 102: Conversion error when selecting return value.


makepipe Command-line Utility

Tests the integrity of the network named pipe services, in conjunction with readpipe.

Syntax

makepipe [/h] [/w] [/p pipename]

where

/h

Displays usage.

/w

Specifies the wait time, in seconds, between read and write. The default is 0.

/p pipename

Is the name of the pipe. The default pipename is abc.

Remarks

This diagnostic utility checks to see if the named pipes are working. Use it (along with readpipe) if you cannot connect to SQL Server.

See Also

readpipe Command-line Utility


readpipe Command-line Utility

Tests the integrity of the network named pipe services, in conjunction with makepipe.

Syntax

readpipe /Sservername /Dstring [/n] [/q] [/w] [/t] [/p pipename] [/h]

where

/Sservername

Is the name of the SQL Server on which you just ran makepipe. Note that there are no spaces between /S and servername.

/Dstring

Is a test character string. Note that there are no spaces between /D and string.

/n

Specifies the number of iterations.

/q

Queries for incoming data (polling). Without /q, readpipe reads the pipe and waits for data.

/w

Specifies the wait time, in seconds, to pause while polling. The default is 0.

/t

Asks for Transact-SQL named pipes. This option overrides polling.

/p pipename

Is the name of the pipe. The default pipename is abc.

/h

Displays usage.

Remarks

This diagnostic utility checks to see if the named pipes are working. Use it (along with makepipe) if you cannot connect to SQL Server.

Because applications for Windows, Windows NT, and MS-DOS all run on Windows NT, you must be careful about which version of makepipe and readpipe you are running. You must use the version specific to the operating system on which you are testing the integrity of the named pipe.

After makepipe is started, the server waits for a client to connect. The readpipe command-line utility can then be run from other workstations. When all testing is complete, go to the screen where the makepipe program is still running and press CTRL+BREAK or CTRL+C to stop execution.

See Also

makepipe command-line utility


sqlservr Command-line Executable

Is the SQL Server executable program.

Syntax

sqlservr [/c] [/dmaster_device_path] [/f] [/eerror_log_path] [/m] [/n]
[/pprecision_level] [/rmaster_mirror] [/sregistry_key] [/Ttrace#] [/x]

where

/c

Indicates to start SQL Server independent of the Windows NT Service Control Manager. This option is used when starting SQL Server from the command line to shorten the amount of time it takes for SQL Server to start. (Note that when you use this option, you cannot stop SQL Server using the SQL Service Manager or the net stop command. And if you log off from the Windows NT system, the SQL Server will be stopped.)

/dmaster_device_path

Indicates the fully qualified path for the MASTER database device (typically, C:\SQL60\DATA\MASTER.DAT). Note that there is no space between /d and master_device_path.

/f

Starts the server in minimally configured mode. The system administrator can then reconfigure configuration options (with the sp_configure system stored procedure) and avoid using the bldmastr command-line utility.

/eerror_log_path

Indicates the fully qualified path for the error log file (typically, C:\SQL60\LOG\ERRORLOG). If you do not specify this option, an error log is not written. Note that there is no space between /e and error_log_path.

/m

Indicates to start SQL Server in single-user mode. When you start SQL Server in single-user mode, only a single user can connect, and the CHECKPOINT mechanism, which guarantees that completed transactions are regularly written from the disk cache to the database device, is not started. (Typically, this option is used if you experience problems with system databases that need to be repaired.)

/n

Indicates that you do not want to use the Windows NT event log to log SQL Server events. If you start SQL Server with the /n option, it is advisable to use the /e option too, or SQL Server events will not be logged.

/pprecision_level

Specifies the maximum level of precision to be supported by decimal and numeric datatypes. By default, SQL Server has a maximum precision of 28. The acceptable values for precision_level are from 1 through 38; however, if no precision_level is supplied with the /p parameter, a maximum precision of 38 will be allowed for decimal and numeric datatypes.

/rmaster_mirror

Indicates the fully qualified path for the device used to mirror the MASTER database device. Use this option when starting SQL Server if the MASTER database device is damaged. (SQL Server always attempts to use the primary device specified by the /d option before it uses the mirror device specified by the /r option.)

/sregistry_key

Indicates that you want to start SQL Server using an alternate set of startup parameters stored in the Windows NT Registry under the key registry_key. This option, which can be run only from the command line, lets you select from multiple previously defined startup configurations. You could, for example, create an alternate Registry key to start SQL Server in single-user mode.

/Ttrace#

Indicates that SQL Server should be started with a specified trace flag (trace#) in effect. Trace flags are used to start the server with non-standard behavior. For a list of available trace flags (trace#), see the Trace Flags topic.

Important  When specifying a trace flag, use /T to pass the trace flag number. A lower case t (/t) is accepted by SQL Server; however, /t sets other internal trace flags that are needed only by SQL Server support engineers.

/x

Disables maintaining CPU statistics.


Variables

Variables are user-defined entities that are assigned values. A local variable is defined with a DECLARE statement, assigned an initial value with a SELECT statement, and used within the statement batch or procedure in which it was declared. Global variables are predefined and maintained by the system.

The following sections describe the declaration of local variables as well as the use of local and global variables.

Local Variables

Local variables are declared in the body of a batch or procedure with the DECLARE statement and given values with a SELECT statement. Local variables are often used in a batch or procedure as counters for WHILE loops or for IF...ELSE blocks.

Syntax

Variable declaration:

DECLARE @@variable_name datatype
[, @@variable_name datatype...]

Variable assignment:

SELECT @@variable = {expression | select_statement}
[, @@variable = {expression | select_statement}...]
[FROM table_list]
[WHERE search_conditions]
[GROUP BY clause]
[HAVING clause]
[ORDER BY clause]

where

@@variable_name

Is the name of a variable. Variable names must be preceded by the "at" symbol (@@). The single @@ preceding the alphanumeric name signifies a local variable name. The variable name must conform to the rules for identifiers except that it can contain only 29 characters. Variables can be used only in place of constants. In standard SQL statements, variables cannot be used in place of the names of tables, columns, other database objects, or keywords. In SQL Server 6.0, strings can be resolved at execution time (rather than at compile time) by using the EXECUTE statement. For more information, see the EXECUTE statement.

datatype

Is a system or user-defined datatype. A variable cannot be of the image datatype. For more information on system datatypes, see the Datatypes topic. For more information about user-defined datatypes, see the sp_addtype system stored procedure.

Remarks

Local variables are often used in batches, stored procedures, and control-of-flow statement blocks. Local variables can be used only within the batch or procedure in which they are declared. When used in stored procedures, local variables are declared for automatic, non-interactive use by the procedure when it executes.

The SELECT statement that assigns a value to the local variable usually returns a single value. If the SELECT variable assignment statement returns more than one value, the variable is assigned the last value returned. If the SELECT variable assignment statement returns no rows, the variable retains its present value unless the variable assignment is made with a subquery. Only if the subquery returns no rows is the variable set to NULL. The SELECT statement that assigns values to variables cannot retrieve data in the same statement.

Global Variables

Predefined global variables can be used without being declared. Global variables are distinguished from local variables by having two "at" symbols (@@) preceding their names. Many of the global variables report on system activity since the last time SQL Server was started; others report information about a connection. In the listing that follows, connection-specific variables are noted with an asterisk (*). For information on the contents of a connection-specific variable, execute SELECT @@variablename. For the contents of many of these global variables, execute the sp_monitor system stored procedure.

@@CONNECTIONS

Specifies the number of logins or attempted logins since SQL Server was last started.

@@CPU_BUSY

Specifies the amount of time, in ticks (one three-hundredth second, or 3.33 milliseconds), that the CPU has spent doing SQL Server work since the last time SQL Server was started.

@@CURSOR_ROWS*

Specifies the number of qualifying rows in the last-opened cursor. @@CURSOR_ROWS returns:

−m	If the cursor is being populated asynchronously. The value returned (−m) refers to the number of rows currently in the keyset.
n	If the cursor is fully populated. The value returned (n) refers to the number of rows.
0	If no cursors have been opened or the last opened cursor has been closed or deallocated.
@@DBTS

Specifies the value of the current timestamp datatype for the database. This timestamp is guaranteed to be unique for the database.

@@ERROR*

Specifies the last error number generated by the system for the user connection. The @@ERROR global variable is commonly used to check the error status (succeed or fail) of the most recently executed statement. It contains 0 if the last statement succeeded. Using @@ERROR with control-of-flow statements is advantageous for handling errors. The statement IF @@ERROR < > 0 RETURN exits if an error is returned.

@@FETCH_STATUS*

Contains the status of a cursor FETCH command. It is set to 0 if the fetch is successful, to − 1 if the fetch failed or the row was beyond results set, − 2 if the row fetched is missing.

@@IDENTITY*

Saves the last-inserted IDENTITY value. The @@IDENTITY variable is updated specifically for each user when an INSERT or SELECT INTO statement or bulk copy inserting into a table occurs. If a statement changes the table without an identity column, @@IDENTITY is set to NULL. 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. For more information, see the IDENTITY property.

@@IDLE

Specifies the amount of time, in ticks (one three-hundredth second, or 3.33 milliseconds), that SQL Server has been idle since it was last started.

@@IO_BUSY

Specifies the amount of time, in ticks (one three-hundredth second, or 3.33 milliseconds), that SQL Server has spent doing input and output operations since it was last started.

@@LANGID*

Specifies the local language ID of the language currently in use (specified in syslanguages.langid).

@@LANGUAGE*

Specifies the language currently in use (specified in syslanguages.name).

@@MAX_CONNECTIONS

Specifies the maximum number of simultaneous connections that can be made with SQL Server in the current computer environment. The user can configure SQL Server for fewer connections by using the sp_configure system stored procedure. @@MAX_CONNECTIONS is not necessarily the number configured currently.

@@MAX_PRECISION

Returns the level of precision used by decimal and numeric datatypes as currently set in the server. By default, the maximum precision is 28; however, a larger precision can be set when SQL Server starts by using the /p parameter with sqlservr. For more information, see the Utilities and Executables topic.

@@MICROSOFTVERSION

Is a version used internally to track the current version of the server. If version checking is necessary, use @@VERSION.

@@NESTLEVEL*

Specifies the nesting level of the current execution (initially 0). Each time a stored procedure calls another stored procedure, the nesting level is incremented. If the maximum of 16 is exceeded, the transaction is terminated.

@@PACK_RECEIVED

Specifies the number of input packets read by SQL Server since it was last started.

@@PACK_SENT

Specifies the number of output packets written by SQL Server since it was last started.

@@PACKET_ERRORS

Specifies the number of errors that have occurred while SQL Server was sending and receiving packets since the last time SQL Server was started.

@@PROCID*

Specifies the stored procedure ID of the currently executing procedure.

@@REMSERVER*

Returns the server name contained within a remote server's login record.

@@ROWCOUNT*

Specifies the number of rows affected by the last statement. This variable is set to 0 by any statement that does not return rows, such as an IF statement.

@@SERVERNAME

Specifies the name of the local SQL Server. You must define this name with the sp_addserver system stored procedure, and then restart SQL Server. The setup program sets this variable to the computer name during installation. Although you can change @@SERVERNAME by using the sp_addserver system stored procedure and restarting SQL Server, this method is not usually required.

@@SERVICENAME

Specifies the name of a running service. Currently, @@SERVICENAME defaults to @@SERVERNAME.

@@SPID*

Specifies the server process ID number of the current process (the spid column of the sysprocesses system table).

@@TEXTSIZE*

Specifies 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. The default limit is 4K.

@@TIMETICKS

Specifies the number of microseconds per tick. The amount of time per tick is computer-dependent. Each tick on the operating system is 31.25 milliseconds (1/32 second).

@@TOTAL_ERRORS

Specifies the number of errors that have occurred while SQL Server was reading or writing since the last time SQL Server was started.

@@TOTAL_READ

Specifies the number of disk reads by SQL Server since it was last started (disk reads only, not cache reads).

@@TOTAL_WRITE

Specifies the number of disk writes by SQL Server since it was last started.

@@TRANCOUNT*

Specifies the number of currently active transactions for the current user.

@@VERSION

Specifies the date, version number, and processor type for the current version of SQL Server.

See Also

Datatypes	RAISERROR
PRINT	sp_monitor


Wildcard Characters

Wildcard characters are used with the LIKE keyword to represent any character in a string when searching for a char, varchar, or datetime value.

Syntax

expression [NOT] LIKE 'string'

The string can include these wildcard characters:

Wildcard	Meaning
%	Any string of zero or more characters
_ (underscore)	Any single character
[ ]	Any single character within the specified range ([a−f]) or set ([abcdef])
[^]	Any single character not within the specified range ([^a−f]) or set ([^abcdef])
Remarks

You can use the LIKE keyword and wildcard characters with datetime data as well as with char and varchar data. When you use LIKE with datetime values, SQL Server converts the dates to the standard datetime format and then to varchar. Since the standard storage format doesn't include seconds or milliseconds, you cannot search for seconds or milliseconds with LIKE and a pattern. It is a good idea to use LIKE when you search for datetime values, since datetime entries can contain a variety of date parts. For example, if you insert the value 9:20 into a column named arrival_time, the clause WHERE arrival_time = '9:20' does not find the value because SQL Server converts the entry into 'Jan 1, 1900 9:20 AM'. However, the clause WHERE arrival_time LIKE '%9:20%' does find the value.

To use %, _, [ ], or [^] as literal characters in a LIKE string rather than as wildcards, use square brackets around the percent sign, the underscore, and the open bracket. Use the close bracket by itself. Use the dash as the first character inside a set of square brackets, as shown here:

Symbol	Meaning
LIKE '5%'	5 followed by any string of 0 or more characters
LIKE '5[%]'	5%
LIKE '_n'	an, in, on, and so on
LIKE '[_]n'	_n
LIKE '[a−cdf]'	a, b, c, d, or f
LIKE '[−acdf]'	−, a, c, d, or f
LIKE '[ [ ]'	[
LIKE ']'	]
You can't always duplicate NOT LIKE patterns with LIKE and the negative wildcard [^] because NOT LIKE finds the items that do not match the entire LIKE pattern; LIKE with negative wildcards is evaluated one character at a time.

For example, this query shows all system tables in a database, because they all begin with the letters sys:

SELECT name

FROM sysobjects

WHERE name LIKE 'sys%'

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 won't always find the same names with a pattern such as LIKE '[^s][^y][^s]%'. Instead of 19 names, you might 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 result occurs 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.

Pattern Matching with Blanks

When performing string comparisons with LIKE, all characters in the pattern string are significant, including every leading and/or trailing blank (space). A string comparison using a pattern 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 datatype and where a LIKE comparison may fail. In the following example, a local char variable is passed to a stored procedure and then pattern matching is used 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 will be returned because the char variable (@@au_lname) will contain trailing blanks whenever the name contains fewer than 20 characters. Because the au_lname column is varchar, there are no trailing blanks. This procedure will fail because the trailing blanks are significant.

This example succeeds because trailing blanks are not added to a varchar variable:

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 + '%'

Examples

A.	Pattern Matching with LIKE and %

This example finds all phone numbers in the authors table that begin with the 415 area code:

SELECT phone

FROM authors

WHERE phone LIKE '415%'

B.	Pattern Matching and Placement of NOT

These two queries are equivalent: they find all phone numbers in the authors table that do not begin with the 415 area code:

SELECT phone

FROM authors

WHERE phone NOT LIKE '415%'

SELECT phone

FROM authors

WHERE NOT phone LIKE '415%'

C.	Multiple Wildcards

This example finds all names that have the characters "en" in them (Bennet, Green, McBadden):

SELECT au_lname

FROM authors

WHERE au_lname LIKE '%en%'

D.	Single Character Wildcard

This example finds six-letter names that end with "heryl" (Cheryl or Sheryl):

SELECT au_fname

FROM authors

WHERE au_fname LIKE '_heryl'

E.	Single Character Range

This example finds names ending with "inger" and beginning with any single character between "M" and "Z":

SELECT au_lname

FROM authors

WHERE au_lname LIKE '[M-Z]inger'

F.	Single Character Listing

This example finds both DeFrance and deFrance:

SELECT au_lname

FROM authors

WHERE au_lname LIKE '[dD]eFrance'

G.	NOT a Single Character

This example finds names beginning with "M" that have a second letter that is not "c":

SELECT au_lname

FROM authors

WHERE au_lname LIKE 'M[^c]%'

See Also

Expressions	Search Conditions


Appendix A   System Tables Diagram
System Tables Diagram

The following illustration shows the realtionships among the system catalog and database catalog tables.


Appendix B   The pubs sample Database
The pubs sample Database

authors Table

Column_name	Datatype	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
(1) The 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, au_fname.
The following tables show the contents of the authors table. The first column (au_id) is repeated in the lower listing, along with columns #5 through #9. Column #1 is repeated for readability purposes only.

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 Table

Column_name	Datatype	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 Table

Column_name	Datatype	Nullable	Default	Check	Key/Index
emp_id	empid	no		yes (1)	PK, nonclust.
fname	varchar(20)	no			Composite, clust. (2)
minit	char(1)	yes			Composite, clust.  (2)
lname	varchar(30)	no			Composite, clust.  (2)
job_id	smallint	no	1		FK jobs(job_id)
job_lvl	tinyint	no	10
pub_id	char(4)	no	'9952'		FK publishers(pub_id)
hire_date	datetime	no	GETDATE( )
(1) The CHECK constraint is defined as (emp_id LIKE '[A-Z][A-Z][A-Z][1-9][0-9][0-9][0-9][0-9][FM]')  OR  (emp_id LIKE '[A-Z]-[A-Z][1-9][0-9][0-9][0-9][0-9][FM]') (2) The composite, clustered index is defined on lname, fname, minit.
The following tables show the contents of the authors table. The first column (emp_id) is repeated in the lower listing, along with columns #6 through #8. Column #1 is repeated for readability purposes only.

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

Column_name	Datatype	Nullable	Default	Check	Key/Index
job_id	smallint	no	IDENTITY(1,1)		PK, clust.
job_desc	varchar(50)	no	yes (1)
min_lvl	tinyint	no		yes (2)
max_lvl	tinyint	no		yes (3)
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 Officier	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
(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).
pub_info Table

Column_name	Datatype	Nullable	Default	Check	Key/Index
pub_id	char(4)	no			PK, clust., FK publishers(pub_id)
logo	image	yes
pr_info	text	yes
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, Massachusettes.
0877	BINNET.BMP	This is sample text data for Binnet & Hardley, publisher 0877 in the pubs  database. Binnet & Hardley is located in Washington, D.C.
1389	ALGODATA.BMP	This is sample text data for Algodata Infosystems, publisher 1389 in the pubs  database. Algodata Infosystems is located in Berkeley, California.
1622	5LAKES.BMP	This is sample text data for Five Lakes Publishing, publisher 1622 in the pubs  database. Five Lakes Publishing is located in Chicago, Illinois.
1756	RAMONA.BMP	This is sample text data for Ramona Publishers, publisher 1756 in the pubs  database. Ramona Publishers is located in Dallas, Texas.
9901	GGGG.BMP	This is sample text data for GGG&G, publisher 9901 in the pubs database.  GGG&G is located in München, Germany.
9952	SCOOTNEY.BMP	This is sample text data for Scootney Books, publisher 9952 in the pubs  database. Scootney Books is located in New York City, New York.
9999	LUCERNE.BMP	This is sample text data for Lucerne Publishing, publisher 9999 in the pubs  database. Lucerne Publishing is located in Paris, France.
(1) The information shown here is NOT the actual data. It is the filename from which the bitmap (image data) was loaded. (2) The text shown here is NOT the complete text data. When displaying text data the display is limited to a finite number of characters. This information shows the first 120 characters of the text column.
publishers Table

Column_name	Datatype	Nullable	Default	Check	Key/Index
pub_id	char(4)	no		yes (1)	PK, clust.
pub_name	varchar(40)	yes
city	varchar(20)	yes
state	char(2)	yes
country	varchar(30)	yes	'USA'
(1) The pub_id CHECK constraint is defined as (pub_id = '1756' OR (pub_id = '1622' OR (pub_id ='0877'  OR (pub_id = '0736' OR (pub_id = '1389')))) OR (pub_id LIKE '99[0-9][0-0]').
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 Table

Column_name	Datatype	Nullable	Default	Check	Key/Index
title_id	tid	no			FK titles(title_id)
lorange	int	yes
hirange	int	yes
royalty	int	yes
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 Table

Column_name	Datatype	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, title_id.
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 Table

Column_name	Datatype	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
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 Table

Column_name	Datatype	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, 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.
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 Table

Column_name	Datatype	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( )
The following tables show the contents of the titles table. The first column (title_id) is repeated in the lower listing, along with columns #5 through #8, #9, and #10. Column #1 is repeated for readability purposes only.

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


Part 4   What's New for Transact-SQL
What's New for Transact-SQL

This part highlights additions and improvements to Microsoft Transact-SQL that are provided in Microsoft SQL Server 6.5, and it supplements the information that is presented in the Microsoft SQL Server Transact-SQL Reference for SQL Server 6.0. The following table identifies Transact-SQL features as new or enhanced in SQL Server 6.5. Features are in alphabetical order.

Feature	New	Enhanced
@@OPTIONS global variable	•
ANSI-standard null handling	•
Bound connections	•
Catalog stored procedures
sp_column_privileges		•
sp_columns		•
sp_datatype_info		•
sp_fkeys		•
sp_sproc_columns		•
sp_table_privileges		•
Composite indexes		•
CUBE operator	•
Data definition language    in transactions		•
Disabling constraints	•
Distributed transactions	•
Extended stored procedures
xp_cmdshell		•
xp_readmail		•
xp_sendmail		•
xp_snmp_getstate	•
xp_snmp_raisetrap	•
xp_sqlinventory	•
xp_sqltrace	•
float datatype		•
Functions
APP_NAME built-in	•
USER	•
Insert row-level locking (IRL)	•
Joins		•
Replication stored procedures
sp_addsubscriber		•
sp_addsubscription		•
sp_changearticle
sp_changesubscriber		•
sp_dsninfo	•
sp_enumdsn	•
sp_helpsubscriberinfo		•
sp_replcmds		•
Replication of text and image    datatypes	•
ROLLUP operator	•
SQL Executive stored procedures
sp_addtask		•
sp_helphistory		•
sp_helptask		•
sp_runtask		•
sp_updatetask		•
Statements
ALTER TABLE		•
BEGIN DISTRIBUTED    TRANSACTION	•
CREATE INDEX		•
CREATE SCHEMA	•
CREATE TABLE		•
DECLARE CURSOR		•
DBCC DBREINDEX	•
DBCC PROCCACHE	•
DBCC ROWLOCK	•
DBCC UPDATEUSAGE	•
DISK INIT		•
DUMP		•
EXECUTE		•
FETCH		•
GRANT		•
INSERT		•
ISDATE and ISNUMERIC	•
LOAD		•
RAISERROR		•
REVOKE		•
SELECT		•
SET		•
UPDATE
System stored procedures		•
sp_addlogin	•
sp_bindsession		•
sp_certify_removable	•
sp_change_users_login	•
sp_coalesce_fragments		•
sp_configure		•
sp_dboption	•
sp_dropwebtask	•
sp_fallback_activate_svr_db	•
sp_fallback_deactivate_svr_db	•
sp_fallback_enroll_svr_db	•
sp_fallback_help	•
sp_fallback_permanent_svr	•
sp_fallback_upd_dev_drive	•
sp_fallback_withdraw_svr_db	•
sp_getbindtoken	•
sp_helplogins		•
sp_helprotect	•
sp_help_revdatabase		•
sp_helpserver	•
sp_makewebtask	•
sp_rename	•
sp_runwebtask		•
sp_serveroption	•
sp_setnetname		•
sp_tableoption	•
sp_who
Tables		•
MSsubscriber_info	•
sysbackupdetail	•
sysbackuphistory		•
syscolumns		•
sysindexes		•
sysprocesses		•
sysprotects	•
sysrestoredetail	•
sysrestorehistory		•
text datatype		•
Trace flags
Utilities		•
isql options		•
ISQLPASSWORD	•
PRINTDMP.EXE command-prompt    utility	•
SQLMAINT.EXE command-prompt    utility	•
Web pages


@@OPTIONS  Global Variable
@@OPTIONS Global Variable (version 6.5)

The @@OPTIONS global variable provides information about the current values of query-processing SET options. The SET options can be modified as a whole by using the sp_configure 'user options' configuration option. Each user has an @@OPTIONS global variable that represents the configuration environment. When first logging in, all users are assigned a default configuration environment that is set by the system administrator.

You can change the query-processing options by using the SET statement.

Values within @@OPTIONS are the same as the configuration values for 'user options' in sp_configure.

For more information, see SET Statement .

For more information about sp_configure 'user options', see sp_configure.

Example

This example switches on the NOCOUNT option and then tests the value of @@OPTIONS. The NOCOUNT ON option prevents the number of rows affected message from being sent back to the requesting client for every statement in a session. The value of @@OPTION is set to 512 (0x0200), which represents the NOCOUNT option. The following statement tests whether the NOCOUNT option has been enabled on the client. For example, it can help to track down performance differences on a client machine.

SET NOCOUNT ON
IF @@OPTIONS & 512 > 0

RAISERROR ('Current user has SET NOCOUNT turned on.',1,1)


ANSI-standard Null Handling
ANSI-standard Null Handling (version 6.5)

The American National Standards Institute (ANSI) provides standards throughout the trade and communications industries to promote compatibility among products and establish common behavior in related products.

Microsoft SQL Server 6.5 complies with ANSI standards and retains backward compatibility with configuration options that can be switched on or off by using the SET statement. These options enforce data manipulation behavior for the duration of a user's work session or for the duration of a running trigger or a stored procedure.

These are the new configuration options.

Enabling options	Description
SET ANSI_NULLS ON	Specifies ANSI-standard behavior of the comparison operators, EQUAL (=) and NOT EQUAL (< >). ANSI-standards require that a null value in any statement evaluates to NULL. Default is OFF.
SET ANSI_WARNINGS ON	Specifies warnings are generated when null values appear in aggregate functions when data is truncated during an update or when arithmetic overflows occur. Default is OFF.
SET ANSI_PADDING ON	In varchar and varbinary columns, trailing spaces and NULLS are not deleted. When this option is set to OFF, trailing spaces and NULLS are deleted in these columns. Default is OFF.
SET ANSI_DEFAULTS ON	Turns on all ANSI-standard behaviors. This option includes setting to ON these options: ANSI_NULLS, ANSI_NULL_DFLT_ON, ANSI_PADDING, ANSI_WARNINGS, ARITHABORT, CURSOR_CLOSE_ON_COMMIT, IMPLICIT_TRANSACTIONS, and QUOTED_IDENTIFIER. Default is OFF.
For information about the SET statement, comparison operators, and aggregate functions, see SET Statement.


Bound Connections
Bound Connections (version 6.5)

Bound connections allow two or more connections to share the same transaction lock space and the same transaction, and to work on the same data without lock conflicts. Bound connections can be created from multiple connections within the same application, from multiple applications on the same computer with separate connections, or from multiple applications on different computers with separate connections.

By using bound connections, an extended stored procedure can share the transaction space of the connection that called it by invoking the extended stored procedure. Bound connections make coordinating actions across multiple connections easier.

To participate in a bound connection, the first connection gets a bind token, a character string that SQL Server uses to keep track of the bound transaction and that uniquely identifies each bound transaction, by using sp_getbindtoken or srv_getbindtoken (Open Data Services). The bind token is then transmitted or passed to the other connections that will participate in the same bound connection. The other participating connections call sp_bindsession by using the bind token received from the first connection.

Think of a bound connection as a conference call. Person P1 places a telephone call or connection to person P2. To add person P3 to the existing call or connection, P1 uses a conference mechanism. Only one person involved in the conference call can talk at a time. Now replace the people in the conference call with database connections where bound connections use bind tokens. Only one connection involved in a bound connection can interact with the server at a time.

The following example of bound connections illustrates how two connections can access the same transaction: A customer decides to purchase a product at a local department store. The salesperson accesses a sales transaction system that inserts a row into the sales transaction table, including a credit card authorization number. Two connections are made to the same server: connection C1 and connection C2. C1 begins a transaction that adds a product sale row to the sales table. A credit card authorization number must be added to the new sales transaction row. During the credit card authorization process, the extended stored procedure creates connection C2 to dial out across a telephone line to the credit card company and modifies the sales transaction row with the credit card authorization number. Only by using bound connections can both connections access the same row without locking conflicts.

Once the two or more connections are bound together by using bind tokens, only one connection at a time can actively use the bound connection. If one connection is executing a statement on the server or has results pending from the server, no other connections that share the same transaction space can access the server until the current connection finishes executing the current statement. If the server is busy, an error occurs indicating that the transaction space is in use and that the connection should retry later.

Note  The application developer should add the appropriate recovery code for a server busy error.

There are two types of bound connections: local and distributed. A local bound connection allows two or more connections to share the same transaction space of a single transaction on a single server until the entire transaction is either committed or rolled back. A distributed bound connection allows two servers to participate in the same transaction until the entire transaction is either committed or rolled back by using Microsoft Distributed Transaction Coordinator (MS DTC). For more information about distributed transactions, see Distributed Transactions and the Guide to Microsoft Distributed Transaction Coordinator.

If a bound connection is involved in a local transaction and executes a remote procedure call (RPC) on a remote server with SET REMOTE_PROC_TRANSACTIONS ON, the local bound transaction is automatically promoted to a distributed bound transaction by MS DTC and an MS DTC session is started. When the transaction is promoted, the bind token changes to a distributed token identification number. This new token identification number should be used with any future calls to sp_bindsession. For more information about using RPC calls and the SET REMOTE_PROC_TRANSACTIONS ON statement, see the Guide to Microsoft Distributed Transaction Coordinator.

Bound connections are also useful in developing extended stored procedures that can use ODBC or DB-LIBRARY to call back to the server and share the same transaction lock space as the connection calling the extended stored procedure. This method allows an extended stored procedure more flexibility when performing database functions.

Bound connections can also be used to develop three-tier applications where business logic is represented in separate programs that can work cooperatively on a single business transaction.

For more information about bound connections, see sp_bindsession and sp_getbindtoken.

For more information about using bound connections with Open Data Services, see sp_getbindtoken.


Composite Indexes
Composite Indexes (version 6.5)

Composite indexes can now contain 900 bytes in the index. The order and number of columns in a composite index affect performance. Listing a greater number of columns in the index improves performance for covered queries that benefit by having a column or search criteria listed in the composite index. However, indexes that cover fewer columns require less I/O to update and insert rows.


CUBE Operator
CUBE Operator (version 6.5)

In SQL Server 6.5, there is an aggregate operator called CUBE, which can be used to produce results sets that typically are used for reports.

The CUBE operator is an additional switch in the GROUP BY clause in the SELECT statement. For additional information about the SELECT statement, see SELECT Statement in this document and in the Microsoft SQL Server Transact-SQL Reference.

The CUBE operator is used with an aggregate function to generate additional rows in a results set. Columns included in the GROUP BY clause are cross-referenced to produce a superset of groups. The aggregate function specified in the select_list is applied to these groups to produce summary values for the additional super-aggregate rows. The number of extra groups in the results set is determined by the number of columns included in the GROUP BY clause.

The aggregate function used in the SELECT statement is applied to the cross-referenced columns for the super-aggregate calculation. The CUBE operator can be applied to all aggregate functions, including AVG, SUM, MAX, MIN, and COUNT.

In fact, every possible combination of the columns or expressions in the GROUP BY clause is used to produce super-aggregates. If you have n columns or expressions, there are 2 (n) −1 possible super-aggregate combinations. Mathematically, these combinations form an n-dimensional cube, which is how the operator got its name.

The ROLLUP operator, which produces a summary of aggregates, has also been added in SQL Server 6.5. It is useful when only summary information is needed and a full CUBE provides extraneous data. For more information about the ROLLUP operator, see ROLLUP Operator.

The following are guidelines for using the CUBE operator:

•	The maximum size of a GROUP BY column list is 900 bytes.

•	A maximum of 10 columns or expressions are permitted when WITH CUBE or WITH ROLLUP is specified.

•	Columns or expressions must be specified in the GROUP BY clause; GROUP BY ALL is not permitted.

•	The CUBE and ROLLUP operators are disabled when trace flag 204 is ON.

You can use the CUBE operator to present cross-referenced information without having to write additional procedures. Consider a personnel department report that includes information such as job titles, home addresses, and modes of transportation to work. The SELECT statement reports on these records for each employee. By introducing the CUBE operator and the COUNT aggregate function, you can obtain statistics such as the number of people who drive to work and from what locations, and whether their jobs may be related to where they live or how they get to work.

You might also apply the CUBE operator to a company sales management report that records sales personnel, customers, products, and quantities sold of each product. A SELECT statement used with the SUM aggregate function produces a report of how many of each product were sold, to which customers, and by which sales persons.

The CUBE operator expands the information returned by cross-referencing and reporting data such as the products that particular customers frequently buy, which sales personnel sell the most of a particular product, and which products are the most popular. By using application or programming tools, this information can then be fed into charts and graphs that convey results and relationships visually and effectively.

Examples

A.	Use the SELECT Statement with the CUBE Operator

This example demonstrates the results set from a SELECT statement that uses 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.

SELECT title, "qty" = SUM(qty)

FROM sales, titles
WHERE sales.title_id = titles.title_id
GROUP BY title
WITH CUBE

This is the results set:

title                                              qty
-------------------------------------------------- -----------
But Is It User Friendly?                                    30
Computer Phobic AND Non-Phobic Individuals: Behavi          20
Cooking with Computers: Surreptitious Balance Shee          25
Emotional Security: A New Algorithm                         25
Fifty Years in Buckingham Palace Kitchens                   20
Is Anger the Enemy?                                        108
Life Without Fear                                           25
Onions, Leeks, and Garlic: Cooking Secrets of the           40
Prolonged Data Deprivation: Four Case Studies               15
Secrets of Silicon Valley                                   50
Silicon Valley Gastronomic Treats                           10
Straight Talk About Computers                               15
Sushi, Anyone?                                              20
The Busy Executive's Database Guide                         15
The Gourmet Microwave                                       40
You Can Combat Computer Stress!                             35
(null)                                                     493

(17 row(s) affected)

The null value represents all values in the title column. The results set returns values for the quantity sold of each title and the total quantity sold of all titles. For this particular example, applying the CUBE operator or ROLLUP operator returns the same result.

B.	Use the CUBE Operator on a Results Set with Three Columns

The 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 results set contains more detailed information about the quantities of titles sold by publishers. The null value represents all values in the title column.

SELECT pub_name, title, "qty" = SUM(qty)

FROM sales, titles, publishers
WHERE sales.title_id = titles.title_id
AND publishers.pub_id = titles.pub_id
GROUP BY pub_name, title
WITH CUBE

This is the results 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
Binnet & Hardley     Onions, Leeks, and Garlic: Cooking Secr     40
Binnet & Hardley     Silicon Valley Gastronomic Treats           10
Binnet & Hardley     Sushi, Anyone?                              20
Binnet & Hardley     The Gourmet Microwave                       40
Binnet & Hardley     (null)                                     150
New Moon Books       Emotional Security: A New Algorithm         25
New Moon Books       Is Anger the Enemy?                        108
New Moon Books       Life Without Fear                           25
New Moon Books       Prolonged Data Deprivation: Four Case St    15
New Moon Books       You Can Combat Computer Stress!             35
New Moon Books       (null)                                     208
(null)               (null)                                     493
(null)               But Is It User Friendly?                    30
(null)               Computer Phobic AND Non-Phobic Individua    20
(null)               Cooking with Computers: Surreptitious Ba    25
(null)               Emotional Security: A New Algorithm         25
(null)               Fifty Years in Buckingham Palace Kitche     20
(null)               Is Anger the Enemy?                        108
(null)               Life Without Fear                           25
(null)               Onions, Leeks, and Garlic: Cooking Secre    40
(null)               Prolonged Data Deprivation: Four Case St    15
(null)               Secrets of Silicon Valley                   50
(null)               Silicon Valley Gastronomic Treats           10
(null)               Straight Talk About Computers               15
(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 illustrates why the CUBE operator is an n-dimensional operator. A GROUP BY clause that has two columns returns three more groups when the CUBE operator is used.

The results 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.

The (null) value in the title column stands for "all titles." See the GROUPING function later in this section for information about how to differentiate specific values and all values in the results set. The CUBE operator returns these groups of information from one SELECT statement:

•	The quantity of each title that each publisher has sold.

•	The quantity of each title sold.

•	The quantity of titles sold by each publisher.

•	The 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 results set. Information returned in the results set grows n-dimensionally along with the number of cross-referenced 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 were to use au_fname and au_lname, the CUBE operator would return irrelevant information such as the number of books sold by authors with the same first name.

C.	Use the CUBE Operator on a Results Set with Four Columns

In this example, the GROUP BY clause contains three columns that are 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.

SELECT pub_name, au_lname, title, SUM(qty)

FROM publishers, authors, titles, titleauthor, sales
WHERE publishers.pub_id = titles.pub_id
AND authors.au_id = titleauthor.au_id
AND titleauthor.title_id = titles.title_id
AND titles.title_id = sales.title_id
GROUP BY pub_name, au_lname, title
WITH CUBE

The CUBE operator returns the following information based on the cross-referenced groupings that are returned with the CUBE operator.

•	The quantity of each title that each publisher has sold for each author.

•	The quantity of all titles each publisher has sold for each author.

•	The quantity of all titles each publisher has sold.

•	The total quantity of all titles sold by all publishers for all authors.

•	The quantity of each title sold by all publishers for each author.

•	The quantity of all titles sold by all publishers for each author.

•	The quantity of each title sold by each publisher for all authors.

•	The quantity of each title sold by all publishers for each author.

A pattern emerges as the number of relationships grows. The pattern of values and nulls in the report shows which groups have been formed for a summary aggregate. Explicit information about the groups is provided by the GROUPING function.

The GROUPING function can be used with the GROUPING function or with the CUBE operator. The GROUPING function is applied to a column_name in the select_list. The column_name must be one of the columns that appears in the GROUP BY clause. A value of 1 is returned when there is a (null) representing all values in the column; 0 is returned when the column contains a value. The 1 or 0 returned is a tinyint datatype.

D.	Use the GROUPING Function with the CUBE Operator

In this example, 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 that are listed after the GROUP BY clause.

SELECT pub_name, GROUPING(pub_name),title, GROUPING(title),

"qty" = SUM(qty)

FROM sales, titles, publishers
WHERE sales.title_id = titles.title_id
AND publishers.pub_id = titles.pub_id
GROUP BY pub_name, title
WITH CUBE

The results set has two columns containing 0 and 1 values, which are produced by the GROUPING(pub_name) and GROUPING(title) expressions. The value 1 appears when the column contains a (null). The GROUPING function returns a 1 when the values in that particular column have been grouped together by the CUBE operator.

This is the results 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
Binnet & Hardley       0 Onions, Leeks, and Garlic   0          40
Binnet & Hardley       0 Silicon Valley Gastronomi   0          10
Binnet & Hardley       0 Sushi, Anyone?              0          20
Binnet & Hardley       0 The Gourmet Microwave       0          40
Binnet & Hardley       0 (null)                      1         150
New Moon Books         0 Emotional Security: A New   0          25
New Moon Books         0 Is Anger the Enemy?         0         108
New Moon Books         0 Life Without Fear           0          25
New Moon Books         0 Prolonged Data Deprivatio   0          15
New Moon Books         0 You Can Combat Computer S   0          35
New Moon Books         0 (null)                      1         208
(null)                 1 (null)                      1         493
(null)                 1 But Is It User Friendly?    0          30
(null)                 1 Computer Phobic AND Non-P   0          20
(null)                 1 Cooking with Computers: S   0          25
(null)                 1 Emotional Security: A New   0          25
(null)                 1 Fifty Years in Buckingham   0          20
(null)                 1 Is Anger the Enemy?         0         108
(null)                 1 Life Without Fear           0          25
(null)                 1 Onions, Leeks, and Garlic   0          40
(null)                 1 Prolonged Data Deprivatio   0          15
(null)                 1 Secrets of Silicon Valley   0          50
(null)                 1 Silicon Valley Gastronomi   0          10
(null)                 1 Straight Talk About Compu   0          15
(null)                 1 Sushi, Anyone?              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)


Data Definition Language in Transactions
Data Definition Language in Transactions (version 6.5)

Data definition language (DDL) statements can appear within a user transaction. This allows the new CREATE SCHEMA statement to function. You can build a batch of schema-building statements and they will all be committed simultaneously. This eases the strict instruction order that was required by earlier releases.

The following statements can appear in transactions:

ALTER TABLE	DROP PROCEDURE
CREATE DEFAULT	DROP RULE
CREATE INDEX	DROP TABLE
CREATE PROCEDURE	DROP TRIGGER
CREATE RULE	DROP VIEW
CREATE TABLE	GRANT
CREATE TRIGGER	REVOKE
CREATE VIEW	SELECT INTO
DROP DEFAULT	TRUNCATE TABLE
DROP INDEX
A database object (including a global temporary table) cannot be dropped while it is in use. If the object is in use and a drop is attempted, the transaction will be rolled back. The only exception to this is the implicit drop that is done to a global-temporary object when the creating connection disconnects.

The SELECT INTO statement is now supported within a transaction. This means that tables can be created by using SELECT INTO within a transaction. The data is removed and the table is dropped if the transaction is rolled back.

User transactions are not rolled back when a batch contains a syntax or compile-time error. A batch with this type of error will not execute. This situation can cause unexpected behavior if the BEGIN TRANSACTION statement was executed in a previous batch, because the transaction will be active even though the rest of the batch will not run.

If an uncommitted procedure or trigger is executed and causes a rollback, it will drop itself but continue executing the cached copy. This copy will be removed when the procedure or trigger completes execution.

The sp_bindrule, sp_unbindrule, sp_bindefault, and sp_unbindefault stored procedures can also be used within a transaction whether or not the rule or table has been modified within that transaction or within another transaction.

All resources (such as pages, extents, and locks) used by a transaction are freed only at the end of the transaction. For DDL statements on large tables, this can affect a significant number of pages.

Important  While implicit drops of temporary tables can occur successfully at any time, the resources for the temporary table (including locks on system tables in tempdb) are not freed until the end of the transaction.

Use caution when you create temporary tables inside a transaction. Until the transaction commits or rolls back, exclusive locks are held on several system tables in the tempdb database to ensure recovery. These locks are held even if the temporary tables are dropped, and they can block other users' attempts to create temporary tables or other objects in tempdb.

This caution also applies to stored procedures that create temporary tables. If the stored procedure is executed within a transaction, the locks are held on the system tables until the transaction completes, even though the temporary table is automatically dropped when the procedure completes execution.

When invoked inside a user transaction, SELECT INTO has the ACID transaction properties (atomicity, consistency, isolation, durability): either the transaction is completely committed or it is completely rolled back.

Examples

A.	Create a Table and Insert Values in One Transaction

This example creates and fills a table in a single transaction. The table is created and filled with data simultaneously. Either the table is not created and the transaction is rolled back, or the table is created, filled with data, and then committed.

BEGIN TRAN
CREATE TABLE pay_type_table (pay_id int, pay_type varchar(20))
INSERT pay_type_table (1, 'Cash')
INSERT pay_type_table (2, 'Check')
INSERT pay_type_table (3, 'Credit Card')
INSERT pay_type_table (4, 'Electronic Wire')
INSERT pay_type_table (5, 'Banker Draft')
COMMIT TRAN

B.	Demonstrate Exclusive Locks on a Temporary Table in a Transaction

This example attempts a second session to access a newly created but uncommitted object; it results in the second session waiting until the creating transaction is complete. If the first transaction results in the object being removed and also creates another object by the same name and the waiting session is attempting to open the object by name, the waiting session will open the second (and newest) object.

This table illustrates the relationship between the two connections.

User One	User Two
BEGIN TRAN CREATE TABLE test (c1 int) INSERT test VALUES (1) go
	SELECT * FROM test
DROP TABLE test go CREATE TABLE test (c1 int, c2 int) INSERT test VALUES (1,2) go COMMIT TRAN
	Results Set c1    c ------------ 1     2 (1 row(s) affected)
C.	Use SELECT INTO Within a Transaction

Before running this example, sp_dboption select into\bulk copy must be set to TRUE.

The SELECT INTO statement creates a new table called authors2, into which the records in the authors table are copied. After the transaction is rolled back the authors2 table has been dropped and the final SELECT statement causes an error.

GO

BEGIN TRANSACTION

SELECT * INTO authors2 FROM authors

SELECT * FROM authors2

ROLLBACK TRANSACTION

SELECT * FROM authors2

GO


Disabling Constraints
Disabling Constraints (version 6.5)

You can disable constraints by using:

•	SET DISABLE_DEF_CNST_CHK option

Disables deferred constraint checking for the session. Constraints that have been disabled by using the NOCHECK option or NOT FOR REPLICATION option are checked individually.

•	NOCHECK option in ALTER TABLE statement

Temporarily disables constraint checking for a foreign key or a check constraint. The constraint is disabled and can be re-enabled rather than re-created.

•	NOT FOR REPLICATION in ALTER TABLE or CREATE TABLE statements

Disables foreign key constraint checks on data inserted by distribution during replication.

Disabling constraints can improve performance and streamline replication processes. For example, when rebuilding or replicating databases at a remote site there is no need to repeat constraint checks because the integrity of the data was checked when it was entered into the original database.

For more information about disabling constraints, see SET Statement, ALTER TABLE Statement, and CREATE TABLE Statement.


Distributed Transactions
Distributed Transactions (version 6.5)

Distributed transactions are transactions that update data on two or more network-connected computer systems and are available as part of Microsoft Distributed Transaction Coordinator (MS DTC). Distributed transactions provide an interface to applications that update distributed data. MS DTC provides this by employing the "ACID" properties: atomicity, consistency, isolation, and durability.

Atomicity provides an all or nothing property to a transaction. At any point before the transaction is committed, either the application or the system can terminate the transaction. If the transaction is terminated, the system ensures that all effects of the transaction are undone. If the transaction is committed, the system ensures that all targets of the transaction are committed.

Consistency is preserved if a transaction transforms the data from one correct state to another. The application programmer can write procedures that ensures that the work done within a transaction preserves consistency.

Isolation prevents concurrent updates from interfering with one another. Generally, data read for a transaction cannot be updated by other concurrent transactions. Also, data written by a transaction cannot be read or updated by other concurrent transactions until the transaction is committed.

Durability ensures that committed transactions remain permanent even in the event of hardware, software, or network failures.

Distributed transactions are an essential tool for building robust, scalable, distributed applications. Distributed applications are vulnerable to hardware, software, and network failure. In the absence of distributed transactions, the application must detect and recover from these failures. Distributed transactions, however, permit distributed data to be updated while providing simple failure recovery semantics to the application.

For example, consider an order-entry system for compact discs. When an order is placed at headquarters, it is entered into the local (headquarter) database. The order details are transmitted to the database at the warehouse where the compact disc distribution actually occurs. All orders committed locally must have a parallel order committed remotely at the warehouse. Distributed transactions ensure that the order transaction is committed or rolled back in both databases. To ensure consistency in the headquarters database and the warehouse database, the server-to-server procedure calls will be in a single atomic transaction.

To participate in a transaction that is distributed by MS DTC in an MS DTC distributed transaction, the server must be instructed to participate in a distributed transaction and to inform MS DTC of that participation. SQL Server's participation in an MS DTC transaction can be started by any of the following:

•	By a client application calling API functions from a DB-Library or an ODBC program.

•	By using the BEGIN DISTRIBUTED TRANSACTION statement. This statement begins a new MS DTC transaction.

•	By enabling the remote REMOTE_PROC_TRANSACTIONS option in the SET statement. For more information, see Set Statement.

Important  Connected servers need a time-out period to shut down an inactive connection. Otherwise, the servers remain connected until the originating user's session is terminated.

To set a time-out period before you begin a transaction, use the sp_configure stored procedure with the 'remote conn timeout' option.

A BEGIN DISTRIBUTED TRANSACTION affects subsequent Transact-SQL statements.

These are the statements that are affected by MS DTC.

Statement	Description
BEGIN TRANSACTION	The statements included between BEGIN DISTRIBUTED TRANSACTION and COMMIT TRANSACTION can include nested pairs of BEGIN TRANSACTION and COMMIT TRANSACTION statements. The transactions are not committed until the outermost transaction is committed. The nesting level of transactions is stored in the @@TRANCOUNT global variable. Each call to BEGIN TRANSACTION increases the outstanding transaction count by one.
BEGIN DISTRIBUTED TRANSACTION	BEGIN DISTRIBUTED TRANSACTION statements cannot be nested. SQL Server will detect such calls, reject them, and report an error.
COMMIT TRANSACTION	If the outstanding transaction count is one and this SQL Server session initiated the distributed transaction, then SQL Server calls MS DTC and commits the distributed transaction. Each call to COMMIT TRANSACTION decreases the outstanding transaction count by one.
PREPARE TRANSACTION	The PREPARE TRANSACTION statement is not permitted in a distributed transaction and will return an error.
ROLLBACK TRANSACTION	A distributed transaction can be rolled back when the ROLLBACK TRANSACTION statement is executed before the COMMIT TRANSACTION. MS DTC aborts the entire distributed transaction when the outstanding transaction count is one.
SAVE TRANSACTION	MS DTC does not support distributed savepoints. If an MS DTC transaction is aborted or rolled back, the entire transaction is rolled back to the beginning of the distributed transaction, regardless of any savepoints.
Any user involved in a distributed transaction can roll back the transaction. However, only the user who started the transaction can commit the transaction.

For more information about distributed transactions, see the Guide to Microsoft Distributed Transaction Coordinator.

Example

This example updates the author's last name on the local and remote databases. Both the local and remote databases will either commit or roll back the transaction.

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


float Datatype
float Datatype (version 6.5)

The precision of the float datatype uses less storage space for different ranges of precision. For example, consider the following declaration of float (n):

Declare @mf float(n)

These are the ranges of precision values permitted.

Where n =	Version 6.0 and earlier	Version 6.5
1-7	real, 4 bytes	real, 4 bytes
8-15	float, 8 bytes	real, 4 bytes
16-23	float, 8 bytes	real, 4 bytes
24-53	float, 8 bytes	float, 8 bytes


Insert Row-level Locking (IRL)

By default, the locking granularity in Microsoft SQL Server is a page, which can contain several rows. In SQL Server 6.5, the lock manager has been enhanced to provide row-level locking (IRL) for most INSERT operations. IRL improves performance in situations where access contention and hotspots, which are areas of unusually high access, occur.

While row-level locking is not a substitute for a well-designed application, there are specific scenarios where it is especially useful. Row-level locking is useful when a hotspot develops on tables structured as a sequential file. With SQL Server, hotspots can occur when records are inserted at the end of a table and one of the following conditions exists:

•	A table does not have an index.

•	A table has a nonclustered index.

•	A table has a clustered index with a monotonically increasing key (for example, a clustered index on an identity column).

When concurrent users try to insert data into the table's last page and contend for exclusive page access, a hotspot results. To alleviate these performance bottlenecks, enhancements to the lock manager in SQL Server 6.5 provide row-level concurrency for INSERT operations. Properly implemented IRL increases the speed of multiuser INSERT operations. The IRL operations occur in all data pages and in all levels of an index.

Note  If a clustered index exists on a table, it must be a unique clustered index to take advantage of IRL. (Typically, a unique clustered index is created by default on the column or columns that form the primary key when the primary key is defined.)

For more information about enabling IRL, see sp_tableoption, later in this document.

Two new lock modes provide increased concurrency for IRL.

Lock mode	Description
Insert_page	Multiple transactions can obtain an Insert_page lock on a page while concurrently inserting data. An Insert_page lock is compatible only with other Insert_page locks and is held until the transaction completes.
Link_page	A Link_page lock is obtained by the first transaction that detects that the current page is full and that a new page needs to be allocated and linked to the current page. The transaction's Insert_page lock is upgraded to a Link_page lock. Subsequent requests for Insert_page locks are blocked until the transaction owning the Link_page lock completes.
The following table describes the compatibility of the new types of locks. "Y" means that the requested lock is compatible with the granted lock. "N" means that the requested lock is not compatible with the granted lock.

IRL is OFF by default. IRL can be enabled on individual tables or on an entire database by using the sp_tableoption stored procedure. The following example shows how the database owner can turn on the insert row lock option for all tables in the current database:

EXECUTE sp_tableoption '%.%', 'insert row lock', 'true'

Note  The new value for insert row lock takes immediate effect on existing tables in the current database. For each table subsequently created, IRL must be explicitly set.

This example shows how a user other than the system administrator or database owner can turn off the insert row lock option for the sales table:

EXECUTE sp_tableoption 'sales', 'insert row lock', 'false'

For more information about enabling table options, see sp_tableoption, later in this document.

For recovery purposes, additional information must be logged into the transaction log each time a transaction that uses the IRL concurrency option rolls back. This additional information consists of compensating log records, which are used during recovery to bring the database back to a consistent state. To account for a potential rollback operation, SQL Server reserves enough space in the transaction log for all concurrent IRL operations.

Important  If you intend to use IRL, and your application performs many concurrent INSERT operations, you should monitor the size of the log using the Windows NT Performance Monitor. Increase the size of the log space or dump the transaction log more frequently if your database is running low.

Reducing the locking granularity can result in deadlocks in some applications. It is possible for existing applications to encounter deadlocks if IRL is implemented without adequate testing. For example, consider a transaction that inserts a row on a page and then updates the row within the same transaction. For the INSERT operation, the transaction must acquire an Insert_page lock, and for the subsequent UPDATE operation, it needs an exclusive page lock. If there are several such transactions running concurrently, each transaction can have its own Insert_page lock on the page. When attempting to update the page, each transaction requests an exclusive page lock, which blocks on the Insert_page lock of another transaction and results in a deadlock. To achieve maximum benefit from IRL and to avoid deadlocks, it is recommended that you extensively test existing applications before changing to this new locking level.


Joins
Joins (version 6.5)

ANSI-standard join clauses are supported and include:

•	JOIN

•	CROSS JOIN

•	INNER JOIN

•	LEFT OUTER JOIN

•	RIGHT OUTER JOIN

•	FULL OUTER JOIN

Earlier versions of SQL Server joins continue to be supported although they will be discontinued in a future release.

For more information about implementing joins, SELECT Statement.


Replication of text and image Datatypes
Replication of text and image Datatypes (version 6.5)

For a published replication article, text and image columns are now replicated as text or image datatypes.

The synchronization process initializes NULL pointers in tables loaded by BCP by default. The process first obtains the names of nullable text and image columns and subsequently issues an UPDATE statement to initialize all columns with uninitialized pointers. The statement is issued repeatedly for columns with ROWCOUNT set to 1000.

Potentially, the synchronization process can cause a large number of records to be written to the transaction log of the subscriber database. To switch off the initialization of NULL pointers for text and image coumns, do one of the following:

•	Use automatic transaction log backups provided in Windows NT Performance Monitor. See the Microsoft SQL Server Administrator's Companion for more information.

•	Reduce the number of NULL text and image datatype columns in the published table.

•	Add the -N switch to the distribution process and ensure that applications modifying text or image columns in the published table initialize pointers using some value other than NULL in the UPDATE statement.


ROLLUP Operator
ROLLUP Operator (version 6.5)

The ROLLUP operator is an aggregate operator that delivers aggregates and super-aggregates for elements within a GROUP BY statement. The ROLLUP operator is applicable to cumulative aggregates such as running sums or running averages. It differs from the CUBE operator only in that it is sensitive to the column's position in the GROUP BY clause. Aggregate groupings are made up of columns to the right of the current column value.

The ROLLUP operator can be used by report writers to extract statistics and summary information from results sets. The cumulative aggregates, such as running sums, can be used in reports, charts, and graphs.

The ROLLUP operator creates groupings by moving in only one direction, from right to left, along the list of columns in the GROUP BY clause. It then applies the aggregate function to these groupings. The CUBE operator creates all combinations of groupings from the list of columns in the GROUP BY clause.

Example

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.

SELECT pub_name, au_lname, title, "SUM" = SUM(qty)

FROM publishers, authors, titles, titleauthor, sales
WHERE publishers.pub_id = titles.pub_id
AND authors.au_id = titleauthor.au_id
AND titleauthor.title_id = titles.title_id
AND titles.title_id = sales.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)

The (null) value 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 results set. Where you see (null) in the results set, it 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:

•	The quantity of each title that each publisher has sold for each author.

•	The quantity of all titles each publisher has sold for each author.

•	The quantity of all titles each publisher has sold.

•	The total quantity of all titles sold by all publishers for all authors.

This is the results set returned by the SELECT query:

pub_name          au_lname     title                                SUM

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

Algodata Infosys  Bendit       The Busy Executive's Database Guide  15

Algodata Infosys  Bendit       (null)                               15

Algodata Infosys  Carson       (null)                               30

Algodata Infosys  Dull         Secrets of Silicon Valley            50

Algodata Infosys  Dull         (null)                               50

Algodata Infosys  Green        The Busy Executive's Database Guide  15

Algodata Infosys  Green        (null)                               15

Algodata Infosys  Hunter       Secrets of Silicon Valley            50

Algodata Infosys  Hunter       (null)                               50

Algodata Infosys  MacFeather   Cooking with Computers: Surre        25

Algodata Infosys  MacFeather   (null)                               25

Algodata Infosys  O'Leary      Cooking with Computers: Surre        25

Algodata Infosys  O'Leary      (null)                               25

Algodata Infosys  Straight     Straight Talk About Computers        15

Algodata Infosys  Straight     (null)                               15

Algodata Infosys  (null)       (null)                              225

Binnet & Hardley  Blotchet-Hal Fifty Years in Buckingham Palace Ki  20

Binnet & Hardley  Blotchet-Hal (null)                               20

Binnet & Hardley  DeFrance     The Gourmet Microwave                40

Binnet & Hardley  DeFrance     (null)                               40

Binnet & Hardley  del Castillo Silicon Valley Gastronomic Treats    10

Binnet & Hardley  del Castillo (null)                               10

Binnet & Hardley  Gringlesby   Sushi, Anyone?                       20

Binnet & Hardley  Gringlesby   (null)                               20

Binnet & Hardley  Karsen       Computer Phobic AND Non-Phobic Indiv 20

Binnet & Hardley  Karsen       (null)                               20

Binnet & Hardley  MacFeather   Computer Phobic AND Non-Phobic Indiv 20

Binnet & Hardley  MacFeather   (null)                               20

Binnet & Hardley  O'Leary      Sushi, Anyone?                       20

Binnet & Hardley  O'Leary      (null)                               20

Binnet & Hardley  Panteley     Onions, Leeks, and Garlic: Cooking   40

Binnet & Hardley  Panteley     (null)                               40

Binnet & Hardley  Ringer       The Gourmet Microwave                40

Binnet & Hardley  Ringer       (null)                               40

Binnet & Hardley  Yokomoto     Sushi, Anyone?                       20

Binnet & Hardley  Yokomoto     (null)                               20

Binnet & Hardley  (null)       (null)                              250

New Moon Books    Green        You Can Combat Computer Stress!      35

New Moon Books    Green        (null)                               35

New Moon Books    Locksley     Emotional Security: A New Algorithm  25

New Moon Books    Locksley     (null)                               25

New Moon Books    Ringer       Is Anger the Enemy?                 216

New Moon Books    Ringer       Life Without Fear                    25

New Moon Books    Ringer       (null)                              241

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)

For more information about the ROLLUP operator, see SELECT Statement.

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 and it returns either 1 or 0 depending upon whether the column is grouped by the ROLLUP operator. For more information about the GROUPING function, see SELECT Statement or CUBE Operator.


text Datatype
text Datatype (version 6.5)

Literal strings longer than 255 bytes are automatically converted to the text datatype. This may require stricter datatype checking in applications because a char or varchar variable cannot be directly compared to a text variable. In earlier releases of SQL Server, literal strings longer than 255 bytes were truncated and treated as a varchar datatype.


Trace Flags
Trace Flags (version 6.5)

Trace flags are used to temporarily set specific server characteristics. For example, if you set the trace flag 8501 when you start SQL Server, detailed information is logged about MS DTC transactions.

Trace flags are generally used to switch off a particular behavior. SQL Server 6.5 introduces many new features, some of which can be switched off by using a trace flag. Often trace flags are used to diagnose performance issues and to debug stored procedures or complex systems.

This is how to start a trace flag by using the DBCC command:

DBCC TRACEON (8501)

These flags are new or enhanced in SQL Server 6.5.

Flag	Description
110	Disables ANSI SELECT characteristics. For more information, see SELECT Statement.
204	Supports queries that contain sort columns in the ORDER BY clause that are not in the select list when the DISTINCT keyword is supplied. For more information, see the Microsoft SQL Server Transact-SQL Reference.
237	Disables the requirement for REFERENCES permission to create a foreign key on a table that is not owned by the key creator, and when disabled ensures ANSI-standard behavior. When enabled, this flag needs only SELECT permission and SQL Server 6.0 behavior is ensured.
246	Disables error reporting when no column name is given to a column created by a SELECT INTO or a CREATE VIEW statement.
330	Enables full output when using the SET SHOWPLAN option, which gives detailed information about joins.
506	Enforces ANSI standards regarding null values for comparisons between variables and/or parameters. Any comparison of variables and/or parameters that contain a NULL will always result in a NULL. This flag is disabled if ANSI_NULLS is enabled (set to True).
1081	Sets a flag in index pages that prevents index pages from being removed from the cache the first time the cache tries to remove them to make space for new data. Unless the index page is reused and the flag is reset, the index page is received next time the cache requires space for new data pages. This flag extends the life of the index page within the cache. Use this flag on databases where performance gained by retaining the index pages in the cache outweighs the performance lost by the increase in data page I/O.
2701	Sets the global variable @@ERROR to 50000 for RAISERROR messages with severity levels of 10 and under. When disabled, sets the global variable @@ERROR to 0 for RAISERROR messages with severity levels of 10 and under.
3002	Backups will have SQL Server 6.0 DUMP format. To use this option the database must be running in stand-alone mode by setting the database option "DBO UseOnly" to TRUE.
4022	In SQL Server 6.5, bypasses automatically started procedures.
7501	In SQL Server 6.5, dynamic cursors are used by default on forward-only cursors. Dynamic cursors are faster in version 6.5 and no longer require unique indexes. This flag disables the dynamic cursor enhancements and reverts to version 6.0 behavior.
7502	Disables the caching of cursor plans for extended stored procedures.
8501	Performs detailed logging that describes all MS DTC−related context and state changes.
Trace flags are set when SQL Server is started at the command prompt. For more information about "sqlservr command-line executable," see the Microsoft SQL Server Transact-SQL Reference. This is how to start SQL Server with a trace flag at the command prompt:

sqlservr /dc:\mssql\data\master.dat /T8501


Utilities
Utilities (version 6.5)

SQL Server contains several utilities, such as isql and SQLMAINT, that are included for performing certain maintenance, administration, and debugging tasks.

isql is a command-line query tool that is used for MS-DOS®−based connectivity and batch processing.

SQLMAINT is a command-line utility that is used to run automated consistency checks and backups. For example, it can create status reports and send them to an e-mail account.


isql Options
isql Options (version 6.5)

isql /b

The /b option specifies that isql exits and returns a DOS ERRORLEVEL value when an error occurs. The value returned to the DOS ERRORLEVEL variable is 1 when the SQL Server error message has a severity of 10 or greater, otherwise the value returned is 0. DOS batch files can test the value of DOS ERRORLEVEL and handle the error appropriately.

isql /O

The /O option specifies that the behavior of earlier versions of isql is required and disables the following:

•	EOF batch processing

•	Auto console width scaling

•	Wide messages

•	Default DOS ERRORLEVEL value is −1

isql /l timeout

The /l option specifies the number of seconds before an isql login times out. If no timeout is specified, a command runs indefinitely; the default timeout for login to isql is eight seconds.


ISQLPASSWORD
ISQLPASSWORD (version 6.5)

The isql ISQLPASSWORD environment variable allows you to set a default password for the current session. Therefore, you do not have to hard code a password into batch files.

If you do not specify a password with the /P qualifier, isql first checks for the ISQLPASSWORD variable. If no value is set, isql uses the default password, NULL. The following example sets the ISQLPASSWORD variable at the command prompt and then accesses the isql utility:

C:\>SET ISQLPASSWORD=abracadabra

C:\> isql


PRINTDMP.EXE Command-prompt Utility

The PRINTDMP.EXE command-prompt utility provides formatted output of stack traces for specific debugging purposes. Use this only when instructed to do so by your Primary Support Provider.


SQLMAINT.EXE Command-prompt Utility
SQLMAINT.EXE Command-prompt Utility (version 6.5)

The SQLMAINT.EXE command-prompt utility performs routine database maintenance. Use SQLMAINT.EXE to run DBCC checks, to dump a database and its transaction log, to update statistics, and to rebuild indexes. All database maintenance activities generate a report that can be sent to a designated e-mail account.

Syntax

SQLMAINT
 [-?] | [-S server_name]
[-U login_ID [-P password]]
-D database_name
-Rpt output_file
[-To operator_name]
[-CkDB | -CkDBNoIdx]
[-CkAl | -CkAlNoIdx]
[-CkTxtAl]
[-CkCat]
[-UpdSts]
[-RebldIdx free_space]
[-BkUpDB backup_path | -BkUpLog backup_path]
[-BkUpOnlyIfClean]
[-BkUpMedia {DISK [-DelBkUps number_of_weeks] | TAPE}]

where

-?

Specifies that the syntax diagram for SQLMAINT.EXE utility be returned. This parameter must be used alone.

-D database_name

Specifies the target database name. This parameter is required if the -? parameter is not used.

-Rpt report_file

Specifies the full path and name of the file into which the report is to be generated. The report is also generated on the screen. This parameter is required if the -? parameter is not used. The report maintains version information by adding a date to the filename. The date is generated as follows: at the end of the filename but before the period, in the form _YYYYMMDD.

If you run the utility on Dec. 1, 1996 and this is the report_file value:

c:\mssql\backups\pubs_maint.rpt

Then it becomes:

c:\mssql\backups\pubs_maint_19961201.rpt

The full UNC filename is required for the -Rpt file when SQLMAINT.EXE accesses a remote server.

-S server

Specifies the target server. If this parameter is not supplied, SQL Server is assumed to be on the local machine. The SQL Server must be version 6.0 or later, though it is recommended that you run the utility on version 6.5. This parameter is optional.

-U login_ID

Specifies the login ID to use when connecting to the server. If this parameter is not supplied SQLMAINT.EXE will attempt to log in by using a trusted connection. This parameter is optional.

-P password

Specifies the password for the login ID. Only valid if the -U parameter is also supplied. This parameter is optional.

-To operator_name

Specifies the operator to whom the generated report will be sent through SQL Mail. The operator can be defined by using SQL Enterprise Manager. This parameter is optional.

-CkDB | -CkDBNoIdx

Specifies page checking against extent structures. The CkDB checks data and index pages against allocation units. CkDBNoIdx will check only the data pages against the extent structures.

Data storage is held in pages, 256 of which are grouped into one extent structure. At the beginning of each allocation unit, a page is dedicated to keeping track of the pages within the extent. Also, the pages are linked by pointers stored on the pages. This check tests to see that the pages linked by pointers match the pages listed on the first page in the extent structure.

A warning is written to an output file if the database is in use when SQLMAINT.EXE runs. This parameter is optional.

These parameters are equivalent to DBCC NEWALLOC and DBCC NEWALLOC with the NOINDEX option. For more information, see the DBCC statement.

-CkAI | -CkAlNoIdx

Is to check the allocation of text and image columns in the database and generates a report of allocation errors. This parameter is optional.

-CkCat

Is to check for consistency of the system tables and generates a report of all consistency errors. This parameter is optional.

-UpdSts

Is to update statistics about the distribution of key values in specified indexes for all tables in the target database. This parameter is optional.

-Rebldldx free_space

Specifies that indexes on tables in the target database should be rebuilt by using the Free Space percent value as the inverse of the fillfactor. For example, if Free Space percentage is 30 then the fillfactor used is 70. If the Free Space percentage value of 100 is specified, then the indexes are rebuilt with the original fillfactor value.

This parameter is optional and is available only with SQL Server version 6.5.

-BkUpDB backup_path | -BkUpLog backup_path

Specifies a backup action. BkUpDb backs up the entire database. BkUpLog backs up only the transaction log.

The backup_path specifies the directory for the backup. The backup can be placed in a directory or a tape device address (For example, \\.\TAPE0). The filename for a database backup is automatically generated as follows:

dbname_db_dump.yyyymmdd

The filename for a transaction backup is automatically generated as follows:

dbname_log_dump.yyyymmdd

If you use the -BkUpDB parameter you must also specify the media using the -BkUpMedia parameter.

-BkUpMedia {TAPE | DISK [DelBkUps num_weeks]}

Specifies the media type of the backup as either TAPE or DISK.

-DelBkUps number_of_weeks

Specifies the number of weeks to retain disk backup files. Backup files older than the specified number of weeks are deleted. This parameter can be used only if -BkUpType DISK is also specified.

-BkUpOnlyIfClean

Specifies that the backup occurs only if any specified -CK checks did not find problems with the data. Maintenance actions run in the same sequence as they appear on the command line. Specify the parameters -CkDB, -CkDBNoIdx, -CkAL, -CkAlNoIDX, -CkTxtAL,  or -CkCat before the -BkUpDB/-BkUpLog parameter(s) if you are also going to specify -BkUpOnlyIfClean, or the backup will occur whether or not the check reports problems.

Remarks

SQLMAINT.EXE is a SQL-DMO application, which makes it necessary to register SQL-DMO on the machine where you intend to run SQLMAINT.EXE. If SQL Server or SQL Enterprise Manager are installed on the machine, SQL-DMO is already registered.

Type the following to register SQL-DMO at the command line:

regsvr32 c:\mssql\binn\sqlole65

SQLMAINT.EXE returns 0 if it runs successfully or 1 if it fails. Failure is reported:

•	If any of the maintenance actions fail.

•	If -CkDB, -CkDBNoIdx, -CkAL, -CkALNoIdx, -CkTxtAL, or -CkCat checks find problems with the data.

•	If a general failure is encountered.

For example, SQLMAINT.EXE returns 1 if SQL-DMO has not been registered.


Web Pages
Web Pages (version 6.5)

By using three new SQL Server stored procedures, you can generate HTML documents for web pages. Other than the information needed to use these stored procedures, no programming knowledge is required to create a web page. In addition, the SQL Server Web Assistant provides an interface for using the sp_makewebtask stored procedure.

For more information about creating web pages with the new SQL Server stored procedures, see sp_dropwebtask, sp_makewebtask, and sp_runwebtask, later in this document.

Important  The Web Assistant can be run only on Intel-based computer systems. The sp_dropwebtask, sp_makewebtask, and sp_runwebtask stored procedures can be run only on Microsoft SQL Server version 6.5 databases and on any supported platform. Running these procedures on earlier version databases will result in errors.

You can use the sp_dropwebtask, sp_makewebtask, and sp_runwebtask stored procedures to:

•	Create standard HTML pages from your SQL Server data.

•	Improve performance and scalability compared to CGI applications.

•	Generate HTML pages automatically through powerful scheduling options.

•	Generate trigger-based HTML pages.

These are example uses for generating dynamic web pages in SQL Server:

•	With your inventory information stored in a Microsoft SQL Server database, you can keep track of what items are in stock, what items are on order, and what items are on back order. By using these stored procedures, you can create a web page that displays current inventory levels. This web page can be updated every hour so customers can see your up-to-date inventory status.

•	An investments firm can use a Microsoft SQL Server database to store prices of stocks, mutual funds, and precious metals, and to store performance statistics associated with each investment. Current and potential customers can browse a web page that displays the weekly top ten recommended investments.

Before you use sp_dropwebtask, sp_makewebtask, and sp_runwebtask, consult your web browser or HTML documentation for more information.


Statements and Functions

ALTER TABLE Statement

APP_NAME Built-in Function

BEGIN DISTRIBUTED TRANSACTION Statement

CREATE INDEX Statement

CREATE SCHEMA Statement

CREATE TABLE Statement

DBCC DBREINDEX Statement

DBCC UPDATEUSAGE

DECLARE CURSOR Statement

DUMP Statement

EXECUTE Statement

FETCH Statement

GRANT Statement

INSERT Statement

ISDATE and ISNUMERIC Functions

LOAD Statement

RAISERROR Statement

REVOKE Statement

SELECT Statement

SET Statement

UPDATE Statement

User Function


ALTER TABLE Statement
ALTER TABLE Statement (version 6.5)

Disables a foreign key constraint and defers constraints during replication. Constraints can be deferred without being dropped.

For additional syntax information for the ALTER TABLE statement, see the Microsoft SQL Server Transact-SQL Reference.

Syntax

ALTER TABLE [database.[owner.]]table_name
[WITH {CHECK | NOCHECK}]
{{CHECK | NOCHECK} CONSTRAINT {constraint_name | ALL}
|
[ADD
{col_name column_properties [column_constraints]
| [[, ] table_constraint]}
[, {next_col_name | next_table_constraint}]...]
|
[DROP CONSTRAINT]
constraint_name [, constraint_name2]...]}

where

table_name

Specifies which table to alter. You can specify local or global temporary tables, but FOREIGN KEY constraints are not enforced on temporary tables.

WITH {CHECK | NOCHECK}

Allows CHECK and FOREIGN KEY constraints to be added to a table without verifying existing data for constraint violations.

{NOCHECK | CHECK} CONSTRAINT

Turns the constraint checking on or off for foreign key and check constraints.

constraint_name | ALL

Specifies an individual constraint or all constraints to modify.

You can defer constraints for the table, including CHECK and FOREIGN KEY constraints, by using the ALL keyword. However, you cannot defer primary and unique key constraints; these constraints must be dropped.

Important  Deferring constraints on a table does not defer constraints on other tables that refer to the altered tables. Updates to the table can still raise constraint violation errors.

ADD

Specifies that a column- or table-level constraint be added to an existing table.

col_name

Is a new column for the table. Column names must conform to the rules for identifiers and must be unique in the table.

column_properties =

datatype [NULL | IDENTITY[(seed, increment)]]

datatype

Specifies the datatype of the column. System or user-defined datatypes are acceptable. Columns added to a table must be defined as NULL.

IDENTITY(seed, increment)

Specifies values for existing rows based on the seed and increment parameters.

table_constraints=

Specifies up to one PRIMARY KEY constraint per table, one DEFAULT constraint per column, and any number of FOREIGN KEY, UNIQUE, or CHECK constraints on any column or columns. All can be entered within the same ALTER TABLE statement.

For a table-level constraint:

[CONSTRAINT constraint_name]
{ PRIMARY KEY [CLUSTERED | NONCLUSTERED]
(col_name [, col_name2[..., col_name16]])
| UNIQUE [CLUSTERED | NONCLUSTERED]
(col_name [, col_name2[..., col_name16]])
[WITH FILLFACTOR = fillfactor]
| FOREIGN KEY (col_name[, col_name2[..., col_name16]])
REFERENCES [owner.] ref_table (ref_col[, ref_col2[..., ref_col16]])
[NOT FOR REPLICATION]
| CHECK [NOT FOR REPLICATION] (expression)}

CONSTRAINT constraint_name

Specifies the constraint within the database. Constraint names must follow the rules for identifiers, except that the name cannot begin with a number sign (#). If this clause is omitted, a system-generated name is assigned to the constraint.

PRIMARY KEY | UNIQUE [CLUSTERED | NONCLUSTERED]

Specifies entity integrity for a given column or columns, which can be used as primary keys.

WITH FILLFACTOR

Specifies how full SQL Server makes each index page when creating an index with existing data.

SORTED_DATA | SORTED_DATA_REORG

Specify that the sort that is performed when a clustered index is created be eliminated. Both options verify that the data has been sorted by checking each index value to determine whether it is higher than the previous one. If any row fails this check, the ALTER TABLE statement terminates. You can either fix the data or rerun the ALTER TABLE statement without the SORTED_DATA option (the data will be sorted but not reorganized).

When the data satisfies the checks, the SORTED_DATA option will always be faster than the SORTED_DATA_REORG because the data is not copied and nonclustered indexes will not be rebuilt.

SORTED_DATA_REORG differs from SORTED_DATA because it physically reorganizes the data. This option is useful when a FILLFACTOR is specified to compact or expand the pages on which a table is stored. The effects of these options change slightly if used with the ON segment_name option.

Reorganizing the data is a good idea when a table becomes fragmented. To determine whether or not a table is contiguous, use the DBCC statement's SHOW_CONTIG. For details about what causes table fragmentation and recommended solutions, see the DBCC statement.

ON segment_name

Specifies the segment on which to create the index.

column_constraints=

Is up to one unique or foreign key constraint, one DEFAULT constraint, and any number of check constraints for each new or existing column.

For a column-level constraint:

[CONSTRAINT constraint_name]
{ PRIMARY KEY [CLUSTERED | NONCLUSTERED] [(col_name)]
| UNIQUE [CLUSTERED | NONCLUSTERED] [(col_name)]
[WITH FILLFACTOR = fillfactor]
| FOREIGN KEY [(col_name)]
REFERENCES [(ref_col)]
[NOT FOR REPLICATION]
| CHECK [NOT FOR REPLICATION] (expression)}

FOREIGN KEY [NOT FOR REPLICATION]

Specifies single column or multicolumn referential integrity. When defined, the number of columns and datatypes of each column specified in the FOREIGN KEY clause must identically match the columns in the REFERENCES clause. Values entered in this column or columns must exist in the table, and column(s) defined in the REFERENCES clause and the referenced table's columns must have a PRIMARY KEY or UNIQUE constraint defined on them. For column-level constraints, using the FOREIGN KEY and col_name identifiers are optional.

NOT FOR REPLICATION

Specifies that column-level constraints be suspended during replication.

Remarks

The ALTER TABLE NOCHECK statement allows replication to take place without permanently removing referential integrity constraints. Replication needs deferred constraints because constraints are sometimes violated by modifying a database with INSERT and DELETE statements. Use the ALTER TABLE statement to temporarily suspend constraints checking.

Two conditions cause an error to be returned: when ALL is specified and no constraints exist and when the specified constraint does not exist.

Once all data modifications are made, you can use the ALTER TABLE statement to reestablish constraint checking.

For more information about foreign keys or the ALTER TABLE statement, see the Microsoft SQL Server Transact-SQL Reference.

Examples

A.	Add a Constraint

This example reviews adding a constraint. The foreign key constraint pub_id is added to the titles table.

ALTER TABLE titles

ADD

CONSTRAINT FK_pub_id FOREIGN KEY (pub_id)

REFERENCES publishers(pub_id)

B.	Disable a Constraint

This example disables the ssn_constraint in the authors table.

ALTER TABLE authors
NOCHECK CONSTRAINT ssn_constraint

C.	Enable a Constraint

This example enables the ssn_constraint in the authors table.

ALTER TABLE authors
CHECK CONSTRAINT ssn_constraint

Permission

Only the system administrator, the database owner, and the table owner can use the ALTER TABLE statement.


APP_NAME Built-in Function
APP_NAME Built-in Function (version 6.5)

Returns the program name for the current session. This function is useful for tracking which client applications are running processes in SQL Server or to limit access to specific applications.

Syntax

APP_NAME()

Remarks

This built-in function returns the program name for the current session if one has been set by the program.

Note  The value returned must have a char or varchar datatype and can be a maximum length of 30 characters.

Example

This example checks that the client application that initiated this process is the correct one.

DECLARE @ThisApp varchar(35)

SELECT @ThisApp = APP_NAME()

IF @ThisApp <> 'Log3'

PRINT "This process was not started with the current
version of the Log program"


BEGIN DISTRIBUTED TRANSACTION Statement
BEGIN DISTRIBUTED TRANSACTION Statement (version 6.5)

Begins a distributed transaction.

Syntax

BEGIN DISTRIBUTED TRANsaction [transaction_name]

where

BEGIN DISTRIBUTED TRANSACTION

Specifies that a distributed transaction managed by Microsoft Distributed Transaction Coordinator (MS DTC) starts.

transaction_name

Specifies a user-defined transaction name is used to track the distributed transaction within MS DTC utilities.

Remarks

The BEGIN DISTRIBUTED TRANsaction statement is used instead of the BEGIN TRANsaction statement when a transaction is to be processed on one or more remote servers. The command alerts MS DTC to manage the transaction processing on the local and remote servers.

For example, suppose a company has several marketing departments in different physical locations. At each location a server is running a database. The company headquarter database records the company marketing budget and the amounts of money that subsidiary offices have to produce events and run their various departments. Each subsidiary's database allocates budget and costs. When the company's headquarters issues a check to the subsidiary, headquarters records the debit to its local database and also credits the database on the remote subsidiary's server. If the transaction fails, then the transaction must not be recorded on one server and not the other. The BEGIN DISTRIBUTED TRANsaction statement protects the transaction so that records of the budget cannot be lost between servers.

The BEGIN DISTRIBUTED TRANsaction statement requests that the MS DTC begin a new transaction and enlist the requester in that transaction.

The requester who issued the BEGIN DISTRIBUTED TRANsaction statement is the transaction originator, and a subsequent COMMIT TRANsaction statement causes the server to ask the MS DTC to start the commit sequence. The MS DTC transactions started by SQL Server cannot be exported to other servers because the client is not able to pass the transaction object from one server to another server.

To protect server-to-server remote procedure calls (RPCs) under MS DTC control without changing existing applications, a server configuration option is provided, remote proctrans in sp_configure, to implicitly create MS DTC transactions that cover server-to-server RPCs.

The session-level SET option, REMOTE_PROC_TRANSACTIONS,  overrides the server default established by sp_configure. With this option in effect, an MS DTC transaction is created to cover an RPC if an MS DTC transaction does not exist. The server that creates the MS DTC transaction becomes the originating site for the transaction. Provided any nested transactions have been committed, the COMMIT TRANsaction initiates an MS DTC coordinated commit.

For more information about the distributed transaction environment and process, see the Guide to Microsoft Distributed Transaction Coordinator.

Example

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.

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


CREATE INDEX Statement
CREATE INDEX Statement (version 6.5)

Creates an index on a given table. The CREATE INDEX statement either changes the physical ordering of the table or provides the optimizer with a logical ordering of the table to increase efficiency for queries. When you create an index for the primary key, use the table- and column-level Primary Key constraint provided with the CREATE TABLE or ALTER TABLE statements.

For additional syntax information for the CREATE INDEX statement, see the Microsoft SQL Server Transact-SQL Reference.

Syntax

CREATE [UNIQUE] [CLUSTERED | NONCLUSTERED] INDEX index_name
ON [[database.]owner.]table_name (column_name [, column_name]...)
[WITH
[PAD_INDEX, ]
[[,] FILLFACTOR = fillfactor]
[[,] IGNORE_DUP_KEY]
[[,] SORTED_DATA | SORTED_DATA_REORG]
[[,] IGNORE_DUP_ROW | ALLOW_DUP_ROW]]
[ON segment_name]

where

PAD_INDEX

Specifies that the FILLFACTOR setting should be applied to the index node pages as well as to the data pages in the index.

Note  The number of items on an index page is never less than two, regardless of how low the value of FILLFACTOR.

Remarks

Indexes are made up of pages that form a branching structure known as a B-tree. The starting page records ranges of values within the table. Each range on the starting page branches to another page that contains a more detailed range of values in the table. In turn, these index pages branch out to more layers, which increase the number of pages in the layer and narrow the range of data on each page.

The branching index pages are called node pages. The final layer in the branching structure is called the leaf layer. In a unique, non-clustered index, the ranges on each leaf layer page point to a specific row of data in the table. In a clustered index, the leaf layer is the data pages because the data is stored in the physical order specified in the index.

Setting FILLFACTOR to 100 in SQL Server version 6.5 has the same behavior as it does in SQL Server 6.0. Index node pages are filled completely and have no space for additional items.

Example

This example creates an index on the author's identification number in the authors table. Without the PAD_INDEX option, SQL Server version 6.5 creates leaf pages that are 10 percent full, but the node pages are filled almost completely. With PAD_INDEX the node 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.

CREATE INDEX au_id_ind
ON authors (au_id)
WITH PAD_INDEX, FILLFACTOR=10


CREATE SCHEMA Statement
CREATE SCHEMA Statement (version 6.5)

Creates a schema that can be thought of as a conceptual container object, which is the definition of the database without any data in it.

Syntax

CREATE SCHEMA
[AUTHORIZATION owner]
[schema_element [schema_element2[...schema_elementn]]]

where

AUTHORIZATION owner

Specifies the ID of the schema object owner. This identifier must begin with a letter and can have as many as 30 characters. Hyphens are not supported.

schema_element = {table_definition | view_definition | grant_statement}

table_definition = CREATE TABLE statement

Creates a table within this defined schema. For more information about the CREATE TABLE statement, see the Microsoft SQL Server Transact-SQL Reference.

view_definition = CREATE VIEW statement

Creates a view for this schema. For more information about the CREATE VIEW statement, see the Microsoft SQL Server Transact-SQL Reference.

grant_statement = GRANT statement

Grants permissions to a user or group of users. For more information, see GRANT statement later in this document.

Remarks

Often database developers find it useful to keep a script or procedure, which creates the database schema for creating a copy of the database for testing or installation. Database administrators can set up a database and use the CREATE SCHEMA statement to set up all of the objects and permissions in a single batch.

CREATE SCHEMA provides a way to create database objects such as tables and views and to grant privileges on the objects, all within a single batch. The created objects do not need to appear in logical order. For example, a GRANT statement can grant permission to an object before the object itself has been created.

In another example, a CREATE VIEW statement can appear before the CREATE TABLE statement is created as long as all necessary objects are in the same CREATE SCHEMA statement. Also, the CREATE TABLE statement can declare foreign keys to tables that have not yet been created. Because objects are created at the same time, it is possible to create two tables that have mutually dependent foreign keys.

This statement complies with ANSI SQL standards. There are other ways to achieve the same results (DDL in transaction or add foreign key after creating both tables), and there are no restrictions to the objects created with CREATE SCHEMA other than that they are created under the current database user. In SQL Server, using the owner qualifier on database objects or on a separate database is usually preferable to using the CREATE SCHEMA statement.

ANSI-standards require that an AUTHORIZATION owner be included in the CREATE SCHEMA statement. Because a user must be signed on under a particular username in order to issue statements,  the AUTHORIZATION owner is optional.

The tables and view can be specified in any order. For example, a view can appear before the table on which it is defined.

Note  Errors from other statements in the CREATE SCHEMA statement, such as REVOKE or ALTER TABLE, will be ignored and not return error messages.

Examples

A.	Grant Access to Objects Before Object Creation

This example shows permission 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 TABLE Statement
CREATE TABLE Statement (version 6.5)

Defers constraints during replication by using the NOT FOR REPLICATION clause. The current user must have REFERENCES permission to the table(s) to which any foreign key constraints refer.

For additional syntax information for the CREATE TABLE statement, see the Microsoft SQL Server Transact-SQL Reference.

Syntax

CREATE TABLE table_name
(
{col_name column_properties[constraint [constraint [...constraint]]]
| [[, ] constraint]}
[[, ] {next_col_name | next_constraint}
)
[ON segment_name]

where

table_name

Is the name of the new table.

col_name

Is the name of a column in the table.

column_properties

Specifies the datatype, null values, or identity values for the column.

Note  Using the IDENTITY column property implies a value of NOT NULL. Because IDENTITY requires that a column have a value, NOT NULL is superfluous.

constraint

Specifies a table-or column-level constraint. The NOT FOR REPLICATION clause suspends column-level, foreign key, and check constraints during replication.

The REFERENCES permission must be placed on tables where non-table owners must create foreign keys.

Note  Table-level default constraints are not supported within the CREATE TABLE statement.

Note  The datatypes of the primary key and the foreign must match exactly.

ON segment_name

If specified with a PRIMARY KEY or UNIQUE constraint, creates only the index on the named segment.

Remarks

REFERENCES permissions are not checked during data manipulation language (DML) operations.

For example, suppose table country_table already exists and you are creating table city_table with a FOREIGN KEY constraint to the country_table table. You must have REFERENCES permission to country_table in order to create the FOREIGN KEY constraint.

Users who need access only to city_table must only have SELECT permission to city_table; they do not need access to country_table.

For information about disabling the REFERENCES permission, see Trace Flags .

Example

This example defines a table with a foreign key constraint called p1_constraint that can be deferred during replication.

CREATE TABLE employee

(

emp_id	integer

CONSTRAINT p1_constraint PRIMARY KEY NONCLUSTERED,

fname 	CHAR(20) NOT NULL,

minitial	CHAR(1) NULL,

lname	VARCHAR(30) NOT NULL,

job_id 	SMALLINT NOT NULL

DEFAULT 1

REFERENCES jobs(job_id) NOT FOR REPLICATION

)

Permission

You must have REFERENCES permission to create a FOREIGN KEY constraint to a table you do not own.


DECLARE CURSOR Statement
DECLARE CURSOR Statement (version 6.5)

Allows individual row operations to be performed on a given results set. There are several cursor improvements in SQL Server 6.5:

•	Dynamic cursors allow updates on underlying tables without requiring a unique index on the table.

•	Forward-only cursors are significantly faster on large tables.

•	Cursors automatically close upon COMMIT when SET CURSOR_CLOSE_ON_COMMIT option is set to ON.

•	Forward-only cursors are dynamic by default, which allows faster cursor opening and also allows the results set to display updates made to the underlying tables.

•	The results sets from read-only dynamic cursors no longer use temporary tables in tempdb.

DECLARE CURSOR cannot be used on a table that was created in the same batch or stored procedure.

If you need to use these statements in the same batch or stored procedure, you must put the DECLARE CURSOR statement inside a dynamic EXECUTE. Using a dynamic EXECUTE enables the cursor to benefit from any indexes on the temporary table, which allows a sensitive scrollable cursor.

An exception to this is when the created table is a temporary table (indicated by a leading number sign (#)). You can create a temporary table and declare a cursor on it in the same batch or stored procedure. However, the cursor will not recognize any of the table's indexes. Scroll cursors and any cursor with an ORDER BY statement will be created as INSENSITIVE and READ ONLY. Forward-only cursors (those that do not require an interim work table) will be dynamic and can be updated.

Note  If the definition of the forward-only cursor contains interim work tables for outer joins or aggregate functions, then the forward-only cursor does not default to a dynamic cursor.

Example

This example illustrates the dynamic behavior of a forward-only cursor. There are two processes: User One declares and opens a cursor, then User Two makes a change to the underlying table, which affects the first row of the cursor. Finally, the update is displayed when User One fetches the first row.

These are the connections that illustrate the dynamic behavior of a forward-only cursor.

User One	User Two
DECLARE forwardcursor CURSOR FOR SELECT au_lname FROM authors OPEN forwardcursor
	UPDATE authors  SET au_lname = 'Whittacker' WHERE au_lname = 'White'
FETCH NEXT FROM forwardcursor
This is the results set for User One:

--------------------------------
au_lname
--------------------------------
Whittacker

(1 row(s) affected)


DBCC DBREINDEX Statement
DBCC DBREINDEX Statement (version 6.5)

Rebuilds one or more indexes for a table.

For additional syntax information for the DBCC statement, see the Microsoft SQL Server Transact-SQL Reference.

Syntax

DBCC DBREINDEX (['database.owner.table_name' [, index_name
[, fillfactor [, {SORTED_DATA | SORTED_DATA_REORG}]]]])
[WITH NOINFOMSGS]

where

database.owner.table_name

Specifies the table for which to rebuild the index. If you specify the database name or owner the entire name must be enclosed in single quotation marks. If only the table name is specified then the quotes are optional.

index_name

Specifies the name of the index to rebuild. Specifying ' ' or no index_name rebuilds all indexes.

fillfactor

Specifies how full each index page is to be created. If 0 (zero) is entered for this parameter then the original fillfactor is used.

SORTED_DATA | SORTED_DATA_REORG

Specify that the sort performed when a clustered index is created can be eliminated because the data is sorted. Both options verify that the data has been sorted by checking each index value to determine whether it is a higher value than the previous one.

If any row fails this check, the DBCC DBREINDEX statement terminates. You can either fix the data or rerun the DBCC DBREINDEX statement without the SORTED_DATA or SORTED_DATA_REORG options.

When the data satisfies the checks, the SORTED_DATA option will always be faster than the SORTED_DATA_REORG option because the data is not copied and nonclustered indexes are not rebuilt.

SORTED_DATA_REORG differs from SORTED_DATA because it physically reorganizes the data. This option is useful when a FILLFACTOR is specified to compact or expand the pages on which a table is stored. The effects of these options change slightly if used with the ON segment_name option.

Reorganizing the data is a good idea when a table becomes fragmented. To determine whether or not a table is fragmented, use the DBCC SHOWCONTIG statement.

Important  If you specify one of the optional parameters (ind_name, fillfactor, or SORTED_DATA), you must specify all the parameters preceding it in the parameter list.

WITH NO_INFOMSGS

Prevents the printing of informational messages (severity 1 through 10).

Remarks

The DBCC DBREINDEX statement rebuilds an index for a table or all indexes defined for a table. By allowing an index to be rebuilt dynamically, indexes that enforce PRIMARY KEY or UNIQUE constraints can be rebuilt without having to drop and re-create constraints. This means that an index can be rebuilt without having to know the table's structure or constraints. This could occur after a bulk copy of data into the table.

If the index is a clustered index, all nonclustered indexes will also be reindexed with the same supplied fillfactor. This statement is completely recoverable and atomic for all of the indexes being rebuilt.

The DBCC DBREINDEX statement is not supported for system tables.

Examples

A.	Rebuild an Index

This example rebuilds the au_nmind 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 a table by using the existing fillfactor values and physically reorganizes the data.

DBCC DBREINDEX (authors, '', 0, SORTED_DATA_REORG)

Permission

Only the system administrator, database owner, and table owner can use this statement.


DBCC PROCCACHE Statement

Used by SQL Performance Monitor to interrogate the procedure cache.

For additional syntax information for the DBCC command, see the Microsoft SQL Server Transact-SQL Reference.

Syntax

DBCC PROCCACHE

The following values are returned:

num proc buffs	The number of possible procedures that could be in cache.
num proc buffs used	The number of slots that have a procedure in them.
num proc buffs active	The number of slots that have a procedure in them and are executing.
proc cache size	The total size of the procedure cache.
proc cache used	The amount of procedure cache containing procedures.
proc cache active	The amount of procedure cache containing procedures that are executing.
Note  The size of the procedure cache can grow and shrink as other operations, such as cursors and the query parser, start.


DBCC ROWLOCK

Enables Insert Row Locking (IRL) operation on tables dynamically.

For additional syntax information for the DBCC command, see the Microsoft SQL Server Transact-SQL Reference.

Syntax

DBCC ROWLOCK (dbid, tableid, set)

where

dbid

Specifies a unique identifier for the database. This value is stored in the sysdatabases system table in the master database.

tableid

Specifies a unique identifier for the table within the database. This value is stored in the sysobjects table within each database.

set

Specifies to enable Insert Row Locking (IRL) when the value of set is 1 and to disable it when the value is 0.


DBCC UPDATEUSAGE Statement
DBCC UPDATEUSAGE Statement (version 6.5)

Reports and corrects inaccuracies in the counts contained in the sysindexes table and includes the new WITH COUNT_ROWS syntax.

For additional syntax information for the DBCC statement, see the Microsoft SQL Server Transact-SQL Reference.

Syntax

DBCC UPDATEUSAGE ({0 | database_name} [, table_name [, index_id]])
[WITH COUNT_ROWS]

where

UPDATEUSAGE ({0 | database_name} [, table_name [, index_id]])

Reports and corrects inaccuracies in the sysindexes table that can result in incorrect space usage reports by the sp_spaceused system stored procedure.

This statement corrects the used, reserved, and dpages columns of the sysindexes table for any clustered indexes on objects of the type U (user-defined table) or S (system table). Size information is not maintained for nonclustered indexes. You can use this statement to synchronize space usage counters in sysindexes, which will result in accurate usage information being returned. When you use 0 instead of the database_name, the update is performed in the current database.

When processing, UPDATEUSAGE acquires a shared table lock on the table being processed, so updates to the sysindexes row for syslogs can be performed only if the database is in single-user mode and the syslogs table is specified. This prevents any logging during the update and ensures accurate changes. All other changes to sysindexes are fully logged.

Note  The stored procedure sp_spaceused used with the @updateusage qualifier provides the same functionality as DBCC UPDATEUSAGE. The sp_spaceused stored procedure takes longer to execute. Using this option on large tables may take longer to complete because every row in the table is counted.

WITH COUNT_ROWS

Specifies that the rows column of sysindexes is updated with the current count of the number of rows in the table. This only applies to sysindexes rows that have an index_id of 0 or 1. This option can affect performance on large tables.

Remarks

When the DBCC UPDATEUSAGE statement is executed with the WITH_COUNT_ROWS clause, inaccuracies are reported and corrected in the counts contained in the sysindexes table. The counts for rows, used, reserved, and dpages columns of the sysindexes table for any clustered indexes on objects of the type U (user-defined) or S (system table) are updated.

If there are inaccuracies in sysindexes, DBCC UPDATEUSAGE returns data that shows what rows and columns are being updated in sysindexes. Otherwise, no data is returned.

Example

This example corrects all of the page and row counts in the sysindexes table for all the indexes on the authors table.

DBCC UPDATEUSAGE (pubs, authors) WITH COUNT_ROWS


DISK INIT Statement

SQL Server 6.5 supports the use of raw partitions for creating devices with the DISK INIT statement. Raw partitions are disk partitions that have not been formatted with a Windows NT file system, such as FAT and NTFS. In some cases, using devices created on raw partitions can yield a slight performance gain over NTFS or FAT. However, for most installations the preferred method is to use devices on NTFS or FAT partitions.

Syntax

DISK INIT
NAME = 'logical_name',
PHYSNAME = 'physical_name',
VDEVNO = virtual_device_number,
SIZE = number_of_2K_block
[, VSTART = virtual_address]

where

NAME

Is the logical name of the database device.

PHYSNAME

Is the drive letter, path, and filename of the database device. To create a device on a raw partition, use only the partition drive letter for the physname parameter in the DISK INIT statement.

VDEVNO

Is the virtual device number.

SIZE

Specifies the size of the database in 2K blocks.

VSTART

Is the starting virtual address.

Example

This example creates a 200 MB device named Inventory_Dev on the raw partition corresponding to the G: drive.

DISK INIT

NAME = 'Inventory_Dev',

PHYSNAME = 'G:',

VDEVNO = 16,

SIZE = 102400

Remarks

There are several limitations to consider when using raw partitions:

•	Only one device can be created on each raw partition. The logical partition must be configured as a single device, because there is no file system on the raw partition.

•	Normal file system operations such as copy, move, and delete cannot be used with raw partitions.

•	Devices located on raw partitions cannot be backed up using the Windows NT Backup utility; however, databases or transaction logs stored on raw partitions can still be backed up using the Transact-SQL DUMP statement or through SQL Enterprise Manager.

•	File system services such as bad block replacement are not available with raw partitions.


DUMP Statement
DUMP Statement (version 6.5)

Allows an individual table to be backed up.

For additional syntax information for the DUMP statement, see the Microsoft SQL Server Transact-SQL Reference.

Syntax

Dumping a table:

DUMP TABLE [[database.]owner.]table_name
TO dump_device [, dump_device2 [..., dump_device32]]
[WITH options]

where

dump_device =

{dump_device_name | @dump_device_namevar}
| {DISK | TAPE | FLOPPY | PIPE} =
{'temp_dump_device' | @temp_dump_device_var}
[VOLUME = {volid | @volid_var}]

options =

[[, ] {UNLOAD | NOUNLOAD}]
[[, ] {INIT | NOINIT}]
[[, ] {SKIP | NOSKIP}]
[[, ] {EXPIREDATE = {date | @date_var}
| RETAINDAYS = {days | @days_var}}]
[[, ] STATS [= percentage]]

TABLE

Specifies that a table is to be backed up.

database

Specifies the database that contains the table being dumped.

owner

Specifies the owner of the table to dump.

table_name

Specifies the table to dump.

STATS = percentage

Specifies the percentage of pages backed up in increments specified at the time of the dump. If the percentage is not specified, statistics are shown for each 10 percent of the dump. This option is supported for DUMP DATABASE and DUMP TABLE. If you do not specify the STATS option then no statistics are shown.

Remarks

This statement backs up a single database table. By backing up specific tables, you can conserve system resources, save time by backing up only tables that have changed, and target high-volume tables for regular backups.

When you anticipate loading individual tables, use DUMP TABLE. DUMP TABLE locks the table and provides an exact snapshot of the table data. When tables have FOREIGN KEY constraints, you can cause the database to be logically inconsistent if conflicting transactions have occurred since the time of the backup.

Important  If data manipulation transactions were occurring on the table when the dump was performed, the data in the table may be logically inconsistent because outstanding transactions would not be reapplied.

Load a full table from a database dump only in disaster recovery situations.

A striped dump is created when more than one dump device is specified. Dumping to multiple devices can improve the performance of the dump because pages can be written to multiple dump devices at the same time. For DISK and FLOPPY devices, you must load from the same number of devices as you dumped to . For TAPE and PIPE devices, you can load from fewer devices than were dumped to. For example, if a database is dumped to four tape drives, you can load from one tape drive. The tapes can be loaded in any order, and a message will prompt you to change tapes.

For compatibility, database dumps from SQL Server 6.0 can be loaded into SQL Server 6.5 when the same sort order is running on both SQL Servers. The dump must be a full database dump and must occur when there is no update activity in the database. For this reason, it is recommended that the dump occur when SQL Server is started in single-user or read-only mode. After the database is successfully loaded, the database is upgraded.

The trace flag 3002 causes a SQL Server 6.5 to dump databases that can be loaded into SQL Server 6.0, Service Pack 3. It is recommended that the SQL Server 6.5 database be started in single-user or read-only mode before making the dump. A SQL Server 6.5 master database cannot be restored to a SQL Server 6.0 server.

A disk backup uses WITH INIT. A tape backup uses WITH NOSKIP and WITH NOUNLOAD, but not WITH INIT.

For more information about the DUMP statement, see the Microsoft SQL Server Transact-SQL Reference.

Example

This example creates the disk_dev1 dump device and then dumps the employees table to the disk_dev1 disk.

EXECUTE sp_addumpdevice 'disk','disk_dev1','c:\MSsql\dumps\diskdev1.dmp'
DUMP TABLE employees TO disk_dev1 WITH STATS

Permission

SELECT permission is required to dump a table.


EXECUTE Statement
EXECUTE Statement (version 6.5)

Specifies the keyword DEFAULT in place of a parameter.

For additional syntax information for the EXECUTE statement, see the Microsoft SQL Server Transact-SQL Reference.

Syntax

EXECute procedure_name [parameter [, parameter2 [..., parameterN ]]]

where

procedure_name

Specifies the name of the procedure to call.

@parameter=

parameter_value
| @parameter_name = parameter_value
| @parameter_name = DEFAULT
| DEFAULT

@parameter_value

Is the value that is supplied to the procedure.

parameter_name

Is the name of the parameter.

DEFAULT

Supplies the default value of the parameter as defined in the procedure.

Remarks

The DEFAULT keyword allows you to generically specify that a parameter's default value be used.

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.

Example

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.

--- create the stored procedure ---

CREATE PROC proc_calculate_taxes (@p1 SMALLINT = 42, @p2 CHAR(1), @p3 VARCHAR(8) = 'CAR')

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


FETCH Statement
FETCH Statement (version 6.5)

Accepts variables and procedure parameters for the row number arguments to the ABSOLUTE and RELATIVE keywords.

For additional syntax information for the FETCH statement, see the Microsoft SQL Server Transact-SQL Reference.

Syntax

FETCH [[NEXT | PRIOR | FIRST | LAST
| ABSOLUTE {n | @nvar} | RELATIVE {n | @nvar}]
FROM] cursor_name
[INTO @variable_name1, @variable_name2, ...]

where

NEXT

Specifies that the first row of the results set is returned if this is the first fetch against the cursor; otherwise, it moves the cursor one row forward within the results set. NEXT is the primary method to move through the results set; it is also the default cursor fetch action.

PRIOR

Specifies that the previous row within the results set is returned.

FIRST

Specifies that the cursor is moved to the first row within the results set and returns the first row.

LAST

Specifies that the cursor is moved to the last row within the results set and returns the last row.

ABSOLUTE {n | @nvar}

Specifies that the nth row within the results set is returned. If n is a negative value, the returned row will be the nth row counting backward from the last row of the results set. Only the smallint, tinyint and int datatypes are supported for n.

RELATIVE {n | @nvar}

Specifies that the nth row after the currently fetched row is returned. If n is a negative value, the returned row will be the nth row counting backward from the relative position of the cursor. Only the smallint, tinyint and int datatypes are supported for n.

FROM cursor_name

Specifies the cursor from which the fetch should be made. Multiple cursors are allowed within any session provided that each has a unique name.

INTO @variable_name1, @variable_name2, ...

Specifies a variable in which to place data that is returned by a fetch. Each of the variable datatypes must match the datatype returned by the fetch. Errors occur when the datatypes are incompatible.

Remarks

This statement retrieves a specific row from the cursor. Variables can be used for row number arguments. For example, the FETCH ABSOLUTE statement can be used with a variable to find a particular row within the cursor. For example, the row this statement retrieves depends upon the value of the @row_num variable:

FETCH ABSOLUTE @row_num FROM customer_cursor

By using variables for row number argument names, the program can provide the value at run time. This is useful because the row number value can be dependent upon run-time data that is available only at run time. This offers greater flexibility for programming the FETCH statement.

Example

This example calculates the median number of personnel in the various departments of a specific company. The company name is specified in the procedure. To calculate the median number of employees in a specific department, follow these steps:

1.	For the company specified, order the departments by population into a department list.

2.	Determine if the number of departments is odd or even.

•	If the number of departments is even, the median value is derived from the two departments' population values that appear on either side of the middle of the department list. Add the two population values together and divide by two.

•	If the number of departments is odd, the median value is derived from the population value that appears in the middle of the company list.

For this example, assume that a database exists that holds all departments' populations for all companies in the Algodata Infosystems conglomerate.

/*Create procedure*/

CREATE PROCEDURE find_median_population @company varchar(25)

AS

DECLARE @num_departments int

DECLARE @value1 int

DECLARE @value2 int

DECLARE @middle int

/* Declare cursor on population table */

DECLARE population_cursor SCROLL CURSOR

FOR select population

FROM population_table

WHERE company = @company

ORDER BY population

OPEN population_cursor

SELECT @num_departments=@@cursor_rows

SELECT @middle=@num_departments /2

IF (@num_departments % 2)=0

BEGIN

FETCH ABSOLUTE @middle FROM population_cursor INTO @value1

FETCH NEXT FROM population_cursor INTO @value2

SELECT "Company population median for " + @company + " is: " + CONVERT(char(10), (@value1 + @value2) / 2)

END

ELSE

BEGIN

SELECT @middle = @middle + 1

FETCH ABSOLUTE @middle FROM population_cursor INTO @value1

SELECT "Company population median for " + @company + " is: " + 	CONVERT(char(10), @value1)

END

CLOSE population_cursor

DEALLOCATE population_cursor

The find_median_population stored procedure can be executed in these ways:

EXECUTE find_median_population 'New Moon Books'

EXECUTE find_median_population 'Five Lakes Publishing'

EXECUTE find_median_population 'Scootney Books'


GRANT Statement
GRANT Statement (version 6.5)

Provides ANSI-compliant syntax for column-level grants and the ability to confer grant permissions to others.

For additional syntax information for the GRANT statement, see the Microsoft SQL Server Transact-SQL Reference.

Syntax

To grant permission to access database objects:

GRANT {ALL [PRIVILEGES][column_list] | permission_list [column_list]}
ON {table_name [(column_list)]
 | view_name [(column_list)]
 | stored_procedure_name}
TO {PUBLIC | name_list }
[WITH GRANT OPTION]

To grant permission to execute specific SQL statements in the current database:

GRANT {ALL | statement_list}
TO { PUBLIC | name_list}

where

ALL

When used to grant permission to access database objects, specifies that all permissions possessed by the current user (grantor) will be granted to the grantee. When used to assign statement permissions, only the system administrator can use ALL, because only the system administrator can grant or revoke CREATE DATABASE permission.

permission_list

Is the list of permissions granted. When permissions are granted on a column, the permission list can include only SELECT, REFERENCES, and/or UPDATE.

When permissions are granted on a table or view, the permission list can include: SELECT, INSERT, DELETE, and/or UPDATE. Permissions on a table can also include REFERENCES. To grant REFERENCES permission, you must specify REFERENCES because it is not automatically included in the SELECT permission.

When permissions are granted on stored procedures, the permission list can include only EXECUTE.

table_name

Is a table in the current database. Only one table can be listed for each GRANT statement.

column_list

Is a list of columns names delimited by commas, to which the permissions apply. If columns are specified, only SELECT and UPDATE permissions can be granted.

view_name

Is a view in the current database. Only one view can be listed for each GRANT statement.

stored_procedure_name

Is the name of a stored procedure or extended stored procedure in the current database. Only one stored procedure can be listed for each GRANT statement.

PUBLIC

Is all users, including those who are members of a user-defined group.

name_list

Is a list of user names and/or group names delimited by commas. These names are stored in the sysusers table of the database.

WITH GRANT OPTION

Extends the ability to grant the specified permission or statement to the grantee.

Note  Users can neither grant the WITH GRANT OPTION permission to a group nor use it with statement permissions.

statement_list

Is a list of statements granted. The statement list can include: CREATE DATABASE, CREATE DEFAULT, CREATE PROCEDURE, CREATE RULE, CREATE TABLE, CREATE VIEW, DUMP DATABASE, and DUMP TRANSACTION.

Remarks

You can confer, along with a permission, the ability to confer that permission to another user. For example, suppose the owner of an object grants Bob INSERT permission and trusts Bob to determine who else in his work group should get INSERT permission. By using WITH GRANT OPTION, the owner of the object gives Bob permission to grant INSERT permission to others.

Granting a permission to a user who has already received the WITH GRANT OPTION permission through a group or public grant will be recorded in the sysprotects table. If the permission is revoked for the group, the user will still retain the permission.

Important  The WITH GRANT OPTION should be managed carefully. Security can be compromised when the option is used improperly.

Users may need SELECT permission in addition to UPDATE permission to update a column or view. SELECT permissions are required only when there are column names after SET or WHERE in the UPDATE statement.

For more information about the GRANT statement, see the Microsoft SQL Server Transact-SQL Reference.

For more information about the sysprotects table, see sysprotects System Table.

Examples

A.	Use New ANSI Syntax for Column-level GRANT

This example grants SELECT permissions on population_table and UPDATE permissions on the census_org column of the population_table to the admin_group.

Users in the admin_group can view the entire population_table and can change the values in the census_org column.

GRANT SELECT, UPDATE(census_org) ON population_table TO admin_group

B.	Use WITH GRANT OPTION

In this example, the object owner grants UPDATE permission to user zachary on the city_statistics table.

User zachary then gives SELECT permission to user matthew. Note that because user matthew does not have the WITH GRANT OPTION, he cannot confer this permission to anyone else.

GRANT SELECT ON city_statistics TO zachary WITH GRANT OPTION

GRANT ALL ON city_statistics TO matthew


INSERT Statement
INSERT Statement (version 6.5)

Populates a local table with results returned from a procedure and makes it easier to import data from remote systems to the local server.

For additional syntax information for the INSERT statement, see the Microsoft SQL Server Transact-SQL Reference.

Syntax

INSERT [INTO]
{table_name | view_name} [(column_list)]
EXECute { procedure_name | @procedure_name_var}
[[@parameter_name=] {value | @variable [OUTPUT] | DEFAULT}
[, [@parameter_name =] {value | @variable [OUTPUT] | DEFAULT}]...]

where

table_name

Is the existing table in the local database to populate.

column_list

Is a list of one or more columns in which to insert data. The columns can be listed in any order, but the incoming data must be in the same order as the listed columns. The column_list must be enclosed in parentheses and delimited by commas.

The column_list is necessary only when some, but not all, columns in the table are to receive data. You can leave out items in the column_list as long as the omitted columns permit null values or the columns are associated with a default.

If column_list is not specified, all columns in the receiving table (in CREATE TABLE order) are assumed to be included.

procedure_name = {[[[server.]database.]owner.]procedure_name[;number] }

Is a user-defined procedure name.

procedure_name

Is a stored procedure. You can execute a local procedure, or you can execute a procedure that has been created in another database if you are its owner or have permission to execute it in that database. You can execute a procedure on another SQL Server if you have permission to use that server (remote access) and to execute the procedure in that database. If you specify a server name but do not specify a database name, SQL Server looks for the procedure in your default database.

;number

Is an optional integer used to differentiate procedures created by using the same name.

@procedure_name_var

Is the name of a locally defined variable that represents a stored procedure name.

@parameter_name

Specifies the parameter for a procedure, as defined in the CREATE PROCEDURE statement. Parameter names must be preceded by the "at" symbol (@). When used with the @parameter_name = value form, parameter names and constants need not be supplied in the order defined in CREATE PROCEDURE statement. However, if the @parameter_name = value form is used for any parameter, it must be used for all subsequent parameters.

value

Is the value of the parameter to the procedure. If you do not use a parameter name, parameter values must be supplied in the order defined in the CREATE PROCEDURE statement.

@variable

Specifies the variable that stores a parameter value.

OUTPUT

Indicates that the stored procedure returns a parameter. The matching parameter in the stored procedure must also have been created with the keyword OUTPUT.

DEFAULT

Specifies that the default value is used.

Remarks

This statement allows you to run procedures on local or remote systems and store the returned information in a local table. The procedures can be system procedures, user-defined procedures, or extended procedures.

Specify the system and procedure you want to run by specifying the procedure name. To specify a remote system, the procedure name will begin with the server name followed by the database name, the owner of the procedure, and the procedure name. Each element of the procedure name is followed by a period except for the procedure name itself. For example, the remote procedure get_latest_sales owned by jake on the accounts server would look like this:

accounts.acct_db.jake.get_latest_sales

The local table is loaded with data returned from SELECT statements. The local table must already exist. Data returned from the PRINT statement, RAISERROR statement, FETCH statement, or other output is not stored in the table.

A procedure that returns multiple results sets appends the data to the table.

Data returned from the SELECT statement must conform to the datatypes in the existing local table's columns. For example, inserting varchar data into a tinyint data column is not permitted.

All INSERT statement rules apply to this operation. That is, table constraints, rules and triggers, and implicit datatype conversion rules are all enforced during table population. For more information about INSERT statement rules, see INSERT Statement.

For more information about writing procedures, see CREATE PROCEDURE Statement.

Errors are reported if there is a datatype mismatch between local table input columns and values returned from the procedure. Also, if the number of columns does not match the number of items returned in a row, an error is returned.

For more information about executing a procedure, see EXECUTE Statement in this document and in the Microsoft SQL Server Transact-SQL Reference.

Examples

A.	Populate Local Tables with Remote Database Information

This example retrieves information from a remote database for administration purposes. The human_resource.hr.dbo.fetch_employee_data and marketing.mis.dbo.fetch_sales_figures procedures pull data from remote sites into local tables.

INSERT INTO employee_info

EXECUTE human_resource.hr.dbo.fetch_employee_data

INSERT INTO sales_info
EXECUTE marketing.mis.dbo.fetch_sales_figures

B.	Assign the Current Value of the SET Option to a Variable

This example shows how to use the new INSERT EXECUTE feature to enable Transact-SQL code to assign the current value of a SET option to a variable.

SET NOCOUNT on

CREATE TABLE #tb_setopts

(SetOptName varchar(35) NOT NULL ,SetOptValue varchar(35) null)

INSERT INTO #tb_setopts (SetOptName,SetOptValue)

EXEC('dbcc useroptions')

DECLARE @CurrentValue varchar(35)

SELECT @CurrentValue=case min(SetOptValue) WHEN 'SET'

THEN 'on' else 'off' END

FROM #tb_setopts WHERE SetOptName='ansi_padding'

IF @CurrentValue='on'

RAISERROR('The SET opt ''ansi_padding'' is''on''.' ,1,1)

ELSE

RAISERROR('The SET opt ''ansi_padding'' is''off''.',1,1)

IF object_id('tempdb..#tb_setopts') IS NOT NULL

DROP TABLE #tb_setopts

/********  Actual output....

DBCC execution completed. If DBCC printed error messages, see your

System Administrator.

The SET opt 'ansi_padding' is 'off'.

********/


The ISDATE and ISNUMERIC Functions
The ISDATE and ISNUMERIC Functions (version 6.5)

ISDATE Function

Checks a variable or column with varchar datatype for valid date format. The function returns 1 when the variable or column contains a valid date, otherwise it returns 0.

In this example, the value 1 is returned:

SELECT ISNUMERIC(zipcode) FROM address

ISNUMERIC Function

Checks a variable or column with varchar datatype for valid numeric format. The function returns 1 when the variable or column contains a valid numeric value, otherwise it returns 0.

In this example, the value 1 is returned:

declare @datestring varchar(8)

SELECT @datestring ="12/21/95"

SELECT ISDATE(@datestring)

The following table is a summary of the return values for the ISDATE and ISNUMERIC functions for a selection of examples.

Column (varchar)  value	ISDATE  return value	ISNUMERIC  return value
NULL	0	0
abc	0	0
100	0	1
100	0	1
100 a	0	0
100.00	0	1
.01	0	1
-100.1234e-123	0	1
.231e90	0	1
$1000	0	1
$100	0	1
$100 a	0	0
$100.12345	0	1
-$100.12345	0	1
$-1000.123	0	1
as100	0	0
1a00	0	0
1995-10-1	1	0
1/20/95	1	0
1995-10-1 12:00pm	1	0
Feb 7 1995 11:00pm	1	0
1995-10-1	1	0
13/43/3425	0	0
1995-10-1a	0	0
1/23/95	1	0


LOAD Statement
LOAD Statement (version 6.5)

Loads a backup copy of one of the following:

•	User database and its transaction log (LOAD DATABASE)

•	Transaction log (LOAD TRANSACTION)

•	Table (LOAD TABLE)

•	Header information about the dump (LOAD HEADERONLY)

For additional syntax information for the LOAD statement, see the Microsoft SQL Server Transact-SQL Reference.

The LOAD TRANSACTION statement supports the STOPAT option, which stops a roll forward at a specified time.

The LOAD TABLE statement loads a backup copy of a table into a database.

The LOAD HEADERONLY statement returns additional columns.

Syntax

To load a table:

LOAD TABLE [[database.]owner.]table_name
FROM dump_device [, dump_device2 [..., dump_device32]]
[WITH options]

To load a transaction log:

LOAD TRANSACTION {dbname | @dbname_var}
FROM dump_device [, dumpdevice2 [..., dumpdevice32]]
[WITH options]

To load header information:

LOAD HEADERONLY
FROM dump_device

where

dump_device =

{dump_device_name | @dump_device_name_var}
|{DISK | TAPE | FLOPPY | PIPE} =
{'temp_dump_device' | @temp_dump_device_var}
[VOLUME = {volid | @volid_var}]

options =

[[, ] {UNLOAD | NOUNLOAD}]
[[, ] {SKIP | NOSKIP}]
[[, ] FILE = fileno]
[[, ] STOPAT = {date_time | @date_time_var}]
[[, ] SOURCE = source_name]
[[, ] APPEND]
[[, ] STATS [= percentage]]

TABLE

Specifies that a table is to be restored.

TRANSACTION

Specifies that only the transaction log is to be applied to this database. Transaction logs must be applied in sequential order. SQL Server checks the time stamps on the dumped transactions to ensure that the transactions are loaded into the correct database and in the correct sequence.

table_name

Is the name of table to be restored.

dbname | @dbname_var

Is the database from which the transaction log or complete database is being loaded. The database name can be specified as a string, char, or varchar variable.

dump_device_name | @dump_device_name_var

Is the logical name of the dump device as created by the sp_addumpdevice stored procedure. The dump device name can be specified as a string, char or varchar variable.

DISK | TAPE | FLOPPY | PIPE =

'temp_dump_device' | @temp_dump_device_var
Specifies the backup device media and is the temporary dump device from which to load the backup. These devices must exist when the load occurs; they do not have entries in sysdevices. The device types of DISK, TAPE, and FLOPPY should be specified with the complete path and filename of the device. A device type of PIPE should specify the named pipe that will be used by the client application. If specified as a variable (@temp_dump_device_var), the device name can be specified as a string or as a char or varchar variable. If you are using either a network server with a Universal Naming Convention (UNC) name or a redirected drive letter, specify a device type of DISK.

Important  When specifying a striped dump, you can use both logical device names (or variables) and temporary device names (or variables). PIPE devices have been added to allow third-party vendors a flexible and powerful way to connect their own software. For typical Transact-SQL use, the PIPE device is not used.

VOLUME = volid | @volid_var

Specifies the volume ID of the backup device, a 6-byte character string. If dumping to a new tape, this value is the name of the ANSI VOL1 label. For SQL Server, the default is SQL001. For subsequent dumps, this value is used to validate the volume name of the dump device. If specified as a variable (@volid_var), the volume name can be specified as a string or as a char or varchar variable. Explicitly specifying the volume ID is not recommended.

UNLOAD

Specifies that the tape be automatically rewound and unloaded when the LOAD is finished. UNLOAD is the default setting when a new user session is started. It remains set until that user specifies NOUNLOAD. This option is used only for tape devices.

NOUNLOAD

Specifies that the tape not be automatically unloaded when the LOAD is finished. NOUNLOAD remains set until UNLOAD is specified. This option is used only for tape devices.

SKIP

Specifies that the server not read the ANSI tape device headers.

NOSKIP

Specifies that the server read the ANSI tape device headers. This is the default.

FILE

Specifies that a file from a tape or disk device will provide the database, table or transaction log to load.

FILE = fileno

Is the file number to be loaded from the tape or disk device that contains multiple database backups. Load the first dump on the device (the default, 1).

STOPAT = date_time | @date_time_var

Is the date and time to stop loading a dump onto the database. If a variable is used for STOPAT, the variable should have a varchar or a char datatype. Only log records written before the specified date and time will be applied to the database.

APPEND

Specifies that all new data will be added to a table that already contains data. For LOAD TABLE use only.

SOURCE = source_name

Is the name of the source from which to load the table. This option must be specified if the source and target table names differ. For LOAD TABLE use only.

STATS = percentage

Is the percentage of pages loaded in increments optionally set at the time of the load. If a percentage is not specified, statistics are shown for each 10 percent of the load. This option is available only for database and table loads.

Remarks

The LOAD TABLE statement loads only one table at a time, which provides more control when recovering a database. Loading a table from a database dump is discouraged because if data manipulation transactions were occurring on the table when the database dump was performed, the data in the table may be logically inconsistent. You should load a table from a database dump only in disaster recovery situations, and even then it is important that you understand that the data loaded from the dump may be inconsistent.

When loading a table, use a target table and data source table. The data source table holds the data to be loaded to the target table; it can be a full database backup or an individual table backup.

For example, a company maintains a mailing list that is updated quarterly by an outside agency. The mailing list table has no index. The company wants to replace the existing mailing list with the new, agency-supplied mailing list. You could use a procedure that deletes all of the rows of the old table and inserts new rows, but a more efficient approach is to load the new table from a backup.

When loading a table, an EXCLUSIVE TABLE lock is placed on the table. No one else can read or modify the table while it is being loaded.

Important  It is recommended that you load a table only from a table dump file because a table dump file is generated from a locked table. It provides an up-to-date snapshot of the table. If you load a table from a database dump file, you will not get any outstanding transactions because the LOAD TABLE statement does not load transactions from the transaction log.

The schema for the data source table and the target table must match for the load to be successful. The names of the tables can be different if the SOURCE option is specified, but the underlying table structure must be the same in terms of base system types, lengths, and nullability.

Note  Once you have performed a load table operation, you must do a full database dump. Until you dump the full database, the transaction log cannot be dumped.

Using LOAD TABLE on a populated table is permitted if you use the APPEND option.

During load operations, triggers, rules, defaults, and declarative referential integrity (FOREIGN KEY, CHECK, PRIMARY KEY) are not enforced.

Important  Table loads are not permitted on tables that have text columns, indexes, or are published for replication. Table loads from mixed platforms are not supported. For example, you cannot dump a table on an Alpha-based server and load it into a table on an Intel-based server.

When a transaction log is not completely correct (because of possible user error) and you want to apply transactions up to a certain point in time, use the LOAD TRANSACTION statement with the STOPAT clause. If you are unsure which transaction log contains the stopping time, specify the STOPAT clause for all transaction logs that are being loaded.

For example, suppose a user mistakenly deletes the rows in a table on Sunday, Aug. 4, 1996 at 1:00 P.M. The transaction log's last transaction time was Sunday, Aug. 4, 1996 at 1:30 P.M. The STOPAT option is used to stop the roll forward at 12:55 P.M. on Sunday, Aug. 4, 1996. Transactions are applied up to just prior to the deletion.

The LOAD HEADERONLY statement retrieves all the volume and dump header information for all dumps on a particular dump device. The information is returned in a tabular format. These columns have been added to the LOAD HEADERONLY results set.

New columns	Datatype	Comment
BackupStart	datetime	Date and time of the oldest committed transaction. Cannot be NULL.
BackupFinish	datetime	Date and time of the most recently committed transaction. Cannot be NULL.
ServerSort	int	Server sort order. Cannot be NULL. This column is valid for database dumps only.
ServerCodePage	int	Server code page, which is the character set used by the server. Value is 0 when viewing a version 6.0 or earlier dump.
TableOwner	char(30)	Table owner.
OperatorName	char(30)	Name of the user performing the dump operation. Cannot be NULL unless viewing a version 6.0 or earlier database backup.
ProcessorType	int	CPU architecture number. Cannot be NULL.
SQLVersionMajor	int	Major version number of server that made the dump. Cannot be NULL. Value is 0 when viewing a version 6.0 or earlier dump.
SQLVersionMinor	int	Minor version number of server that made the dump. Cannot be NULL. Value is 0 when viewing a version 6.0 or earlier dump.
SQLVersionBuild	int	Build number of server that made the dump. Cannot be NULL. Value is 0 when viewing a version 6.0 or earlier dump.
Examples

A.	Load a Table

This example loads the employee_table from the disk file dump1 into  the personnel table.

LOAD TABLE personnel FROM dump1 WITH source='employee_table', APPEND

B.	Load a Transaction

This example loads a transaction log for the corporate database and stops it on Nov. 4, 1996 at 2:00 P.M..

LOAD TRANSACTION corporate FROM TAPEDUMP1
WITH STOPAT='1996 110414:00:00'

C.	Load a Header Only

This example loads the header only from a predefined device.

LOAD HEADERONLY FROM dump_dev1

Permission

INSERT permission is required to load a table. The target table's database must have the select into/bulkcopy database option set before loading a table.


RAISERROR Statement
RAISERROR Statement (version 6.5)

Sets @@ERROR to 0 by default for severity one through ten messages. The WITH SETERROR option sets the @@ERROR value to the msg_id argument or 50000 regardless of the severity.

For additional syntax information for the RAISERROR statement, see the Microsoft SQL Server Transact-SQL Reference.

Syntax

RAISERROR ({msg_id | msg_str}, severity, state
[, argument1 [, argument2]])
[WITH options]

where

msg_id

Is a user-defined error message stored in the sysmessages table.

msg_str

Is an ad hoc message with formatting similar to the C PRINTF format style. The error message can have as many as 255 characters. All ad hoc messages will have one standard message ID of 50000.

severity

Is the user-defined severity level associated with this message. Severity levels 0 through 18 can be used by any user. For severity levels 19 through 25, the WITH LOG option is required. Only the system administrator can issue RAISERROR with a severity level of 19 through 25.

state

Is an integer value from 1 through 127 that represents information about the invocation state of an error. A negative value for state will default to 1.

argument

Specifies the parameter used in the substitution of variables defined in the msg_str or the message corresponding to the msg_id. There can be zero 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 datatypes: int1, int2, int4, char, varchar, binary, or varbinary. No other datatypes are supported.

WITH options

Is one of the following values:

options	Description
LOG	Logs the error in the server error log and the event log. This option is required for messages with a severity level of 19 through 25, and it can be issued only by the system administrator.
NOWAIT	Sends messages immediately to the client server.
SETERROR	Sets @@ERROR value to msg_id or 50000 regardless of the severity level.
Remarks

This statement now sets @@ERROR to 0 if the severity is between 1 and 10 inclusive. Messages with severity levels 10 and under are not errors, but they do provide additional information.

If you set the msg_id by using the SETERROR option, the RAISERROR statement assigns the msg_id to the @@ERROR regardless of severity.

Otherwise, other behaviors of the RAISERROR statement remain the same.

Important  In SQL Server version 6.0, for messages with severity levels 10 and under, @@ERROR is set to 50000. To revert to SQL Server version 6.0 behavior, use either the SETERROR option or trace flag 2701.

For more information about trace flag 2701, see Trace Flags .

Examples

A.	Use msg_str

This example returns an @@ERROR value of 50000.

RAISERROR('Test Only',1,2) WITH SETERROR

B.	Use msg_id

This example returns an @@ERROR value of 101.

RAISERROR (101, 1, 2) WITH SETERROR


REVOKE Statement
REVOKE Statement (version 6.5)

Requires the CASCADE option to revoke a permission granted with the WITH GRANT OPTION option.

For additional syntax information for the REVOKE statement, see the Microsoft SQL Server Transact-SQL Reference.

Syntax

To revoke permission to database objects:

REVOKE [GRANT OPTION FOR]
{ALL [PRIVILEGES] | permission_list } [(column_list)]
ON { table_name [(column_list)]
| view_name [(column_list)]
| stored_procedure_name | extended_stored_procedure_name}
FROM {PUBLIC | name_list}
[CASCADE]

To revoke permission to create database objects:

REVOKE {ALL | statement_list}
FROM {PUBLIC | name_list}

where

GRANT OPTION FOR

Revokes the ability to confer the permission to another user but leaves the user with the permission still granted.

ALL

Specifies that all permissions possessed by all the users in the group or name_list to the specified object be revoked. When used to revoke statement permissions, specifies that all statement permissions possessed by the user be revoked.

permission_list =
{SELECT [(column_list)] | UPDATE [(column_list)]
| REFERENCES | DELETE | INSERT}

[, {SELECT [(column_list)] | UPDATE [(column_list)] | REFERENCES
| DELETE | INSERT} ...]

Lists permissions to revoke.

table_name

Is the name of the table in the current database to which the permissions apply.

column_list

Is a list of column names, delimited by commas, to which the permissions apply. If columns are specified, only SELECT and UPDATE permissions can be revoked.

view_name

Is the name of the view in the current database to which the permissions apply.

stored_procedure_name

Is the name of a stored procedure in the current database to which permissions apply.

extended_stored_procedure_name

Is the name of an extended stored procedure in the current database to which the permissions apply.

PUBLIC

Represents all users, including those who are members of other groups.

name_list

Is a list of user names and/or group names, delimited by commas. These names are stored in the database's sysusers table.

CASCADE

Revokes WITH GRANT privileges that were granted by the specified user, including those of the specified user. The specified user is either a name_list or PUBLIC.

statement_list

Is a list of statements that have already been granted. The statement list can include: CREATE DATABASE, CREATE DEFAULT, CREATE PROCEDURE, CREATE RULE, CREATE TABLE, CREATE VIEW, DUMP DATABASE, and DUMP TRANSACTION.

Remarks

You must use the CASCADE option when revoking a permission that is grantable. By using the CASCADE option, not only is the specified user's permission revoked, permission is revoked for all those to whom the specified user granted permission. If the CASCADE option is not specified and the specified user was granted WITH GRANT OPTION permission, an error is returned.

For example, suppose the owner of the table population_stats grants access permissions to a user, Matthew, by using WITH GRANT OPTION. The table owner enters the following statement:

GRANT SELECT ON population_stats TO matthew WITH GRANT OPTION

This gives the user Matthew permission to grant the same access privileges to another user, Jake. Matthew enters the following statement:

GRANT SELECT ON population_stats TO jake

If the owner attempts to revoke Matthew's SELECT permission with the following statement the owner receives an error:

REVOKE SELECT ON population_stats FROM matthew

The owner cannot revoke Matthew's access privilege because users would have access to tables of which the owner is not aware.

However, if the owner revokes Matthew's privileges by using CASCADE, then Matthew and Jake both lose their access to population_stats.

REVOKE SELECT ON population_stats FROM matthew WITH CASCADE

When the owner revokes Matthew's WITH GRANT OPTION privilege, then only the right to grant access privilege to other users is revoked. Users who have been granted access privileges, such as Jake, lose their access privilege. Matthew still has access privilege on the population_stats table:

REVOKE GRANT OPTION FOR SELECT ON population_stats FROM matthew

For more information about the REVOKE statement, see the Microsoft SQL Server Transact-SQL Reference.

Example

This example revokes the SELECT and UPDATE permissions on the population_stats table for user jake.

REVOKE SELECT, UPDATE(city) ON population_stats FROM jake


SELECT Statement
SELECT Statement (version 6.5)

Provides the WITH CUBE and WITH ROLLUP options as part of the GROUP BY clause. These operators produce an n-dimensional results set rather than the typical zero or one-dimensional results set.

In SQL Server 6.5, the LIKE operator will search on strings that contain wildcard characters by using an ESCAPE option.

For additional syntax information for SELECT statement, see the Microsoft SQL Server Transact-SQL Reference.

Syntax

SELECT [ALL | DISTINCT] select_list
INTO [new_table_name]
[FROM table_name [, table_name2 […, table_name16]]
[WHERE clause]
[GROUP BY clause]
[HAVING clause]
[ORDER BY clause]
[COMPUTE clause]
[FOR BROWSE]]

where

ALL

Specifies that duplicate rows can appear in the results set.

DISTINCT

Specifies that only unique rows can appear in the results set. Null values are considered equal for the purposes of the DISTINCT keyword; only one NULL is selected no matter how many are encountered.

select_list

Is the list of columns to select and can be one or more of the following.

Column	Description
Asterisk (*)	Represents all columns in the order in which they were specified in the CREATE TABLE statement. Affects all tables in the FROM clause.
A list of column names	Specifies the order in which you want to see column names. If the select_list contains multiple column names, separate the names with commas.
A column name and column heading	Specifies a heading to replace the default column heading (the column name), in the following form: column_heading = column_name Or column_name column_heading Or column_name AS column_heading
An expression	Specifies a column name, constant, function, or any combination of column names, constants, and functions connected by an operator(s), or a subquery. The expression can be used to set up an identity column by using the IDENTITY() function with SELECT INTO. For example, ID = IDENTITY(int,1,1).
IDENTITYCOL keyword	Specifies the IDENTITYCOL keyword instead of the name of a column that has the IDENTITY property.
Local or global variable	Specifies a local or global variable.
Local variable assignment	Specifies a local variable assignment in the form: @variable = expression
INTO new_table_name

Is the name of a new table to be created based on the columns specified in the select_list and the rows chosen in the WHERE clause.

FROM

Specifies the table(s) and view(s) used in the SELECT statement.

table_name =

{simple_table_name | derived_table | joined_table}

where

simple_table_name =
[[database.] owner.] {table_name | view_name} [[AS] alias_name]
[(optimizer_hints)]

Specifies the name of the table or view used in the SELECT statement.

where

table_name | view_name

Is the name(s) of the table(s) and view(s) used in the SELECT statement. If the list contains more than one table or view, separate the names with commas. If the table(s) or view(s) exist in another database(s), use a fully qualified table or view name, such as database.owner.object_name.

In SQL Server 6.5, errors are reported when redundant table names appear in the FROM clause. For example, these SELECT statements were supported in earlier releases but generate errors in SQL Server 6.5. In the first SELECT statement the tables were treated as two different tables. In the second SELECT statement the second authors reference is discarded.

SELECT * FROM pubs..authors,pubs.dbo.authors

SELECT * FROM authors,authors

To avoid generating these errors, use trace flag 110. This flag causes SQL Server to revert to the table resolution methods of earlier releases. For more information about trace flag 110, see Trace Flags.

alias_name

Is the name of an alias. Each table_name or view_name can be given an alias, either for convenience or to distinguish a table or view in a self-join or subquery.

optimizer_hints

Specify a locking method, an index, or no index (table scan) be used by the optimizer with this table and for this SELECT. Although this is an option, the optimizer can usually pick the best optimization method without hints being specified.

derived_table =
(select_statement) [AS] alias_name

Is a subquery as specified in select_statement and uses the results set of the subquery as the input to the query being executed.

where

select_statement

Is the statement that retrieves rows from the database.

joined_table =
{table_name CROSS JOIN table_name
| table_name [join_type] JOIN table_name ON search_conditions}

Is the results set that is the product of two or more tables being combined.

join_type =
{INNER | LEFT [OUTER] | RIGHT [OUTER] | FULL [OUTER]}

The following types of ANSI joins are permitted:

CROSS JOIN

Is the cross product of two tables. Returns the same rows as if no WHERE clause was specified in an old-style join.

INNER

Specifies that all inner rows be returned. Discards unmatched rows.

LEFT [OUTER]

Specifies that all left outer rows be returned. Specifies that all rows from the left table that did not meet the condition specified be included in the results set, and output columns from the other table be set to NULL.

RIGHT [OUTER]

Specifies that all rows from the right table that did not meet the condition specified will be included in the results set, and output columns that correspond to the other table be set to NULL.

FULL [OUTER]

If a row from either table does not match the selection criteria, specifies the row be included in the results set and its output columns that correspond to the other table be set to NULL.

Earlier versions of SQL Server outer joins are supported in the following examples:

Right Outer Join (*=)

Select authors.au_name, titleauthor.title_id
FROM authors.titleauthor
WHERE authors.au_id *=titleauthor.au_id

Left Outer Join (=*)

SELECT authors.au_lname, titleauthor.title_id
FROM authors, titleauthor
WHERE titleauthor.au_id =* authors.au_id

Note  Earlier versions of SQL Server joins cannot be used within the same statement as ANSI-style joins.

WHERE clause =

WHERE search_conditions

Specifies the conditions for the rows returned in the results set. There is no limit to the number of search_conditions that can be included in an SQL statement.

The LIKE operator has an ESCAPE option, which allows wildcard characters to be searched for in strings.

Consider the column description in a table, finances contains the value 'lending_rate%'.

The characters '%' and '_' are wildcard characters. If you want to search for rows where the column contains the sequence 'g_', you need to use the ESCAPE option because '_' is a wildcard character.

SELECT * FROM finances

WHERE description LIKE 'gS_' ESCAPE 'S'

The ESCAPE clause uses "S" as an escape character and if the search comes across "S" in the pattern string, it will take the next character "_" as a normal character rather than a wildcard character.

GROUP BY clause =
GROUP BY [ALL] aggregate_free_expression
[, aggregate_free_expression]...[, aggregate_free_expression]
[WITH {CUBE | ROLLUP}]

Specifies the groups into which the table will be partitioned and, if aggregate functions are included in the select_list, finds a summary value for each group.

The maximum number of bytes allowed in the GROUP BY clause is 900.

When the CUBE operator is specified, in addition to the usual aggregate rows, super-aggregate rows are introduced into the results set. A super-aggregate row is a summary row for all of the aggregate rows produced for one of the aggregate-free expressions in the GROUP BY clause.

For example, if your query was computing the average price of an automobile, grouped by manufacturer, a single super-aggregate row would be added that contained the average price of all cars. Suppose your query was grouped instead by manufacturer and color. The results set would then contain super-aggregates for each manufacturer, regardless of color, and separate super-aggregates for each color, regardless of manufacturer.

If the WITH ROLLUP clause is specified, a subset of super-aggregates is computed along with the usual aggregate rows. This is useful when you have sets within sets. Consider grouping by the expressions, column1, column2, and column3. Applying the ROLLUP operator results in these rows:

column1	column2	column3

column1	column2	(null)

column1	(null)	(null)

(null)	(null)	(null)

A maximum of 10 grouping expressions are permitted in a GROUP BY clause when WITH CUBE or WITH ROLLUP is specified. Otherwise, 16 grouping expressions are permitted.

You cannot specify the GROUP BY ALL clause when you use the CUBE or ROLLUP operators.

The CUBE and ROLLUP operators can be disabled when trace flag 204 is ON.

HAVING clause =

HAVING search_conditions

Specifies the conditions for aggregate functions in the select_list; the search_conditions restrict the rows returned by the query but do not affect the calculations of the aggregate function(s).

ORDER BY clause

Is the sort order used on columns returned.

COMPUTE clause =

COMPUTE row_aggregate(column_name)
[, row_aggregate(column_name)...]
[BY column_name [, column_name]...]

where

COMPUTE

Specifies that control-break summary changes be generated for row aggregate functions (SUM, AVG, MIN, MAX, and COUNT).

BY

Specifies that the values for row-aggregate functions be calculated for subgroups.

FOR BROWSE

Specifies that updates be allowed while viewing data in client applications that use DB-Library.

Remarks

Important  When creating a derived table, the SELECT statement does not support the use of the INTO, ORDER BY, COMPUTE, or COMPUTE BY clauses.

The FROM clause has been changed to support the ANSI-SQL syntax for joined tables and derived tables. ANSI-SQL syntax provides the INNER, LEFT OUTER, RIGHT OUTER, and FULL OUTER join operators.

Although the outer join operators *= and =* from earlier versions of SQL Server are supported, you cannot use both outer join operators and ANSI-SQL style joined tables in the same query.

When trace flag 204 is enabled, only the SQL Server version 6.0 and earlier SELECT statement syntax is permitted: joined tables, derived tables, and other ANSI features are not. Trace flag 204 is otherwise unchanged. Also, trace flag 330 enables full output that contains information about joins when you are using SHOWPLAN. For more information about trace flags 204 and 330, see Trace Flags .

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.

Note  In SQL Server version 6.5, 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 the discussion of trace flag 246 in Trace Flags.

The CUBE operator provides a superset of data in the results set. Not only is the typical joined data returned, each operand (column) in the GROUP BY clause is bound under the NULL keyword and applied to all other operands (columns).

The NULL keyword in this case represents all the values in a particular column.

Note  Using the HAVING clause in the SELECT statement does not effect the way the CUBE operator groups the results set and returns summary aggregate rows.

Examples

A.	Use an Aggregate Function in a SELECT Statement

This example uses the following table to demonstrate how the CUBE operator affects the results set.

product_ID	customer_ID	number_of_orders
----------	-----------	----------------
10	a	10
20	b	10
10	a	20
30	b	10
30	a	10
20	b	20
10	b	30
10	c	40
20	c	10
30	b	40
30	a	10
10	a	50
First, issue a typical query with a GROUP BY clause and the results set.

SELECT product_ID, customer_ID, SUM(number_of_orders)

FROM sales

GROUP BY product_ID, customer_ID

The GROUP BY causes the results set to form groups within groups. This is the results set:

product_ID	customer_ID	Sum  (number_of_orders)
---------	---------	---------------
10	a	80
10	b	30
10	c	40
20	b	30
20	c	10
30	a	20
30	b	50
B.	Use the CUBE Operator

Next, do a query with a GROUP BY clause by using the CUBE operator. The results set should include the same information plus super-aggregate information for each of the GROUP BY columns.

SELECT product_ID, customer_ID, SUM(number_of_orders)

FROM sales

GROUP BY product_ID, customer_ID

WITH CUBE

The results 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.

product_ID	customer_ID	SUM (number_of_orders)
-----------	------------	------------------
10	a	80
10	b	30
10	c	40
10	(null)	150
20	b	30
20	c	10
20	(null)	40
30	a	20
30	b	50
30	(null)	70
(null)	(null)	260
(null)	a	100
(null)	b	110
(null)	c	50
C.	Use the ROLLUP Operator with the COUNT Aggregate

This 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 in situations where summary information is needed but a full CUBE provides extraneous data. This is also useful when you have sets within sets. For example, you could think of departments within a company as a set within a set.

SELECT company, department COUNT(*) FROM personnel GROUP BY company, department WITH ROLLUP

This is the results set:

company	department	Number of Employees
abc	finance	10
abc	engineering	40
abc	marketing	40
abc	(null)	90
def	accounting	20
def	personnel	30
def	payroll	40
def	(null)	90
(null)	(null)	180
D.	Use the ROLLUP Operator

This example modifies the SELECT statement above to use the ROLLUP operator.

SELECT product_ID, customer_ID, SUM(number_of_orders)

AS 'Sum number_of_orders'

FROM sales

GROUP BY product_ID, customer_ID

WITH ROLLUP

This is the results set:

product_ID	customer_ID	Sum  number_of_orders
----------	-----------	----------------
10	a	80
10	b	30
10	c	40
10	(null)	150
20	b	30
20	c	10
20	(null)	40
30	a	20
30	b	50
30	(null)	70
(null)	(null)	260
The GROUPING function allows you to discriminate between a true null value and a null value representing an ALL value.

Expression  evaluation	GROUPING  returns	Description
(null)	1	Represents the set of all values.
any other value	0	Represents a particular value.
A new function GROUPING 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 column has a value other than (null). The returned value has a tinyint datatype.

E.	Use the GROUPING Function

This example modifies the SELECT statement that was used in the previous example.

SELECT product_ID, customer_ID, SUM(number_of_orders)

AS 'Sum number_of_orders',

GROUPING(product_ID) AS 'Grouping product_ID',GROUPING(customer_ID) AS 'Grouping customer_ID'

FROM sales

GROUP BY product_ID, customer_ID

WITH ROLLUP

This is the results set:

product_ID	customer_ID	Sum number _of_orders	Grouping product_ID	Grouping customer_ID
----------	-----------	----------	----------	----------
10	a	80	0	0
10	b	30	0	0
10	c	40	0	0
10	(null)	150	0	1
20	b	30	0	0
20	c	10	0	0
20	(null)	40	0	1
30	a	20	0	0
30	b	50	0	0
30	(null)	70	0	1
(null)	(null)	260	1	1
F.	Use Left Outer Join

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 appear in the results set, whether or not they have published any books.

SELECT authors.au_lname, authors.au_fname, titleauthor.title_id

FROM authors LEFT OUTER JOIN titleauthor

ON authors.au_id =titleauthor.au_id

G.	Use Inner Join with Three Tables

This example joins three tables: authors, titleauthors and titles. The results set contains a list of authors and royalties paid to date.

SELECT authors.au_fname, authors.au_lname, sum(titles.royalty * titles.ytd_sales/100)

FROM authors

JOIN titleauthor ON authors.au_id=titleauthor.au_id

JOIN titles ON titleauthor.title_id = titles.title_id

GROUP BY authors.au_lname, authors.au_fname

ORDER BY authors.au_lname

H.	Use Full Outer Join

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.

SELECT titles.title, publishers.pub_name

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

I.	Use Right Outer Join

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 results set, whether or not they have published any books.

SELECT publishers.pub_id, titles.title, titles.title_id

FROM titles RIGHT OUTER JOIN publishers

ON publishers.pub_id = titles.pub_id

J.	Use Cross Join

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.

SELECT au_lname, pub_name

FROM authors CROSS JOIN publishers


SET Statement
SET Statement (version 6.5)

Sets SQL Server query-processing options for the duration of the user's work session or for the duration of a running trigger or a stored procedure.

For additional syntax information for the SET statement, see the Microsoft SQL Server Transact-SQL Reference.

The SET statement provides these options.

Options	Description
ANSI_DEFAULTS	Sets options that control ANSI-compliant behavior.
ANSI_NULLS	Controls NULL handling by using equality operators.
ANSI_PADDING	Controls padding of variables.
ANSI_WARNINGS	Controls truncation and NULL in aggregate warnings.
CURSOR_CLOSE_ON_COMMIT	Controls behavior of cursors once a commit has been performed.
DISABLE_DEF_CNST_CHK	Controls interim constraint checking.
FIPS_FLAGGER level	Specifies the level of ANSI compliance that triggers a warning message. The level parameter can be ENTRY, INTERMEDIATE, FULL, or OFF.
IMPLICIT_TRANSACTIONS	Controls whether a transaction is started implicitly when a statement is executed.
NUMERIC_ROUNDABORT	Controls transaction behavior once a loss-of-precision condition has occurred.
REMOTE_PROC_TRANSACTIONS	When enabled, specifies that if a user-defined transaction is active, an MS DTC transaction will start if a remote stored procedure is executed.
ROWCOUNT	Accepts int, tinyint, and smallint variables for the parameter that sets the number of rows to be returned in the results set.
XACT_ABORT	Controls whether a full transaction termination occurs when an error condition is raised.
Syntax

Option syntax:

SET {
ANSI_DEFAULTS {ON | OFF}
| ANSI_NULLS {ON | OFF}
| ANSI_PADDING {ON | OFF}
| ANSI_WARNINGS {ON | OFF}
| CURSOR_CLOSE_ON_COMMIT {ON | OFF}
| DISABLE_DEF_CNST_CHK {ON | OFF}
| FIPS_FLAGGER {level | OFF}
| IMPLICIT_TRANSACTIONS {ON | OFF}
| NUMERIC_ROUNDABORT {ON | OFF}
| REMOTE_PROC_TRANSACTIONS {ON | OFF}
| ROWCOUNT {number | @int_variable}
| XACT_ABORT{ON | OFF}}

where

ANSI_DEFAULTS

Specifies ANSI-standard behavior.

When enabled, this option enables all the ANSI options, including:

ANSI_NULLS	ARITHABORT
ANSI_NULL_DFLT_ON	CURSOR_CLOSE_ON_COMMIT
ANSI_PADDING	IMPLICIT_TRANSACTIONS
ANSI_WARNINGS	QUOTED_IDENTIFIER
All of these ANSI-standard SET options define the query processing environment for the duration of the user's work session, a running trigger, or a stored procedure.

ANSI_NULLS

Specifies ANSI-standard behavior of the comparison operators, EQUAL (=) and NOT EQUAL (<>).

When ANSI_NULLS is enabled, the equal and not equal comparison operators exhibit new behavior. ANSI standards require that a null behaves like a null value in any mathematical context. That is, NULL in any statement causes the statement to evaluate to NULL.

Once you enable the ANSI_NULLS option, you must use the comparison operators IS NULL and IS NOT NULL to compare for a null value.

When ANSI_NULLS is enabled, the SELECT statement syntax will not accept NULL as an argument. For example, if ANSI_NULLS is enabled, this statement does not work if NULL is passed as the department parameter:

CREATE PROCEDURE get_employees (@department CHAR(30)) AS

SELECT * FROM department WHERE department.name=@department

This procedure returns rows where the department column matches the @department parameter. When ANSI_NULLS is enabled, the procedure must be rewritten for the instances where the @department parameter is a null value, as follows:

CREATE PROCEDURE get_employees (@department CHAR(30)) AS

IF (@department IS NULL)

SELECT * FROM department WHERE department.name IS NULL

ELSE

SELECT * FROM department WHERE department.name=@department

ANSI_PADDING

Specifies padding of values.

When enabled, the ANSI_PADDING causes varchar and varbinary values to be padded with spaces or nulls. It also affects fixed-length datatypes such as char or int. If the user specifies that columns of fixed-length datatypes (char, int, tinyint, smallint) can be NULL, ANSI_PADDING causes these columns to be padded in the event of a null value.

Note  If a table is created while ANSI_PADDING is enabled, the table column will exhibit the padding behavior. Disabling ANSI_PADDING has no effect on existing columns.

ANSI_WARNINGS

Specifies that warnings be generated when:

•	Null values appear in aggregate functions such as SUM, AVG, MAX, MIN, or COUNT.

•	An insert or update is attempted on a character (or binary) column and the current length of the new value exceeds the maximum allowed by that column. The insert or update is aborted as specified by the ANSI SQL-92 standard. Trailing blanks are ignored for character columns and trailing nulls are ignored for binary columns.

•	Divide-by-zero and arithmetic overflow errors occur.

For more information about controlling ANSI_WARNINGS, see sp_configure.

CURSOR_CLOSE_ON_COMMIT

Specifies that the cursor be closed once a transaction has been committed or rolled back. Closes any open cursors on commit or rollback and permits procedures to comply with ANSI NIST standards.

DISABLE_DEF_CNST_CHK

Specifies interim deferred violation checking.

An interim violation occurs when constraints are being violated during data modifications. Sometimes these violations are temporary and will no longer exist by the time the data modification concludes. This option suspends reporting of these temporary violations.

This option also can enhance performance. In rare cases, users cannot modify multiple rows because the query runs out of work tables. Work tables are used by the system to resolve suspect constraint violations while processing data modifications. By turning ON the DISABLE_DEF_CNST_CHK option, you can turn off interim constraint checking, which in turn prevents the query from generating interim work tables.

Once DISABLE_DEF_CNST_CHK is set, its new setting is used for the duration of the user's work session or until its value is changed.

FIPS_FLAGGER

Specifies checking for compliance with ANSI SQL-92 FIPS 127-2 standards.

level | OFF

Is the level of compliance to ANSI SQL standards that is checked for in all database operations. If a database operation conflicts with the level of ANSI SQL standards chosen, a warning is generated.

The level must be ENTRY, INTERMEDIATE, or FULL as described in the following table.

Level	Description
ENTRY	Standards checking for ANSI SQL entry-level compliance.
INTERMEDIATE	Standards checking for ANSI SQL intermediate-level compliance.
FULL	Standards checking for full ANSI SQL compliance.
If checking is turned OFF, no standards checking occurs.

IMPLICIT_TRANSACTIONS

Specifies implicit transactions.

Setting IMPLICIT_TRANSACTIONS opens an implicit transaction when the following statements are used:

FETCH	ALTER TABLE
DELETE	INSERT
CREATE	OPEN
GRANT	REVOKE
DROP	TRUNCATE TABLE
SELECT	UPDATE
When this option is turned on and if there are no outstanding transactions already, every ANSI SQL statement will automatically start a transaction. If there is an open transaction, no new transaction will be started. This transaction has to be explicitly committed by the user by using the command COMMIT TRANSACTION for the changes to take effect and locks released.

NUMERIC_ROUNDABORT

Specifies rounding characteristics when a loss of precision has occurred.

Loss of precision occurs when dividing or multiplying. It can also occur in other operations, such as addition and subtraction when the number is too large or too small to represent.

Setting NUMERIC_ROUNDABORT ON terminates any transaction that causes a loss of precision. When it is set to OFF, numeric data is rounded and the transaction continues normally.

REMOTE_PROC_TRANSACTIONS

Specifies that when a user-defined transaction is active, an MS DTC transaction will be started when a remote stored procedure is executed.

XACT_ABORT

Specifies termination handling for the current procedure.

Setting XACT_ABORT ON terminates the transaction if any error is encountered. If one statement raises an error, the entire transaction is terminated and rolled back.

Setting XACT_ABORT option is set to OFF terminates only the SQL statement that raised the error. The transaction will continue.

Remarks

Using the SET statement inside a trigger or stored procedure causes the option to revert to its previous setting after a trigger or stored procedure is executed.

Options changed with the SET statement take effect at the end of the batch. You can combine SET statements and queries in the same batch, but the SET options won't apply to queries in the batch.

Many of these SET options define the query processing environment for the duration of the user's work session or for the duration of a running trigger or stored procedure.

You can also set these options by using sp_configure 'user options'. For information about using sp_configure 'user options', see sp_configure.

For information about viewing these option settings, see @@OPTIONS Global Variable.

Example

SET ANSI_WARNINGS ON


UPDATE Statement
UPDATE Statement (version 6.5)

Changes data in existing rows, either by adding new data or by modifying existing data. You must use aliases to distinguish between updates of tables and columns with the same names.

For additional syntax information for the UPDATE statement, see the Microsoft SQL Server Transact-SQL Reference.

Syntax

UPDATE {table_name | view_name}
SET
column_name = {column_list | variable_list | variable_and_column_list}
[, column_name2 = {column_list2 | variable_list2 |
variable_and_column_list2}
...[, column_nameN = {column_listN | variable_listN ...
| variable_and_column_listN}]
| expression]
[FROM {table_name1 | view_name1}[(optimizer_hints)]
[, {table_name2 | view_name2}[(optimizer_hints)]
[..., {table_name16 | view_name16}[(optimizer_hints)]]]]

where

table_name | view_name =
[[database_name.]owner.]{table_name | view_name}

Specifies the name of the table or view used in the UPDATE statement.

SET

Is a required keyword used to introduce the list of column or variable clauses to be updated.

column_name =

Specifies a column from the table (table_name) or view (view_name).

column_list =

column_name = {expression | DEFAULT | NULL}

variable_list =

variable_name = {expression | NULL}

expression

Is a column_name, constant, function (aggregate functions are not allowed), or any combination of column_names, constants, and functions connected by an operator(s) or a subquery.

DEFAULT

Specifies the default value for that column.

variable_and_column_list =
variable_name = column_name = {expression | NULL | DEFAULT}

Specifies local variables as well as columns.

WHERE clause =
WHERE {search_conditions | CURRENT OF cursor_name}

Is used to do a searched update (using search_conditions) or a positioned update (using CURRENT OF cursor_name).

search_conditions

Specifies the criteria for a searched update.

CURRENT OF cursor_name

Specifies the criteria for a positioned update against the current row within the specified cursor_name.

FROM

Specifies the table(s) and view(s) that are used in the SELECT statement. FROM is required except when the table_name or view_name contains only constants, variables, and arithmetic expressions (no column names). The FROM clause supports a maximum of 16 tables and views. Tables in subqueries are included in this total.

table_name1 | view_name1 =
[[database.]owner.]{table_name. | view_name.}

Specifies the name(s) of the table(s) and view(s) that are used in the UPDATE statement. If the list contains more than one table or view, delimit the names with commas. If the table(s) or view(s) exist in another database(s), use a fully qualified table or view name (database_name.owner.object_name).

Each table_name or view_name can be given an alias, either for convenience or to distinguish a table or view in a self-join or subquery. Aliases (when defined) must be used for ambiguous column references and must match the alias reference (the full table name cannot be used if an alias has been defined). To use an alias, specify the object name, a space, and then the alias name as follows:

UPDATE titles

SET t.ytd_sales = t.ytd_sales + qty

FROM titles t, sales s

WHERE t.title_id = s.title_id

The order of the tables and views after the FROM keyword does not affect the results set returned.

optimizer_hints

Specify that a locking method, an index, or no index (table scan) be used by the optimizer with this table and for this UPDATE. Although this is an allowable option, the optimizer will usually pick the best optimization method.

An optimizer_hint can be one or more of the following.

Option	Description
TABLOCK	Performs an exclusive lock on the table that is held until the end of command. TABLOCKX can be substituted for TABLOCK.
PAGLOCK	Performs exclusive page locks where a single exclusive table lock would normally be taken.
TABLOCKX	Performs an exclusive lock on the table that is held until the end of command. TABLOCK may be substituted for TABLOCKX.
Important  Some of the optimizer hints can be used in combination. (For example, TABLOCK and PAGLOCK). When multiple options are specified, separate them with a space; the more restrictive option will take precedence.

Remarks

The update table must be unambiguous for updates to occur. If two tables in a query have the same column name, use aliases to distinguish them.

If aliases are used, the UPDATE statement will cause an error when the table that should be updated is ambiguous. Trace flag 110 will disable these changes.

For more information about trace flag 110, see Trace Flags.

Examples

A.	Reference the Same Table Twice in the UPDATE Statement

This example references the same table twice in the WHERE clause or different tables with the same name. In earlier versions, changes were made to the first occurrence of the table. In version 6.5 an error message is returned.

Table stockref

id	qty	type
1	10	'a'
2	10	'a'
3	10	'a'
4	10	'a'
1	30	'b'
2	40	'b'
3	50	'b'
4	60	'b'
update stockref

set s2.qty = s1.qty

from stockref s1, stockref s2

where s1.id = s2.id and

      s1.type = 'a' and

      s2.type = 'b'

This SELECT statement divides the stockref table into two parts, the 'a' range and the 'b' range, matches them on the id field and then copies the qty value from the 'b' range and replaces the qty values in the 'a' range. The UPDATE stockref section of the syntax is ambiguous because it does not specify whether to update the 'a' range or the 'b' range.

The SET s2.qty = s1.qty section of syntax specifies which range to update. In order to avoid an error, use an alias on the ambiguous table reference to indicate which range of the stockref table to update.

UPDATE s2

SET s2.qty = s1.qty

FROM stockref s1, stockref s2

WHERE s1.id = s2.id AND

s1.type = 'a' AND

s2.type = 'b

B.	Use Optimizer Hints

This example uses the PAGLOCK optimizer_hint to use a shared page lock when updating the author's last name from Yokohama to Yokomoto in the authors table.

UPDATE authors

SET au_lname = 'Yokohama'

FROM authors(PAGLOCK)

WHERE au_lame = 'Yokomoto'


USER Function
USER Function (version 6.5)

Returns the user's database username.

Syntax

USER

Remarks

This statement provides the same functionality as the USER_NAME() system function.


Stored Procedures

Microsoft SQL Server version 6.5 includes new and enhanced stored procedures for the following:

•	Catalog Stored Procedures

•	Extended Stored Procedures

•	Replication Stored Procedures

•	SQL Executive Stored Procedures

•	System Stored Procedures

Unless otherwise noted, all system stored procedures return a value of 0 to indicate success. Failure is indicated by any non-zero return value, usually greater than zero.

Important  All extended stored procedures written in the C programming language must be recompiled from the C source code and relinked under Microsoft SQL Server version 6.5 to OPENDS60.LIB.


Catalog Stored Procedures
Catalog Stored Procedures (version 6.5)

The following catalog stored procedures are described in this section:

•	sp_column_privileges

•	sp_columns

•	sp_datatype_info

•	sp_fkeys

•	sp_sproc_columns

•	sp_table_privileges


sp_column_privileges
sp_column_privileges (version 6.5)

Returns column privilege information for a single table in the current environment. The GRANTOR column can be either the database owner (TABLE_OWNER) or someone to whom the database owner granted permission by using the WITH GRANT OPTION clause in the GRANT statement.

For additional syntax information for sp_column_privileges, see the Microsoft SQL Server Transact-SQL Reference.


sp_columns
sp_columns (version 6.5)

Returns column information for the specified table(s) that can be queried in the current environment. The columns returned belong to a table or view.

For additional syntax information for sp_columns, see the Microsoft SQL Server Transact-SQL Reference.

The ORDINAL_POSITION column replaces the COLID column of earlier releases. In addition, the following columns have been inserted after the REMARKS column and before the SS_DATA_TYPE column.

Column	Datatype	Description
COLUMN_DEF	varchar(254)	The default value of the column.
SQL_DATA_TYPE	smallint	The value of the SQL datatype 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 datatypes. NOT NULL.
SQL_DATETIME_SUB	smallint	The subtype code for datetime and ANSI interval datatypes. For other datatypes, this column returns a NULL.
CHAR_OCTET_LENGTH	int	The maximum length in bytes of acharacter or integer datatype column. For all other datatypes, this column returns a NULL.
ORDINAL_POSITION	int	The ordinal position of the column in the table. The first column in the table is number 1. NOT NULL.
IS_NULLABLE	varchar(254)	The 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 displays 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 than the value returned for the NULLABLE column.
The return value for the PRECISION column is in base 10.


sp_datatype_info
sp_datatype_info (version 6.5)

Returns information about the datatypes supported by the current environment.

For additional syntax information for sp_datatype_info, see the Microsoft SQL Server Transact-SQL Reference.

The following columns have been inserted after the MAXIMUM_SCALE column and before the USERTYPE column.

Column	Datatype	Description
SQL_DATA_TYPE	smallint	The value of the SQL datatype 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 datatypes. NOT NULL.
SQL_DATETIME_SUB	smallint	The datetime or ANSI interval subcode if the value of SQL_DATA_TYPE is SQL_DATETIME or SQL_INTERVAL. For datatypes other than datetime and ANSI interval, this field is NULL.
NUM_PREC_RADIX	int	The number of bits or digits for calculating the maximum number that the column can hold. If the datatype is an approximate numeric type, then this column contains the value 2 to indicate that COLUMN_SIZE specifies a number of bits. For exact numeric types, this column contains the value 10 to indicate that the COLUMN_SIZE specifies 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	The value of interval leading precision if interval datatype; otherwise NULL.
In addition, the return value for the PRECISION column is in base 10.


sp_fkeys
sp_fkeys (version 6.5)

Returns logical foreign key information for the current environment. This procedure shows foreign key relationships including disabled foreign keys. Application coding that includes tables with disabled foreign keys could be implemented as follows:

•	Temporarily disable constraint checking (ALTER TABLE NOCHECK or CREATE TABLE NOT FOR REPLICATION) while working with the tables, and enable again later.

•	Use triggers or application code to enforce relationships.

For additional syntax information for sp_fkeys, see the Microsoft SQL Server Transact-SQL Reference.

For more information on disabling constraints, see Disabling Constraints.


sp_sproc_columns
sp_sproc_columns (version 6.5)

Returns column information for a single stored procedure in the current environment.

For additional syntax information for sp_sproc_columns, see the Microsoft SQL Server Transact-SQL Reference.

The ORDINAL_POSITION column replaces the COLID column of earlier releases. In addition, the following columns have been inserted after the REMARKS column and before the SS_DATA_TYPE column.

Column	Datatype	Description
COLUMN_DEF	varchar(254)	The default value of the column.
SQL_DATA_TYPE	smallint	The value of the SQL datatype 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 datatypes. NOT NULL.
SQL_DATETIME_SUB	smallint	The datetime ANSI interval subcode if the the value of SQL_DATA_TYPE is SQL_DATETIME or SQL_INTERVAL. For datatypes other than datetime and ANSI interval, this field is NULL.
CHAR_OCTET_LENGTH	int	The maximum length in bytes of a character or binary datatype column. For all other datatypes, this column returns a NULL.
ORDINAL_POSITION	int	The ordinal position of the column in the table. The first column in the table is 1. NOT NULL.
IS_NULLABLE	varchar(254)	The 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 YESif the column can include NULLS and displays 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 that the value returned for the NULLABLE column.
In addition, the return value for the PRECISION column is in base 10.


sp_table_privileges
sp_table_privileges (version 6.5)

Returns a list of tables and the privileges associated with each table in the current environment. Also, the GRANTOR column may be either the database owner (TABLE_OWNER) or someone to whom the database owner granted permission by using the WITH GRANT OPTION clause in the GRANT statement.

For additional syntax information for sp_table_privileges, see the Microsoft SQL Server Transact-SQL Reference.


Extended Stored Procedures
Extended Stored Procedures (version 6.5)

The following extended stored procedures are described in this section:

•	xp_cmdshell

•	xp_readmail

•	xp_sendmail

•	xp_snmp_getstate

•	xp_snmp_raisetrap

•	xp_sqlinventory

•	xp_sqltrace

Extended stored procedures provide a way to dynamically load and execute a function within a dynamic link library (DLL). Any non-interactive console-based program written in the C/C++ programming language can also be written as an extended stored procedure.

Important  Because of changes to underlying structures, all extended stored procedures written in the C programming language must be recompiled from the C source code and relinked under Microsoft SQL Server version 6.5 to OPENDS60.LIB.


xp_cmdshell
xp_cmdshell (version 6.5)

Grants non-administrative users permission to execute xp_cmdshell.

For complete syntax information for xp_cmdshell, see the Microsoft SQL Server Transact-SQL Reference.

Remarks

Generally, xp_cmdshell executes Windows NT commands in SQL Server's security context, which by default is a user account with local administrator authority. When a non-system administrator executes xp_cmdshell with the new configuration option set, the requested command runs in the SQLExecutiveCmdExec user account, which is the same account used by SQL Executive for scheduled tasks entered by non-system administrators.

When you grant execute permission for xp_cmdshell to users, the users can execute any operating-system command at the Windows NT command shell that the account running SQL Server (usually a local system account) has privilege to execute.

To restrict xp_cmdshell access to users who have administrator permission on the Windows NT−based computer where SQL Server is running, configure your SQL Server at the Server Options tab: Select the "xp_cmdshell - Use SQLExecutiveCmdExecAccount for Non-SAs" option.

Note  If you select the "xp_cmdshell - Use SQLExecutiveCmdExec Account for NonSAs" option and the client logs on to SQL Server as the system administrator, the command is executed under SQL Server's security context instead of the SQLExecutiveCmdExec security context.


xp_readmail
xp_readmail (version 6.5)

Reads a mail message from the SQL Server mail inbox. This procedure supports an additional output parameter, @originator_address, that returns the resolved mail address of the originator of the mail message.

For additional syntax information for xp_readmail see the Microsoft SQL Server Transact-SQL Reference.

Syntax

xp_readmail ([@msg_id = msg_id] [, @type = type [OUTPUT]] [, @peek = {'true' | 'false'}]
[, @suppress_attach = {'true' | 'false'}]
[, @originator = @sender OUTPUT]
[, @subject = @subject_line OUTPUT]
[, @message = @body_of_message OUTPUT]
[, @recipients = @recipient_list OUTPUT]
[, @cc_list = @cc_list OUTPUT]
[, @bcc_list = @bcc_list OUTPUT]
[, @date_received = @date OUTPUT]
[, @unread = {'true' | 'false'} OUTPUT]
[, @attachments = @temp_file_paths OUTPUT])
[, @skip_bytes = @bytes_to_skip OUTPUT]
[, @msg_length = @length_in_bytes OUTPUT]
[, @originator_address = @originator_address OUTPUT])

where

@originator_address

Specifies the resolved mail address of the originator of the mail message. The @originator_address variable must be varchar(255).


xp_sendmail
xp_sendmail (version 6.5)

Sends a message, and/or a query results set, and/or an attachment to specified recipients. The xp_sendmail extended stored procedure 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.

For additional syntax information for xp_sendmail, see the Microsoft SQL Server Transact-SQL Reference.


xp_snmp_getstate
xp_snmp_getstate (version 6.5)

Returns the state of the SQL Server Simple Network Management Protocol (SNMP) agent. The state of the SNMP agent indicates whether the agent is available to have the Microsoft SQL Server server queried by an SNMP client.

For more information about Simple Network Management Protocol (SNMP), consult your Microsoft Windows NT operating-system documentation.

Syntax

xp_snmp_getstate [return_status OUTPUT]

where

return_status OUTPUT

Specifies the status returned from the SNMP agent. The return status must have an int datatype. Executing the procedure with no parameters returns a results set that indicates the status and the definition of the SNMP agent's state.

Remarks

The SQL Server SNMP agent interacts between SQL Server and SNMP clients that are running an operating system, including Windows NT, UNIX®, or another mainframe computer operating system. Stored procedures that depend upon the SNMP agent can query the SNMP agent to make sure it is available and in a normal state before proceeding.

If xp_snmp_getstate is executed with no parameters (for example, EXECUTE xp_snmp_getstate), a status and its meaning are returned. Status indicates the status code integer and meaning explains the status code. For a complete list of all statuses, see xp_snmp_raisetrap later in this document.

Examples

A.	Return SNMP Agent Status

This example returns the state of the SNMP agent.

DECLARE @retval INT

EXECUTE xp_snmp_getstate @retval OUTPUT

SELECT 'status'=@retval

B.	Return SNMP Agent Status and Meaning

This example returns status and status meaning for the current SNMP agent.

EXECUTE xp_snmp_getstate

Status	Meaning

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

3	The network has not been started.

Permission

The system administrator and users granted execute permission by the system administrator can execute this procedure.


xp_snmp_raisetrap
xp_snmp_raisetrap (version 6.5)

Permits a client to define and send a trap (an SNMP alert) to an SNMP client.

Syntax

xp_snmp_raisetrap server, database, error_message, message_id, severity, user, comment, date_and_time, return_status OUTPUT

where

server

Is the name of the server where the trap (SNMP alert) originated. The server string can have a maximum of 30 characters and must have a varchar datatype.

database

Is the name of a database where the trap originated. The database string can have a maximum of 30 characters and must have a varchar datatype.

error_message

Is the message for the trap. The error_message string can have a maximum of 255 characters and must have a varchar datatype.

message_id

Is the message error number for the trap. It corresponds to an error number in the sysmessages table, which is associated with the error_message. The message_id must have an int datatype.

For more information about message_id, see sp_addmessage in the Microsoft SQL Server Transact-SQL Reference.

severity

Is the severity of message_id.. The SNMP client views this value as the trap number. The severity must have an int datatype.

For more information on severity, see sp_addmessage in the Microsoft SQL Server Transact-SQL Reference.

user

Is the name of the user raising the trap. The user string can have a maximum of 30 characters and must have a varchar datatype.

comment

Is additional text associated with the trap. The comment string often will include information that is important to interpreting the trap event. The comment string can have a maximum of 255 characters and must have a varchar datatype.

date_and_time

Specifies the date and the time the trap occurred. The date_and_time column must have a datetime datatype.

return_status OUTPUT

Returns the completion status of the statement. This parameter must have an int datatype. These are the possible status values.

Status	Description
0	The SQL agent is running and the trap was sent successfully.
2	A memory error occurred.
3	The network has not been started.
4	The SQL SNMP agent has timed out while waiting for a response from the SNMP client.
5	The SQL SNMP agent is not running.
Remarks

This procedure provides communication about SQL Server conditions to SNMP management workstation(s). You can create your own error messages, message error numbers, and severity levels, although it is recommended that you use the error messages, message error numbers, and severity levels provided in the sysmessages or sysservermessages system tables. In the Network control panel, you can define which SNMP management workstations (clients) will receive traps under SNMP service. Clients are set up on a per SQL Server basis.

Traps are usually administrative alerts about conditions or events within the SQL Server. Applications may also raise traps to notify SNMP clients of application specific conditions. For example, this procedure allows the system administrator to alert an SNMP workstation of an action that the system administrator needs to fix.

For more information about SNMP, consult your Microsoft Windows NT operating-system documentation.

Example

This example sends a trap to the SNMP management workstation.

DECLARE @db varchar(30)
DECLARE @user varchar(30)
DECLARE @dt datetime
DECLARE @retval int
SELECT @dt = getdate()
SELECT @user = user_name()
SELECT @db = db_name()
EXECUTE xp_snmp_raisetrap @@servername, @db,
'The authors table was updated',
50001, 10, @user, 'This trap could have been raised by  an update
trigger on theauthors table', @dt, @retval OUTPUT
SELECT Status = @retval


xp_sqlinventory
xp_sqlinventory (version 6.5)

Captures SQL Server configuration and inventory information asynchronously on the SQL Server computer and stores it in the specified database and table.

Syntax

xp_sqlinventory {'DbName', 'TableName', Interval | stop}

where

DbName

Specifies the database in which to store inventory information. The DbName specified must already exist and must have enough free space to hold the retrieved inventory data. The DbName can be a maximum of 30 characters and must have a varchar datatype.

TableName

Is the name of the table in which to store the inventory information. The TableName specified will be created if it does not already exist and will store configuration information only for servers that are in the same Windows NT domain as the SQL Server running xp_sqlinventory. The TableName parameter can be a maximum of 30 characters and must be a varchar datatype.

Interval

Specifies the time (in seconds) to wait between checks for inventory messages. The Interval parameter must have an int datatype and can be a value between 1 (once per second) and 3600 (once per hour).

stop

Specifies to stop all in-progress inventory actions.

Remarks

This procedure captures SQL Server configuration and inventory information for all SQL Servers on the domain and stores the information in the specified DbName and TableName. Any SQL Server running the LocalSystem account will not be 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 this extended stored procedure to work, you must configure SQL Server to run in a valid domain user account through the Startup dialog box in Control Panel, Services.

Inventory errors are written to the Windows NT Event Log.

Note  This procedure does not support named parameters.

The following inventory information is captured for each inventoried SQL Server.

Column name	Description
ReceiveDate	Specifies the date and time the message was received on the SQL Server.
ServerName	Specifies the SQL Server machine name.
ProductName	Specifies the product name of Microsoft SQL Server.
SQLRegisteredOwner	Specifies the registered owner name typed in during SQL Server Setup.
DomainName	Specifies the Windows NT domain name of the SQL Server.
MajorVersion	Specifies the major version number for the SQL Server's version. For example, the "6" in SQL Server version 6.50 is the SQLMajorVersion.
MinorVersion	Specifies the minor version number for the SQL Server version. For example, the "50" in SQL Server version 6.50 is the SQLMinorVersion.
BuildNumber	Specifies the internal build number for the SQL Server version.
ServerLogins	Specifies the total number of configured user logins obtained from the master.dbo.syslogins system table.
MaxConnections	Specifies the maximum number of people that can be simultaneously connected to SQL Server.
DBCount	Specifies the total number of databases on the server including master, tempdb, and model databases.
TotalDeviceSize	Specifies the size in megabytes of all devices allocated for SQL Server data. This number does not include dump devices.
SortOrder	Specifies the 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	Specifies the SQL Server security mode. The possible values are: 0    Standard security 1    Integrated security 2    Mixed security
ProcedureCache	Specifies the percentage of memory allocated to SQL Server's procedure cache. Values may range from 1 to 99.
SMPStatus	Specifies how aggressively SQL Server will use multiple microprocessors. The default value is 0. For possible values, see "SMP concurrency" in the sp_configure system stored procedure in the Microsoft SQL Server Transact-SQL Reference.
ConfiguredMemory	Specifies the total amount of memory in megabytes allocated to SQL Server.
PriorityBoost	Specifies whether the SQL Server has been configured to run at a higher NT process priority level. For more information about priority boost, see sp_configure in the Microsoft SQL Server Transact-SQL Reference.
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 if it is in RAM. Default is 0 (no working set) and 1 (working set). For more information, see "Set working set size" in the sp_configure system stored procedure in the Microsoft SQL Server Transact-SQL Reference.
Publisher	Specifies the number of publications configured for the SQL Server.
Subscriber	Specifies the number of publications subscribed to for the SQL Server.
Distribution	Specifies whether the SQL Server is configured as a distribution server. The possible values are: 0    Not a distribution server 1    A distribution server
SupportSNMP	Specifies whether SNMP is available. For possible values, see xp_snmp_getstate, earlier in this document.
NamedPipe	Specifies whether the SQL Server can accept client connections by using the named pipe Net-Library. The possible values are: 0    No 1    Yes
MultiProtocol	Specifies whether the SQL Server can accept client connections by using the MultiProtocol Net-Library. The possible values are: 0    No 1    Yes
SPX	Specifies whether the SQL Server can accept client connections by using the Novell IPX/SPX Net-Library. The possible values are: 0    No 1    Yes
WinSocket	Specifies whether the SQL Server can accept client connections by using a WinSocket application programming interface Net-Library. The possible values are: 0    No 1    Yes
Appletalk®	Specifies whether the SQL Server can accept client connections by using an Appletalk Net-Library. The possible values are: 0    No 1    Yes
VINES	Specifies whether the SQL Server can accept client connections by using a Banyan® VINES® Net-Library. The possible values are: 0    No 1    Yes
DECnet™	Specifies whether the SQL Server can accept client connections by using a DECnet Net-Library. The possible values are: 0    No 1    Yes
CPUBrand	Specifies the brand of the microprocessor for the SQL Server. Possible values can be Intel, Alpha, MIPS, and PowerPC.
CPUModel	Specifies the microprocessor model, such as Pentium or Alpha for the SQL Server.
CPUStepLevel	Specifies the processor stepping version.
CPUCount	Specifies the number of microprocessors for the SQL Server.
ServerTotalMemory	Specifies the total amount of physical memory in megabytes on the SQL Server.
ServerAvailableMemory	Specifies the available amount of physical memory in megabytes on the SQL Server.
OperatingSystem	Specifies the operating system for the SQL Server. An example is Microsoft Windows NT.
OperatingSystemBuild	Specifies the internal operating system build version number for the SQL Server. An example is 1057 for the 1057 build of Windows NT 3.51 or later.
TotalPhysicalDisk	Specifies the total amount of physical disk space in megabytes on non-removable storage media.
AvailablePhysicalDisk	Specifies the amount of free disk space available in megabytes on the SQL Server.
Example

This example checks every two seconds for SQL Server inventory messages. The information is loaded into the db_info table in the sql_info database. After time has passed, the capturing of configure and inventory information stops.

USE pubs

go

DECLARE @db varchar(30)

DECLARE @table varchar(30)

DECLARE @interval int

SELECT @db = 'sql_info', @table = 'db_info', @interval=2

EXECUTE master..xp_sqlinventory @db, @table, @interval

...

...

EXECUTE master..xp_sqlinventory stop


xp_sqltrace
xp_sqltrace (version 6.5)

Allows database administrators and application developers to monitor and record database activity. Multiple instances of xp_sqltrace can be run simultaneously.

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]

where

@Function

Specifies a string that describes what action xp_sqltrace performs. These are the possible values for @Function.

@Function value	Description
audit	Logs all database activity requested by the specified filters to a file specified by @FullFilePath. Returns program control immediately. If @TraceId, @BufSize, or @TimeOut parameters are specified, they are ignored. If audit is used without any parameters, generates a results set that displays 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 an @TraceId before starting a trace session. The @TraceId parameter is required.
remove	Unloads all event handlers. Stops all data from being sent t o 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 results set. The @TraceId parameter has no effect.
@EventFilter

Specifies an integer (int datatype) that describes what server activity to monitor. To specify more than one @EventFilter value, add together the @EventFilter values. For example, @EventFilter = 31 means that xp_sqltrace should monitor CONNECT, DISCONNECT, POST_LANGUAGE, POST_RPC, and ATTENTION events. These are the possible values for @EventFilter.

@EventFilter 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 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.
@LangFilter

Specifies a string that specifies 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 semi-colon (;) for the OR condition (%INSERT%;%SELECT%).

@RPCFilter

Specifies a string pattern of remote stored procedure calls for which to monitor events. Delimit multiple filter strings with a semi-colon (;) for the OR condition. Use the wildcard character (%) to indicate any sequence of characters. Delimit multiple filter strings with a semi-colon (;) for the OR condition (%sp_cursors%;sp_run%).

@UserFilter

Specifies the login name(s) of users for whom to monitor events as a string. Delimit multiple filter strings with a semi-colon (;) 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

Specifies the application name(s) for which to monitor events as a string. Delimit multiple filter strings with a semi-colon (;) for the OR condition. Use the wildcard character (%) to indicate any sequence of characters. For example, specify the application name Acc% to find the Access application.

@HostFilter

Specifies the host(s) for which to monitor events as a string. Delimit multiple filter strings with a semi-colon (;) for the OR condition. Use the wildcard character (%) to indicate any sequence of characters. For example, specify the host name air% to find the airedale host.

@BufSize

Specifies the number of rows of data the server will buffer when the client is busy. The @BufSize parameter is of int datatype and can be a value 1 to 20,000. The default is 1,000.

@TimeOut

Specifies the amount of time in seconds that the server will wait when the row buffer specified in @BufSize is full before terminating the trace session. The @TimeOut parameter is of int datatype and can be 1 to 10 seconds (the default is five seconds).

@TraceId

Specifies the trace identification number used for the trace session. Each @TraceId value is static for a connection as long as you retain your current connection. The @TraceId parameter is of int datatype.

@FullText

Specifies whether the language or RPC strings should be returned as varchar(255) (The default is 0) or as text (1). The @FullText parameter is of int datatype.

@FullFilePath

Specifies the file to send the output to as a string (for example, 'C:\selects.txt'). This parameter uses the standard Microsoft SQL Trace log format for output.

For more information about the SQL Trace log format, see the online Help for SQL Trace.

@IntegerEvents

Specifies whether the event column should be text (The default is 0) or integer (1). The @IntegerEvents parameter is of int datatype.

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 or ISQL/w batch. After you choose the stop button in ISQL/w, another output row must be received for the trace to stop. This is a limitation of the ISQL/w interface.

Note  The recommended way to stop a trace session is to specify the trace identification number. For example:

xp_sqltrace stop, @traceid = <traceid>

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 that are specific to trace session output.

Event	Description
PAUSE (0)	Indicates that 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 who meets the criteria specified in the xp_sqltrace command line. For example, if the system administrator already has three connections, three ACTIVE rows will appear in the output. The trace session will report an ACTIVE row for pre-existing connections.
For more information about monitoring database activity, see the online Help for SQL Trace.

Examples

A.	Trace SELECT Statements for sa and probe

This example begins a trace session that displays the event, the username, the application, the data or language statement, and other columns. All SELECT statements executed by either sa or probe users are included in the trace. Events included in the trace are attention, connect, disconnect, post-language, and post-rpc events.

xp_sqltrace trace, @eventfilter = 31, @userfilter = 'sa;probe',
@langfilter = '%select%'

These are the columns generated in the results set.

Column name	Datatype	Description
Event	varchar(12) or int	Specifies the event (for example START, PAUSE, ACTIVE, Connect, Disconnect, SQL, Attention) as varchar(12) unless @IntegerEvents = 1.
UserName	char(30) NULL	Specifies the username of the user that generated the event.
ID	int	Specifies a unique, increasing identifier for connections.
SPID	int	Specifies the SQL Server process identification number.
StartTime	datetime NULL	Specifies the time that 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	Specifies the time that the language statement or remote stored procedure call stopped executing. For disconnect events, specifies the disconnect time.
Application	char(30) NULL	Specifies the application that generated the event.
Data	varchar(255) NULL or text NULL	Specifies the language statement or remote stored procedure call as varchar(255) unless @FullText = 1.
Duration	int NULL	Specifies the amount of time in milliseconds that 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	in NULLt	Specifies the amount of CPU time used in milliseconds.
Reads	int NULL	Specifies the number of disk reads.
Writes	int NULL	Specifies the number of synchronous disk writes.
NT_Domain	char(30) NULL	Specifies the NT Domain name of the user that generated the event.
NT_User	char(30) NULL	Specifies the NT User name of the user that generated the event.
HostName	char(30) NULL	Specifies the name of the host that generated the event.
HostProcess	int	Specifies the 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 sa or probe users and places the output in a text file called C:\SELECTS.TXT.

xp_sqltrace audit, @eventfilter = 31, @userfilter = 'sa;probe',
@langfilter = '%select%', @FullFilePath = 'C:\SELECTS.TXT'

C.	Obtain and Use a Specific @TraceId

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  xp_sqltrace
--start the trace  xp_sqltrace trace,  @eventfilter = 31
	--pause the trace session  xp_sqltrace control,  @TraceId = <TraceId>
	--begin trace session xp_sqltrace control  @TraceId = <TraceId>,  @EventFilter = 4,  @LangFilter = '%select%'
	--stop the trace session  xp_sqltrace stop,  @traceid = <traceid>
D.	Stop All Current Trace Sessions

The following two xp_sqltrace command examples stop all trace sessions executing on the current server while the third example stops only the specified trace session.

-- stops all trace sessions

xp_sqltrace stop, @traceid = 0

-- OR

xp_sqltrace stop

--recommended way to stop a single trace session

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

EXECUTE master.dbo.xp_sqltrace audit, 2, @FullFilePath = 'C:\MSSQL\LOG\AUDIT.LOG'

END

go

sp_makestartup 'sp_sqlaudit'

go

F.	Capture Server Activity to Table

This example uses the EXECUTE statement to capture all of the server activity to a table named sqltrace in the pubs database. Note that the transaction is not committed until you execute "xp_sqltrace stop" 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 EXECUTE master..xp_sqltrace TRACE, @eventfilter = 31

From another connection, execute the following statement.

EXEC master..xp_sqltrace STOP, 1358560

/* where 1358560 is the trace session returned from xp_sqltrace */

G.	BCP SQL Trace Activity Log

You can easily load an activity log into SQL Server using BCP.  First create a log and capture the server activity to an activity log file.   Next, create a table with the following structure:

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

Finally, load the data using BCP.

bcp pubs..SQLTrace in c:\activity.log -Usa -Psecret -S -c

Permission

Execute permission defaults to the system administrator. It is recommended that the system administrator be the only login permitted to execute this procedure.


Replication Stored Procedures
Replication Stored Procedures (version 6.5)

The following replication stored procedures are described in this section:

•	sp_addsubscriber

•	sp_addsubscription

•	sp_changearticle

•	sp_changesubscriber

•	sp_dsninfo

•	sp_enumdsn

•	sp_helpsubscriberinfo

•	sp_replcmds


sp_addsubscriber
sp_addsubscriber (version 6.5)

Adds a new subscriber server. An optional description parameter has been added and is used as a description for ODBC and SQL Server subscribers to determine what version of Microsoft SQL Server is being used for replication.

For additional syntax information for sp_addsubscriber, see the Microsoft SQL Server Transact-SQL Reference.

Syntax

sp_addsubscriber subscriber [, type] [, login] [, password] [, commit_batch_size] [, status_batch_size] [, flush_frequency] [, frequency_type] [, frequency_interval] [, frequency_relative_interval] [, frequency_recurrence_factor] [, frequency_subday] [, frequency_subday_interval] [, active_start_time_of_day] [, active_end_time_of_day] [, active_start_date] [, active_end_date] [, description]

where

description

Specifies an optional text description. When upgrading to SQL Server 6.5, existing MSsubscriber_info tables are modified to include a description column, which is initialized to SQL Server 6.0. The description parameter can have a maximum of 255 characters and must have a varchar datatype.

Example

This example sets up ACCOUNTS as a subscription server and includes a comment as a description.

sp_addsubscriber ACCOUNTS, @description='Temporary Subscriber'

Permission

Execute permission defaults to the system administrator.


sp_addsubscription
sp_addsubscription (version 6.5)

Adds a subscription to an article and sets the subscriber's status. sp_addsubscription prevents DSN subscribers to publications that:

•	Were created with the native @sync_method in the call to the sp_addpublication stored procedure.

Or

•	Contain articles that were added to the publication with an sp_addarticle stored procedure that had a pre_creation_cmd parameter of 3 (truncate).

For additional syntax information for sp_addsubscription, see the Microsoft SQL Server Transact-SQL Reference.


sp_changearticle
sp_changearticle (version 6.5)

Changes an article's properties.

For additional syntax information for sp_changearticle, see the Microsoft SQL Server Transact-SQL Reference.

Syntax

sp_changearticle publication, article [, property, value]

where

property

Specifies an article property to change. Can be:

status

value

Specifies the article value. Can be used with:

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 non-owner-qualified table names.


sp_changesubscriber
sp_changesubscriber (version 6.5)

Changes the options for a subscription server. Any distribution task for the publisher's subscribers will be updated. The description parameter allows the user to add descriptive text and is used for ODBC and SQL Server subscribers to determine what version of SQL Server is being used for replication.

For additional syntax information for sp_changesubscriber, see the Microsoft SQL Server Transact-SQL Reference.

Syntax

sp_changesubscriber subscriber [, type] [, login] [, password] [, commit_batch_size] [, status_batch_size] [, flush_frequency] [, frequency_type] [, frequency_interval] [, frequency_relative_interval] [, frequency_recurrence_factor] [, frequency_subday] [, frequency_subday_interval] [, active_start_time_of_day] [, active_end_time_of_day] [, active_start_date] [, active_end_date] [, description]

where

description

Specifies an optional text description. When upgrading to SQL Server 6.5, existing MSsubscriber_info tables are modified to include a description column that is initialized to SQL Server 6.0. The description parameter can have a maximum of 255 characters and must have a varchar datatype.

Example

This example sets up ACCOUNTS as a subscription server and puts in a comment as a description.

sp_changesubscriber ACCOUNTS, @description='Temporary Subscriber'

Permission

Execute permission defaults to the system administrator.


sp_dsninfo
sp_dsninfo (version 6.5)

Retrieves ODBC data source name (DSN) information from the replication distribution server that is associated with the current server if replication is installed. Information retrieved is the database vendor name, the database version, the database name, and whether the database permits subscribers.

Syntax

sp_dsninfo dsn [, infotype ][, login ][, password ]

where

dsn

Is the name of the ODBC DSN.

infotype

Is the type of information to return. If an infotype is not specified or if NULL is specified, all information types are returned. The infotype can be one of these.

Infotype	Description
DBMS_NAME	Specifies the returned DSN database vendor name.
DBMS_VERSION	Specifies the returned DSN database version.
DATABASE_NAME	Specifies the returned DSN database name.
SQL_SUBSCRIBER	Specifies the returned information about whether the database permits subscribers. Omitting this parameter or setting it to NULL returns rows for all infotype values.
login

Specifies the login for the DSN. If the DSN includes a login, specify NULL or omit the parameter.

password

Specifies the password for the login. If the DSN includes a login, specify NULL or omit the parameter.

Remarks

This stored procedure retrieves ODBC DSN information that shows what other databases can be used for replication or querying.

Example

This example returns all infotype data for the DSN northwind.

Note  To receive the output shown, you must have Microsoft Access installed on your computer.

sp_dsninfo 'northwind'

Information Type      Value
--------------------- -----------------------------------
DBMS Name             ACCESS
DBMS Version          3.0
Database Name         D:\MSOFFICE\Access\Samples\Northwind
SQL Subscriber        TRUE


sp_enumdsn
sp_enumdsn (version 6.5)

Reports all defined ODBC DSNs for a server running under a specific Windows NT user account.

Syntax

sp_enumdsn

Remarks

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

A two-column result set is returned with the DSN name and description.

Example

This example returns all the defined ODBC DSNs for a server running under a specific Windows NT user account.

sp_enumdsn

Data Source Name 	     Description

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

northwind             Microsoft Access Driver (*.mdb)

sql_pubs	              SQL Server

Permission

Only the system administrator can execute this procedure.


sp_helpsubscriberinfo
sp_helpsubscriberinfo (version 6.5)

Returns description parameters as a results column, which is used for ODBC and SQL Server subscribers to determine what version of SQL Server is being used for replication. Lists subscription information about a specified database or about a list of publication databases on the server.

For additional syntax information for sp_helpsubscriberinfo, see the Microsoft SQL Server Transact-SQL Reference.


sp_replcmds
sp_replcmds (version 6.5)

Treats the first client who runs sp_replcmds within a given database as the logreader. 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 logreader.

For additional syntax information for sp_replcmds, see the Microsoft SQL Server Transact-SQL Reference.

Remarks

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 will be qualified by the owner name, the owner of the table in the target database must be the same owner name.

The error message 18752 is:

Msg 18752, Level 16, State 1, Server <SERVERNAME>, Line 1

Another logreader is replicating the database

Note  The sp_replcmds procedure should be run only to troubleshoot problems with replication.

A warning message number 18759 will be added to both the SQL Server error log and the Windows NT Event Log if sp_replcmds is unable to replicate a text command because the text pointer was not retrieved in the same transaction. The 18759 error message text is: Unable to replicate a text command because the corresponding TEXTPTR was not found in the replicated transaction (%ld, %ld).

For more information about distribution processes, see the Microsoft SQL Server Administrator's Companion.


SQL Executive Stored Procedures
SQL Executive Stored Procedures (version 6.5)

The following SQL Executive stored procedures are described in this section:

•	sp_addtask

•	sp_helphistory

•	sp_helptask

•	sp_runtask

•	sp_updatetask

SQL Executive stored procedures give system administrators the ability to create tasks for replication, event scheduling, and alert management.


sp_addtask
sp_addtask (version 6.5)

Creates a scheduled task. The @cmdexecsuccesscode parameter has been added.

For additional syntax information for sp_addtask, see SQL Server Books Online or the Microsoft SQL Server Transact-SQL Reference.

Syntax

sp_addtask name[, subsystem] [, server] [, username] [, databasename] [, enabled] [, freqtype] [, freqinerval] [, freqsubtype] [, freqsubinterval] [, freqrelativeinterval] [, freqrecurrencefactor] [, activestartdate] [, activeenddate] [, activestarttimeofday] [, activeendtimeofday] [, nextrundate] [, nextruntime] [, runpriority] [, emailoperatorname] [, retryattempts] [, retrydelay] [, command] [, loghistcompletionlevel] [, emailcompletionlevel] [, description] [, tagadditionalinfo] [, tagobjectid] [, tagobjecttype] [, @newid OUTPUT] [, @cmdexecsuccesscode]

where

@cmdexecsuccesscode

Specifies an int value meaningful only for tasks whose @subsystem is CmdExec. This parameter is used by SQL Executive to determine if the CmdExec task failed or succeeded. If @cmdexecsuccesscode does not match the actual process exit code of the program involved in the task, the task is considered to have failed.


sp_helphistory
sp_helphistory (version 6.5)

Returns history only for those tasks owned by the calling user. This procedure prevents sensitive information stored in the systasks table from being displayed to all users.

The system administrator retains the ability to view the histories of all scheduled tasks.

For additional syntax information for sp_helphistory, see the Microsoft SQL Server Transact-SQL Reference.


sp_helptask
sp_helptask (version 6.5)

Provides information about one or more tasks that the user owns. This procedure prevents sensitive information stored in the systasks table from being displayed to all users.

The system administrator retains the ability to view all tasks.

For additional syntax information for sp_helptask, see the Microsoft SQL Server Transact-SQL Reference.


sp_runtask
sp_runtask (version 6.5)

Immediately executes a SQL Executive scheduled task either from a command batch or from a user-defined stored procedure.

Syntax

sp_runtask {'task_name' | @task_id=}

where

task_name

Is the SQL Executive task name.

@task_id=

Is the numeric ID of the task.

Remarks

This procedure must be run from the msdb database.

Example

A.	Run a Task from a Batch

PRINT 'Running sp_runtask...'

EXECUTE msdb.dbo.sp_runtask @taskid = 56

PRINT 'Finished'

B.	Run a Task from a Stored Procedure

CREATE PROC RunTask56 AS

BEGIN

EXECUTE msdb.dbo.sp_runtask @taskid = 56

END

Permission

Execute permission defaults to the public group.


sp_updatetask
sp_updatetask (version 6.5)

Updates information about a task. The @cmdexecsuccesscode parameter has been added.

For additional syntax information for sp_updatetask, see the Microsoft SQL Server Transact-SQL Reference.

Syntax

sp_updatetask {currentname | id} [, name] [, subsystem] [, server] [, username] [, databasename] [, enabled] [, freqtype] [, freqinterval] [, freqsubtype] [, freqsubinterval] [, freqrelativeinterval] [, freqrecurrencefactor] [, activestartdate] [, activeenddate] [, activestarttimeofday] [, activeendtimeofday] [, nextrundate] [, nextruntime] [, runpriority] [, emailoperatorname] [, retryattempts] [, retrydelay] [, command] [, loghistcompletionlevel] [, emailcompletionlevel] [, description] [, tagadditionalinfo] [, tagobjectid] [, tagobjecttype] [, @cmdexecsuccesscode]

where

@cmdexecsuccesscode

Specifies an int value meaningful only for tasks whose @subsystem is CmdExec. This parameter is used by SQL Executive to determine if the CmdExec task failed or succeeded. If @cmdexecsuccesscode does not match the actual process exit code of the program involved in the task, the task is considered to have failed.


System Stored Procedures
System Stored Procedures (version 6.5)

The following system stored procedures are described in this section:

sp_addlogin	sp_fallback_upd_dev_drive
sp_bindsession	sp_fallback_withdraw_svr_db
sp_certify_removable	sp_getbindtoken
sp_change_users_login	sp_helplogins
sp_coalesce_fragments	sp_helprotect
sp_configure	sp_helpserver
sp_dboption	sp_help_revdatabase
sp_dropwebtask	sp_makewebtask
sp_fallback_activate_svr_db	sp_rename
sp_fallback_deactivate_svr_db	sp_runwebtask
sp_fallback_enroll_svr_db	sp_serveroption
sp_fallback_help	sp_setnetname
sp_fallback_permanent_svr	sp_who


sp_addlogin
sp_addlogin (version 6.5)

Creates a new SQL Server user by adding an entry to the master.dbo.syslogins system table. A fifth parameter specifies a login suid for the syslogins table to repair an orphan user that occurs as a result of a database load.

For additional syntax information for sp_addlogin, see the Microsoft SQL Server Transact-SQL Reference.

Syntax

sp_addlogin login_id [, password [, defdb [, deflanguage [, login_suid]]]]

where

login_suid

Is the login suid in the syslogins table. If login_suid is NULL the suid is not affected. Use this parameter only when a database user in the sysusers table is an orphan to the syslogins table.

Example

This example creates a SQL Server login for the login ID Victoria. Victoria's password is citybythewater, her default database is products, her language defaults to the system language, and the new login suid in the syslogins table is 44882.

sp_addlogin 'Victoria','citybythewater','products',default,44882

Permission

Only the system administrator can use this stored procedure.


sp_bindsession
sp_bindsession (version 6.5)

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 Bound Connections earlier in this document.

Syntax

sp_bindsession 'bind_token' | 'NULL'

where

bind_token

Specifies the token that identifies the transaction space originally obtained by using the sp_getbindtoken stored procedure or the srv_getbindtoken Open Data Services function. The bind_token supports a maximum of 255 characters and must have a varchar datatype.

Remarks

This procedure uses a bind token to bind two or more existing client connections together. A connection is a client executing a command. Multiple cooperating database connections allow sharing of a common transaction lock space by being bound together to share a transaction context and lock space.

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.

Unbind from a session either by omitting the bind_token parameter or by passing NULL as the bind_token parameter.

This procedure can be executed through ODBC, DB-LIBRARY functions, or isql.

Important  Prior to executing sp_bindsession, you must obtain a bind token by running sp_getbindtoken or the Open Data Services srv_getbindtoken function.

For information about obtaining a bind token, see sp_getbindtoken, later in this document.

Permission

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 will run correctly.


sp_certify_removable
sp_certify_removable (version 6.5)

Verifies that a database is configured properly for distribution on removable media and writes returned information to a file.

For additional syntax information for sp_certify_removable, see the Microsoft SQL Server Transact-SQL Reference.

Remarks

This procedure writes verification information to a text file that has the following filename format:

CertifyR_[dbname].txt

Note  The permissions on xp_cmdshell must permit this file write.

The verification log file is written to the LOG\ directory under the SQL Server installation directory. The information is delimited by commas. Records preceded by two hyphens (--) are considered comments.

Example

This example certifies that the inventory database is ready to be removed.

sp_certify_removable inventory, AUTO

Permission

Only the system administrator can use this stored procedure.


sp_change_users_login
sp_change_users_login (version 6.5)

Reestablishes foreign key relationships from the syslogins to sysusers and sysalternates tables in cases where cross-server DUMP or LOAD database activity has broken these relationships. Without reestablishing relationships, orphan users may exist.

Syntax

sp_change_users_login {Auto_Fix | Report | Update_One}
[, 'UserNamePattern' [, 'LoginName']]

where

Auto_Fix | Report | Update_One

Specifies the action to take.

Action	Description
Auto_Fix	Links existing orphan usernames to logins of the same name. If an alternate username exists, each entry in the sysusers table is linked with an entry in the syslogins and sysalternates table. It is recommended that you monitor the outcome from the Auto_Fix statement. When linking rows, the Auto_Fix option makes assumptions that may be incorrect.
Report	Lists all usernames in sysusers that have no link to any login name in syslogins. This is the default.
Update_One	Links a specified orphan username in sysusers to an existing login name in syslogins. An orphan username has an entry in the sysusers table that does not have a matching entry in the syslogins table.
Important  Avoid using Auto_Fix in security-sensitive situations. The procedure makes best estimates on links, which could allow a user more access privileges than intended.

UserNamePattern

Is one of the following patterns.

UserNamePattern must be:	Action
Any non-NULL user-name pattern that is compatible with the LIKE operator.	Auto_Fix
NULL (the default).	Report
One username.	Update_One
LoginName

Is an existing login name. A login name is supported only when Update_One is specified. The default LoginName is NULL.

Remarks

It is suggested that you use this stored procedure after running the LOAD DATABASE statement because sp_change_users_login eliminates the need for manual updates for aliases or alternate usernames.

This stored procedure corrects a potential violation of referential integrity between syslogins and sysusers after DUMP and/or LOAD DATABASE activity. If the LOAD DATABASE statement runs and entries in the sysusers table do not have matching entries in the syslogins table, the tables have missing links. Missing links can prevent some users from using the database.

Missing links are created when login or user modifications occur between the DUMP and LOAD statements or if the dump and load are performed on different servers. For example, if a database is loaded from a database backup from six months ago that had only 100 users and the current version of the database has 130 users, the most recently added 30 users may not be able to access the database loaded from the backup. Reestablishing links by using sp_change_users_login can synchronize the entries in syslogins to the corresponding entries in sysusers and sysalternates, where aliases are used.

This procedure can also relink entries in the syslogins table to entries in the sysalternates table by using the Auto_Fix option.

Users such as guest, public, sa, probe, repl_publisher, repl_subscriber, and any group are not processed by this procedure. User logins that meet the conditions specified in UserNameorPattern (Auto_Fix) or LoginName (Update_One) will be processed with this procedure.

If this procedure completes normally, 0 is returned. If this procedure raises an error, 1 is returned.

Permission

Only the system administrator can run Auto_Fix. The public group can run Report. Only the system administrator or the database owner can run Update_One.


sp_coalesce_fragments
sp_coalesce_fragments (version 6.5)

Deletes and updates rows in the sysusages system table and combines sysusage entries where possible.

Syntax

sp_coalesce_fragments [DBNamePattern]

where

DBNamePattern

Specifies the database name pattern. The name pattern must adhere to the LIKE operator standards for string arguments. The default is '%' (all databases will be affected).

For more information about the LIKE operator, see Wildcard Characters in the Microsoft SQL Server Transact-SQL Reference.

Remarks

System administrators sometimes load a database or table backup file from a production database into a database on another server. Requirements for cross-database dump and load activities are documented under the LOAD Statement in the Microsoft SQL Server Transact-SQL Reference. One requirement is that two databases must have compatible lpage (logical page) and segmap (segment map) column information in the sysusages table. The target database must be created so the segmap for each range of logical pages (lpage) is compatible with the same information in the dumped database.

Two databases have compatible lpage and segmap structures if for every lpage number they have the same segmap value. If one database is larger than the other, some of the larger database's lpage numbers will not exist for the smaller database. A smaller database can be dumped into a larger database, but a larger database cannot be dumped into a smaller database.

Important  If the target and destination databases have different segmap structures, dump or load operations can cause data access problems, error messages can appear, or the load can fail if recovery must run.

For more information about logical pages, see the Microsoft SQL Server Administrator's Companion.

The sp_coalesce_fragments procedure simplifies the output from sp_help_revdatabase by replacing multiple rows in the sysusages system table with one row. For every row in the sysusages system table, sp_help_revdatabase produces an ALTER DATABASE statement. With fewer rows in the sysusages system table, fewer ALTER DATABASE statements are produced by sp_help_revdatabase, and fewer rows in sysusages makes it easier to verify compatible logical page and segment map combinations between databases. System administrators can execute sp_coalesce_fragments after ALTER DATABASE statements are issued.

This stored procedure is used with sp_help_revdatabase. Output from sp_help_revdatabase can help create a compatible database.

For more information about creating a compatible database, see sp_help_revdatabase later in this document.

The sysusages system table records the device fragments defined for each database during the CREATE DATABASE and ALTER DATABASE statements. Sometimes several fragments for a database on one device are physically contiguous. The sysusages rows for these contiguous fragments can be reduced to one row by running sp_coalesce_fragments. This reduction is safe because the fragments for a database on any device always have the same value for sysusages.segmap.

For more information about creating a database script that can replicate an existing database structure, see sp_help_revdatabase later in this document.

For more information about altering a database, see the ALTER DATABASE statement in the Microsoft SQL Server Transact-SQL Reference.

For more information about performing a database load, see the LOAD statement in the Microsoft SQL Server Transact-SQL Reference.

For more information about performing a database backup, see the DUMP statement in the Microsoft SQL Server Transact-SQL Reference.

Example

This example compares the output of a SELECT statement before and after sp_coalesce_fragments is run. Comments delimited by two hyphens (--) are interspersed throughout this example.

SELECT

'dbname'=substring(db_name(ug.dbid),1,10)

,ug.segmap,ug.lstart -- page number within a database

,ug.size,ug.vstart -- page number within dv

,'(vstart+size)' = ug.vstart + ug.size

,'device'=substring(dv.name,1,10)

FROM

master.dbo.sysusages ug,master.dbo.sysdevices dv

WHERE ug.vstart between dv.low and dv.high	 AND

dv.status & 2 = 2 --physical disk

AND

db_name(ug.dbid) in ('DB1','DB22','db_junk3')

ORDER BY ug.vstart

This is the results set:

dbname      segmap  lstart  size  vstart       (vstart+size)  device
----------  ------  ------  ----  -----------  -------------  ----------
DB1              3       0  2048    352321536      352323584  dvdata1
DB22             3       0  1024    352323584      352324608  dvdata1
DB22             3    1024  1024    352324608      352325632  dvdata1
DB22             4    2048  1024    369098752      369099776  dvlog1
db_junk3         7       0  1024    369099776      369100800  dvlog1
DB22             4    3072  1024    369100800      369101824  dvlog1
DB1              4    2048  1024    369101824      369102848  dvlog1
DB1              4    3072   768    369102848      369103616  dvlog1

Note  In the results set the size of 768 for one of the DB1 fragments is not an even multiple of 512. These fragment sizes are difficult to mimic when building compatible work databases for dump and load activities.

Compare the two results sets after sp_coalesce_fragments is executed:

EXECUTE sp_coalesce_fragments

This is the results set:

dbname      segmap  lstart  size  vstart       (vstart+size)  device
----------  ------  ------  ----  -----------  -------------  ----------
DB1              3       0  2048    352321536      352323584  dvdata1
DB22             3       0  2048    352323584      352325632  dvdata1
DB22             4    2048  1024    369098752      369099776  dvlog1
db_junk3         7       0  1024    369099776      369100800  dvlog1
DB22             4    3072  1024    369100800      369101824  dvlog1
DB1              4    2048  1792    369101824      369103616  dvlog1

The number of sysusages fragments is reduced by two.

Note  The two DB22 fragments that have segment map 4 cannot be coalesced because they are not contiguous. The lpage 1029 for database DB22 was in a coalesced fragment, and note that its corresponding segmap value remained 3 (system tables and data usage). Similarly, lpage 3081 in DB1 remained on a fragment where segmap is 4 (log usage).

Permission

Only the system administrator can run this procedure.


sp_configure
sp_configure (version 6.5)

Displays or changes global configuration settings for the current server.

The sp_configure stored procedure offers these options for the config_name parameter: affinity mask, max text repl size, remote conn timeout, remote proc trans, and user options.

For additional syntax information for sp_configure, see the Microsoft SQL Server Transact-SQL Reference.

Syntax

sp_configure ['config_name'[, config_value]]

where

config_name

Specifies a configuration option that must be enclosed in single quotation marks ('). These are the options:

affinity mask

Specifies which processor(s) the Symmetric Multiprocessor (SMP) SQL Server will use and allows the system administrator to associate a thread with a processor.

max text repl size

Specifies the maximum size in bytes of text and image data that can be added to a replicated column in a single INSERT, UPDATE, WRITETEXT or UPDATETEXT statement.

remote conn timeout

Specifies a time limit to break a server-to-server connection. The connection will be broken only when the connection has been inactive for the user-defined time. Without this timeout mechanism any server-to-server procedure call results in the connection between servers staying alive until the originating session terminates.

Note  If a connection is involved in an MS DTC−coordinated distributed transaction, the connection will not be timed out even if its inactivity period has expired.

remote proc trans

Allows users to protect the actions of a server-to-server procedure through an MS DTC − coordinated distributed transaction. When set to true, provides an MS DTC − coordinated distributed transaction that protects the ACID properties of transactions. Sessions begun after this option is set will inherit the configuration setting as their default. For more information about distributed transactions, see Distributed Transactions or see the Guide to Microsoft Distributed Transaction Coordinator.

user options

Specifies that the user options system configuration parameter is to be queried or modified.

For information about other config_name options for sp_configure, see the Microsoft SQL Server Transact-SQL Reference.

config_value

Is a value associated with a specific config_name. These are the values for the configuration options.

config_name	Minimum	Maximum	config_value	run_value
affinity mask	0	2147483647	0	0
max text repl size	0	2147483647	65536	65536
remote conn timeout	−1	32767	10	10
remote proc trans	0	1	0	0
user options	0	4095	0	0
affinity mask

Specifies a bit mask in which each bit represents the processors on which the thread is run. Use decimal values to specify affinity mask settings.

max text repl size

Specifies a number of bytes that can be added to a replicated column.

remote conn timeout

Specifies a number in minutes for breaking server-to-server connections.

remote proc trans

Specifies whether server-to-server connections are protected by an MS DTC coordinated distributed transaction (1) or not (0, the default).

user options

Specifies the global defaults for all users. A list of default query-processing options is established for the duration of a user's work session. A user can override these defaults by using the SET statement. The user options option can be dynamically configured for new logins. When the value is changed, new logins will use the new option; current logins will not be affected.

user options is one or a combination of the following.

Configuration  value	Description
1	DISABLE_DEF_CNST_CHK. Controls interim constraint checking.
2	IMPLICIT_TRANSACTIONS. Controls whether a transaction is started implicitly when a statement is executed.
4	CURSOR_CLOSE_ON_COMMIT. Controls behavior of cursors once a commit has been performed.
8	ANSI_WARNINGS. Controls truncation and NULL in aggregate warnings.
16	ANSI_PADDING. Controls padding of variables.
32	ANSI_NULLS. Controls NULL handling by using equality operators.
64	ARITHABORT. Terminates a query when an overflow or divide-by-zero error occurs during query execution.
128	ARITHIGNORE. Returns NULL when an overflow or divide-by-zero error occurs during a query.
256	QUOTED_IDENTIFIER. Differentiates between single and double quotation marks when evaluating an expression.
512	NOCOUNT. Turns off the message returned at the end of each statement that states how many rows were affected by the statement.
1024	ANSI_NULL_DFLT_ON. Alters the session's behavior to use ANSI compatibility for nullability. New columns defined without explicit nullability will be defined to allow NULLs.
2048	ANSI_NULL_DFLT_OFF. Alters the session's behavior to not use ANSI compatibility for nullability. New columns defined without explicit nullability will be defined not to allow NULLS.
Note  Not all configuration values for user options are compatible. For example, ANSI_NULL_DFLT_ON cannot be enabled when ANSI_NULL_DFLT_OFF is enabled.

The bit positions in this option match those in @@OPTIONS. Each connection has its own @@OPTIONS variable. When logging into SQL Server, a user receives a default environment that specifies the @@OPTIONS value equal to the config_value. SET statements for several options will affect the value in @@OPTIONS.

For more information about user options, see the SET Statement, earlier in this document.

For information about bit positions, see @@OPTIONS Global Variable earlier in this document.

Remarks

Generally, Windows NT does not guarantee that any thread in a process will run on a given processor. A thread may migrate from processor to processor, which causes reloading of the the processor's cache. Under heavy system loads, specifying which processor should run which thread can improve performance by reducing the reloading of processor cache. The association between a processor and a thread is called processor affinity.

Processor affinity is determined by using an affinity mask. An affinity mask is a bit mask in which each bit represents a processor. By setting a bit that represents a processor to 1, that processor is selected for thread assignment. An affinity mask of 0, the default, specifies that SQL Server should not set the thread's affinity and instead should allow normal Windows NT scheduling algorithms to apply. A non-zero value is interpreted as a bit mask that specifies the processors eligible for selection.

By using the affinity mask option, symmetric multiprocessor (SMP) systems with more than four microprocessors operating under heavy load offer the best prospects for a performance increase. The affinity mask option can exclude SQL Server activity from processors given specific workload assignments by the Windows NT operating system. Excluding SQL Server threads from running on particular processors helps evaluate the system's handling of NT-specific processes. For example, to evaluate whether an additional network interface card (NIC) increases performance or to assess NIC performance with increasing loads, use the affinity mask option.

Before applying the affinity mask option to a computer system, however, consider that Windows NT assigns all I/O handling to processor 0, the first processor in the system. Changes in disk I/O, for example, will be reflected in the usage level of processor 0. Windows NT assigns delayed process call (DPC) activity associated with NICs to the highest numbered processor in the system. In systems with more than one installed and active NIC, each additional card's activity is assigned to the next higher numbered processor. For example, in an eight-processor system with one NIC, Windows NT assigns I/O to processor 0 and DPCs to processor 7. The same eight-processor system with two NICs will have I/O assigned to processor 0 and DPCs for each NIC assigned to processor 7 and to processor 6.

Note  Use either the WPERF.EXE utility included in the Windows NT Resource Kit or the SQL Server Performance Monitor to view and analyze individual processor usage.

For example, if processors 1, 2, and 5 are selected as available with bits 1, 2, and 5 set to 1, a hexadecimal value of 0x13 or the decimal equivalent of 19 is specified. Number the bits from the right to left. The right-most bit is bit 1. Set bits 1, 2, and 5 (the first, second, and fifth bits) to 1. The number calculated from setting the specified bits is binary 00010011, which is decimal 19 or hexadecimal 0x13.

These are affinity mask options for an eight-processor system.

Decimal  value	Binary bit mask	Allow SQL Server threads on processor(s)
1	00000001	0
3	00000011	0 and 1
7	00000111	0, 1, and 2
15	00001111	0, 1, 2, and 3
31	00011111	0, 1, 2, 3, and 4
63	00111111	0, 1, 2, 3, 4, and 5
126	01111110	1, 2, 3, 4, 5, and 6 (isolates SQL Server activity from I/O and DPC processors)
127	01111111	0, 1, 2, 3, 4, 5, and 6 (isolates SQL Server activity from DPC processor only)
254	11111110	1, 2, 3, 4, 5, 6, 7 (isolates SQL Server activity from I/O processor only)
Because using SQL Server processor affinity is a specialized operation, it is recommended that SQL Server processor affinity be used only when necessary. In most cases, the Windows NT default affinity provides the best performance. Unlike earlier releases of SQL Server, if a config_value is 0, defaults will not be automatically reapplied.

Important  After using sp_configure, the system administrator must execute the RECONFIGURE statement to install the changed value.

Examples

A.	Enable ANSI_WARNINGS and IMPLICIT_TRANSACTIONS

This example enables ANSI warnings (ANSI_WARNINGS) and implicit transaction (IMPLICIT TRANSACTIONS) options and disables all the others.

sp_configure 'user options', 10

B.	Define Timeout Period

This example defines a timeout period of 90 minutes for server-to-server connections.

sp_configure 'remote conn timeout', 90

C.	Set Processor Affinity Mask

This example sets processors 1, 2, 3, and 4 as available for threads. Each bit in the decimal represents a processor, so 15 = 0xf =1111(binary) meaning processors 1, 2, 3, and 4. You can also pass 0xf as the affinity mask argument.

sp_configure 'affinity mask', 15

D.	Set Bits for ANSI Compatibility

This example sets all bits necessary for ANSI-level compatibility.

sp_configure 'user options', 1534

Permission

All users in the users group can execute this procedure with no parameters, or with only one parameter, to obtain the current parameter value(s). Only system administrators can use this stored procedure with two parameters.


sp_dboption
sp_dboption (version 6.5)

Syntax

sp_dboption [ dbname , 'optname' ] [ , {TRUE | FALSE } ]

Displays or changes the database options.

In earlier releases of SQL Server, omitting the optname parameter qualifier (true or false) resulted in a runtime error. In SQL Server 6.5, if the optname parameter is not qualified by true or false, the current setting of the optname option specified is returned.

For additional syntax information for sp_dboption, see the Microsoft SQL Server Transact-SQL Reference.

Remarks

The sp_dboption stored procedure returns current settings if the optname parameter setting is omitted. Otherwise, sp_dboption functions as in earlier releases.

Example

This example returns the current setting for the published column from the pubs database.

sp_dboption pubs, 'published'

This is the results set:

OptionName             Current Setting

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

published              off

Second example:

sp_dboption pubs, 'published', false


sp_dropwebtask
sp_dropwebtask (version 6.5)

Deletes a previously defined web task. The task to be deleted is identified by the output filename, by the procedure name, or by both parameters.

Syntax

sp_dropwebtask {@procname = procname= | @outputfile = outputfile= | @procname = procname=, @outputfile = outputfile=}

where

@outputfile

Specifies the name of the web task to be deleted. The outputfile variable is of varchar datatype and has a maximum of 255 characters.

@procname

Specifies the name of the web task procedure to delete. The named procedure describes the query for the web task. The procname variable is of varchar datatype and has a maximum of 28 characters.

Remarks

This stored procedure must be executed in the database specified in the @dbname parameter of sp_makewebtask.

Important  The sp_dropwebtask, sp_makewebtask, and sp_runwebtask stored procedures can be run only on Microsoft SQL Server version 6.5 databases. Running these procedures on a database of a previous version will return errors.

For more information about creating and running a web task, see sp_makewebtask and sp_runwebtask later in this document.

Example

This example deletes a web task by using the @outputfile of C:\WEB\MYFILE.HTML and an @procname of MYHTML.

sp_dropwebtask 'C:\WEB\MYFILE.HTML', MYHTML

Permission

The user deleting the web task must be the owner of the specified procedure.


sp_fallback_activate_svr_db
sp_fallback_activate_svr_db (version 6.5)

Activates fallback support for the specified fallback enrolled databases for a primary server.

Syntax

sp_fallback_activate_svr_db [PrimarySvrName] [, DBNamePattern]

where

PrimarySvrName

Specifies the name of the primary server for which the local fallback server should provide fallback support. Executing this procedure without a PrimarySvrName (the default) indicates that there is one primary server with databases enrolled and to use the implied primary server name.

DBNamePattern

Specifies the name pattern of a database for which to activate the fallback support. The default is '%'. This parameter can be any pattern appropriate for the LIKE operator.

For more information about the LIKE operator, see Wildcard Characters in the Microsoft SQL Server Transact-SQL Reference.

Remarks

A database can be enrolled on its primary server and on its fallback support server for the same primary server. In the case where the primary server acts as both a primary server and fallback support server this enrollment strategy can be useful for load balancing schemes.

This procedure should be executed on the fallback server. If the hardware fallback changes are in place, then the activated databases is available approximately two seconds after this procedure is executed.

Permission

Only the system administrator can execute this procedure.

Tables Used

master.dbo.spt_fallback_usg

See Also

sp_addremotelogin	sp_helplogins
sp_addserver	sp_serveroption
sp_change_users_login


sp_fallback_deactivate_svr_db
sp_fallback_deactivate_svr_db (version 6.5)

Deactivates fallback support for the specified activated databases on a primary server. Deactivation leaves the databases enrolled.

Syntax

sp_fallback_deactivate_svr_db [PrimarySvrName]
[, DBName Pattern]

where

PrimarySvrName

Specifies the name of the primary server for which the local fallback server should stop active fallback support. Executing this procedure without a PrimarySvrName (the default) indicates there is one primary server with databases enrolled and to use the implied primary server name.

DBNamePattern

Specifies the name pattern of a database for which to activate the fallback support. The default is '%'. This parameter can be any pattern appropriate for the LIKE operator.

For more information about the LIKE operator, see Wildcard Characters in the Microsoft SQL Server Transact-SQL Reference.

Remarks

This procedure should be executed on the fallback server.

Permission

Only the system administrator can execute this procedure.

Tables Used

master.dbo.spt_fallback_usg

See Also

sp_addremotelogin	sp_helplogins
sp_addserver	sp_serveroption
sp_change_users_login


sp_fallback_enroll_svr_db
sp_fallback_enroll_svr_db (version 6.5)

Enrolls a primary server's database into the staging tables of a fallback server, which prepares the server for future fallback support activation.

Syntax

sp_fallback_enroll_svr_db {PrimarySvrName, DBName}

where

PrimarySvrName

Specifies the name of the server that is ready to provide fallback support. If no value is specified, the implied value is the fallback server that is defined on the primary server.

DBName

Specifies the name of a database to enroll in fallback support. This database will be enrolled on the remote fallback server and must be owned by the local or primary server.

Remarks

This procedure should be run locally on the fallback server. The primary server must already be locally defined on the fallback server.

When a server enrolls its own active database and uses itself as the fallback server, the enrolled database is immediately recorded as being actively supported in the spt_fallback tables. In this case, the primary server acts as its own fallback support server. This enrollment strategy can be useful for activating or deactivating a database on the primary server.

Permission

Only the system administrator can execute this procedure on the local primary server.

Tables Used

master.dbo.spt_fallback_usg

See Also

sp_addremotelogin
sp_addserver
sp_change_users_login	sp_helplogins
	sp_serveroption


sp_fallback_help
sp_fallback_help (version 6.5)

Reports about enrollments and activations for fallback support and provides integrity checking.

Syntax

sp_fallback_help [PrimarySvrNamePattern]

where

PrimarySvrNamePattern

Specifies the name of the primary server. The default is '%'. This parameter can be any pattern appropriate for the LIKE operator.

For more information about the LIKE operator, see Wildcard Characters in the Microsoft SQL Server Transact-SQL Reference.

Remarks

This procedure provides useful information only if executed on the fallback server. If a return value is greater than 0, the integrity check detects a problem.

Permission

Only the system administrator can execute this procedure on the local primary server.

Tables Used

master.dbo.spt_fallback_usg

See Also

sp_addremotelogin	sp_helplogins
sp_addserver	sp_serveroption
sp_change_users_login


sp_fallback_permanent_svr
sp_fallback_permanent_svr (version 6.5)

Establishes the local fallback support server as the sole owner of the active databases for an obsolete primary server.

Syntax

sp_fallback_permanent_svr PrimarySvrName, 1

where

PrimarySvrName

Specifies the name of an enrolled and active primary server in fallback support on the local fallback server.

1

Specifies an override. This parameter guards against an accidental execute of this procedure.

Remarks

This procedure should be run only on the fallback support server. This procedure deletes rows from spt_fallback tables. Formerly enrolled databases and databases originally stored on the local server can be distinguished only by drive letters stored in the sysdevices table in the phyname column.

Example

This example brings all active databases for the obsolete primary server MyPrimaryServer under the permanent control of the local fallback server.

sp_fallback_permanent_svr 'MyPrimaryServer', 1

Permission

Only the system administrator can execute this procedure on the local primary server.

Tables Used

master.dbo.spt_fallback_usg

See Also

sp_addremotelogin	sp_helplogins
sp_addserver	sp_serveroption
sp_change_users_login


sp_fallback_upd_dev_drive
sp_fallback_upd_dev_drive (version 6.5)

Creates cross references to the drive letters used by the primary and fallback support servers so both servers refer to the same physical drive.

Syntax

sp_fallback_upd_dev_drive PrimarySvrName, PrimaryDrive, FallbackDrive

where

PrimarySvrName

Specifies the name of the primary server that contains inactive enrolled databases.

PrimaryDrive

Specifies the drive letter found in the phyname column of the sysdevices system table. This parameter consists of one character and a colon (:) and indicates the physical drive on the primary server for enrolled devices.

FallbackDrive

Specifies the drive letter to be used by the fallback support server. This parameter consists of one character and a colon (:).

Remarks

This procedure must be executed on the fallback support server by using a direct connection to the fallback support server, or by using a remote stored procedure call to the fallback support server while connected to the primary server.

Permission

Only the system administrator can execute this procedure on the local primary server.

Tables Used

master.dbo.spt_fallback_usg

See Also

sp_addremotelogin	sp_helplogins
sp_addserver	sp_serveroption
sp_change_users_login


sp_fallback_withdraw_svr_db
sp_fallback_withdraw_svr_db (version 6.5)

Erases the enrollment of inactive databases for a primary server.

Syntax

sp_fallback_withdraw_svr_db PrimarySvrName [, DBNamePattern]

where

PrimarySvrName

Specifies the name of a primary server that contains inactive enrolled databases.

DBNamePattern

Specifies the name pattern for enrolled databases. The default is '%'. This parameter can be any pattern appropriate for the LIKE operator.

For more information about the LIKE operator, see Wildcard Characters in the Microsoft SQL Server Transact-SQL Reference.

Remarks

This procedure must be executed on the fallback support server by using a direct connection to the fallback support server, or by using a remote stored procedure call to the fallback support server while connected to the primary server.

When executing this procedure for troubleshooting problems with fallback support, supply only PrimarySvrName so DBNamePattern defaults to '%' for all enrolled databases on a primary server.

Permission

Only the system administrator can execute this procedure on the local primary server.

Tables Used

master.dbo.spt_fallback_usg

See Also

sp_addremotelogin	sp_helplogins
sp_addserver	sp_serveroption
sp_change_users_login


sp_getbindtoken
sp_getbindtoken (version 6.5)

Creates a bound connection context and returns a unique identifier for the created context. This unique identifier is referred to as a bind token. This system stored procedure returns a string representation to use as a token for a shared transaction between two clients.

Syntax

sp_getbindtoken return_value OUTPUT [, @for_xp_flag]

where

return_value OUTPUT

Is the token to use to share a transaction context. This parameter can have a maximum of 255 characters and must have a varchar datatype.

@for_xp_flag

Specifies a literal constant. If equal to 1, creates a bind token that can be passed to an extended stored procedure to call back into the server.

Remarks

The bind token can be used with sp_bindsession to bind new sessions to the same transaction context. Sessions on one 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 will run correctly.

If a literal constant is not used for the @for_xp_flag parameter, you will receive the following error message:

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.

For more information about sharing a transaction context and binding connections, see sp_bindsession.

Examples

A.	Obtain 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 results set:

Token

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

\0]---5^PJK51bP<1F<-7U-]ANZ

Note  Your bind token name will differ from the results displayed above.

B.	Use @for_xp_flag Parameter

This example specifies a literal 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

For more information about binding connections, see sp_bindsession, earlier in this document.


sp_helplogins
sp_helplogins (version 6.5)

Provides information about current logins and the associated users.

Syntax

sp_helplogins [LoginNamePattern]

where

LoginNamePattern

Is a login username. This value can be any pattern understandable to the LIKE operator. The default is '%'.

For more information about the LIKE operator, see Wildcard Characters in the Microsoft SQL Server Transact-SQL Reference.

Remarks

This procedure reports information on logins. The output consists of two reports. The first report contains information about each login name, including whether a login is associated with a remote login. The second report contains information about users and aliases associated with each login name. The second report gathers information from all databases.

In most cases the width of each column in the output reports is reduced to the length of the longest data value under each column. No data values are truncated.

Example

This example reports on all logins that begin with repl.

sp_helplogins 'repl%'

LoginName       SUID   DefDBName DefLangName AUser ARemote

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

repl_publisher  16382  master    us_english  NO    no

repl_subscriber 16383  master    us_english  yes   no

(2 row(s) affected)

LoginName        DBName          UserName         UserOrAlias

---------------  --------------  ---------------  ------------
repl_subscriber  master          repl_subscriber  User
repl_subscriber  msdb            repl_subscriber  User

(2 row(s) affected)

Note  In the first report of Logins, repl_publisher has an AUser of NO, which indicates that it is unusual not to be a user.

Permission

Only the system administrator can execute this procedure.


sp_helprotect
sp_helprotect (version 6.5)

Reports on user permissions for an object and includes SELECT, execute, and access permissions for a given object.

For additional syntax information for sp_helprotect, see the Microsoft SQL Server Transact-SQL Reference.

Syntax

sp_helprotect [OwnerObject_Statement_Name_Pattern [, GranteeName [, GrantorName [, PermissionsCategories]]]]

where

OwnerObject_Statement_Name_Pattern

Is the name of an object and/or statement for which permissions can be granted: the parameter PermissionCategories determines which permissions will be granted to the object or statement. The name can be any pattern understandable to the LIKE operator.

For more information on the LIKE operator, see Wildcard Characters in the Microsoft SQL Server Transact-SQL Reference.

An object name of 'tb217[_]Customer' can be used to focus on one table. For a broader report use 'tb%' or '%cust%'. An owner name can be used to qualify the object name, such as in 'dbo.vwBudget' or 'Patia%.pc%'. A database name cannot be used as a qualifier in this parameter; instead, rely upon the current database context. The default is '%'.

GranteeName

Is the name of the person who has permission to access the database object. This value can be any pattern that is understood by the LIKE operator (NULL is not accepted). As the GRANT statement syntax implies, users, guest, groups, and public can all be grantees. The default is '%'.

GrantorName

Is the name of the grantor to the database object. The grantor is anyone who has authority to grant another person (the grantee) access to an object. This value can be any pattern that is understood by the LIKE operator (NULL is not accepted). Only members of the users group can be grantors. The default is '%'.

PermissionsCategories

Is a string of single letters that determines which categories will be reported. This determines the interpretation of the first parameter. These are the supported categories of permissions.

Categories	Permissions
O	Object.
S	Statement.
OS	All categories are available (the default).
Remarks

The output report is sorted by permission category, owner, object, grantee, grantor, protection type category, protection type, action, and column sequential ID.

These are the special values that can appear in the report.

Value	Description
(All)	Indicates that the privilege covers all current columns of the object.
(New)	Indicates that the privilege covers any new columns that might be altered (by using the ALTER statement) on the object in the future.
(All+New)	Indicates a combination of All and New.
The width of each column in the output report will be reduced to the length of the longest data value under each column. No data values are truncated.

If this procedure completes successfully, 0 is returned. If an error occurs, 1 is returned.

Example

This example reports all permissions except those for DBO objects that begin with the letter T and grantor names that begin with the letter d.

sp_helprotect 'dbo.[^Tt]%',default,'[^d]%','O'

Permission

Execute permission is granted to the public group during installation or upgrade.


sp_helpserver
sp_helpserver (version 6.5)

Provides the server name, the server's network name, the server's replication status, and the server's identification number. dsn or fallback are possible return values for status.

For additional syntax information for sp_helpserver, see the Microsoft SQL Server Transact-SQL Reference.

Syntax

sp_helpserver [server_name]

where

server_name

Specifies the server for which to display information. When no server_name is supplied, provides information about all servers of both types stored in master.dbo.sysservers.

Remarks

This procedure returns the server name, network name, status, and ID. Status can be:

dist	Distribution server
dpub	Remote publisher to this distribution server
dsn	DSN server
fallback	Fallback server
pub	Publication server
rpc	Remote server
sub	Subscription server
A server can have more than one status.

This procedure is useful if you have access to a server as a DSN through ODBC.

Permission

Execute permission defaults to the public group.


sp_help_revdatabase
sp_help_revdatabase (version 6.5)

Analyzes an existing database and creates a script that can be used to replicate the database structure on another server.

Syntax

sp_help_revdatabase [DBNamePattern]

where

DBNamePattern

Specifies a database name pattern. The name pattern must adhere to the LIKE operator standards for string arguments. The default is '%' (all databases will be affected).

For more information about the LIKE operator, see Wildcard Characters in the Microsoft SQL Server Transact-SQL Reference.

Remarks

The purpose of the sp_help_revdatabase stored procedure is to ease the task of building a database by ensuring the lpage (logical page) and segmap (segment map) structures are compatible with an existing database.

The output of this system stored procedure is a script of CREATE/ALTER DATABASE statements that match an existing database. The output also contains any necessary invocations of sp_logdevice to update sysusages.segmap. For every row in the sysusages system table, sp_help_revdatabase produces an ALTER DATABASE statement. With fewer rows in the sysusages system table, fewer ALTER DATABASE statements are produced by sp_help_revdatabase and fewer rows in sysusages make it easier to verify compatible logical page and segment map combinations between databases.

The database and device names in the generated script output can be edited in preparation for creating another database with compatible lpage and segmap structures. The output script might be unable to achieve compatible lpage and segmap structures when any fragment size in the original database is not an even multiple of 512 2K pages. When this procedure detects fragments with a size not evenly divisible by 512, sp_help_revdatabase includes in the output a cautionary comment indicating that the ALTER size in 1 MB units represents a rounded-up representation of the size as recorded in 2K pages in sysusages. You can avoid this problem if you code size-parameter values in even multiples of 512 2K pages when you issue DISK INIT statements.

System administrators sometimes load a database or table backup file from a production database into a database on another server. Requirements for successful cross-database dump and load activities are documented under the LOAD statement in the Microsoft SQL Server Transact-SQL Reference. One requirement is that the two databases have compatible lpage and segmap column information in the sysusages table. The target database must be created so the segmap for each range of logical pages (lpage) is compatible with the same information in the dumped database.

Important  If the target and destination databases have different segmap structures, dumped or loaded databases can experience data access problems.

Two databases have compatible lpage and segmap structures if for every given lpage number they have the same segmap value. Fragment sizes and sequences are not an issue. If one database is larger than the other, some of the larger database's lpage numbers will not exist for the smaller database. A smaller database can be loaded into a larger database, but a larger database cannot be loaded into a smaller database.

For more information about logical pages, see the Microsoft SQL Server Administrator's Companion.

For more information about preparing to run sp_help_revdatabase, see sp_coalesce_fragments, earlier in this document.

For more information about altering a database, see the ALTER DATABASE statement in the Microsoft SQL Server Transact-SQL Reference.

For more information about performing a database load, see the LOAD statement in the Microsoft SQL Server Transact-SQL Reference.

For more information about performing a database backup, see the DUMP statement in the Microsoft SQL Server Transact-SQL Reference.

Example

This example shows the results of running sp_help_revdatabase after executing sp_coalesce_fragments. Since sp_coalesce_fragments does not generate any output, this example only shows the output from running sp_help_revdatabase.

SELECT

'dbname'=substring(db_name(ug.dbid),1,10)

,ug.segmap,ug.lstart -- page number within a database

,ug.size,ug.vstart -- page number within dv

,'(vstart+size)' = ug.vstart + ug.size

,'device'=substring(dv.name,1,10)

FROM

master.dbo.sysusages ug,master.dbo.sysdevices dv

WHERE ug.vstart between dv.low and dv.high	 AND

dv.status & 2 = 2 --physical disk

AND

db_name(ug.dbid) in ('DB1','DB22','db_junk3')

ORDER BY ug.vstart

This is the results set:

dbname segmap lstart size vstart    (vstart+size) device

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

DB5         3      0 1024 520093696     520094720 dv9

DB66        3      0 1536 520094720     520096256 dv9

DB5         3   1024  512 520096256     520096768 dv9

DB5         4   1536  512 536870912     536871424 dv8

DB66        4   1536 1024 536871424     536872448 dv8

DB5         4   2048  512 536872448     536872960 dv8

DB777       3      0 1024 687865856     687866880 dv7

DB777       3   2048  512 687866880     687867392 dv7

DB777       4   1024 1024 704643072     704644096 dv6

This is the output from running sp_help_revdatabase:

-- This is the command for executing sp_help_revdatabase

EXECUTE sp_help_revdatabase

-- This is the output generated by executing sp_help_revdatabase

CREATE Database DB5 on dv9 = 2 --  2 Mb = 1024 2Kb pages

go

ALTER  Database DB5 on dv9 = 1

go

ALTER  Database DB5 on dv8 = 1

go

Execute sp_logdevice DB5,dv8

go

ALTER  Database DB5 on dv8 = 1

go

Execute sp_logdevice DB5 ,dv8

go

-- - - - - -

CREATE Database DB66  on dv9 = 3

go

ALTER  Database DB66  on dv8 = 2

go

Execute sp_logdevice DB66 ,dv8

go

-- - - - - -

CREATE Database DB777 on dv7 = 2

go

ALTER  Database DB777 on dv6 = 2

go

Execute sp_logdevice DB777 ,dv6

go

ALTER  Database DB777 on dv7 = 1

The output this procedure generated differs for databases DB5 and DB66. However, both of these databases can be safely loaded with a dump from the other. However, DB777 cannot be involved with dump and load activity along with DB5 or DB66. The following SELECT statement example shows the lpage and segmap combinations for all of these databases after running sp_coalesce_fragments.

SELECT

 'DBName'=substring(db_name(ug.dbid),1,6),

'FromLPage'=ug.lstart,

'ToLPage'  =ug.lstart + ug.size - 1,

ug.segmap

FROM

 master.dbo.sysusages ug

ORDER BY

 DBName,FromLPage

DBName FromLPage   ToLPage     segmap

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

DB5              0        1023           3

DB5           1024        1535           3

DB5           1536        2047           4

DB5           2048        2559           4

DB66             0        1535           3

DB66          1536        2559           4

DB777            0        1023           3

DB777         1024        2047           4

DB777         2048        2559           3

Note  lpage 1029 corresponds to a segmap of 3 for databases DB5 and DB66, but to a segmap of 4 for DB777. Because the lpage and segmap combinations are in agreement between DB5 and DB66, dump and load activity between the two databases is safe. This dump and load activity is safe even though DB5 and DB66 have different numbers of fragments after sp_coalesce_fragments has been run.

This procedure does not update or change anything on the server.

Permission

Execute permissions default to permissions of the public group.


sp_makewebtask
sp_makewebtask (version 6.5)

Creates a task that produces an HTML document. This HTML document contains data returned by executed queries.

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

@outputfile

Specifies the location of the generated HTML file on the computer that is running SQL Server and can be a UNC name if the file is to be created on a remote computer. This parameter is required and must be unique for each task created with sp_makewebtask. The outputfile variable is of varchar datatype and has a maximum of 255 characters.

@query

Specifies the query to be run. This parameter is required. 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 will result in multiple tables being displayed in the @outputfile. The @query parameter is of text datatype.

@fixedfont

Specifies that the query results be displayed in a fixed font (1) or a proportional font (0). Fixed font (1) is the default. The fixedfont variable is of tinyint datatype.

@bold

Specifies that the query results be displayed in a bold font (1) or non-bold font (0). Non-bold (0) is the default. The bold variable is of tinyint datatype.

@italic

Specifies that the query results be displayed in an italic font (1) or non-italic font (0). Non-italic (0) is the default. The italic variable is of tinyint datatype.

@colheaders

Specifies that the query results be displayed with column headers (1) or no column headers (0). Column headers (1) is the default. The colheaders variable is of tinyint datatype.

@lastupdated

Specifies whether the generated HTML document displays a Last Updated: timestamp indicating the last updated date and time (1) or no timestamp (0). Timestamp (1) is the default. The timestamp appears one line before the query results in the HTML document. The lastupdated variable is of tinyint datatype.

@HTMLHeader

Specifies the HTML formatting code for displaying the text contained in the @resultstitle variable. The HTMLHeader variable is of tinyint datatype. These are the values.

Value	HTML formatting code
1	H1
2	H2
3	H3
4	H4
5	H5
6	H6
@username

Specifies the username for executing the query. The default is the current user. The username variable is of varchar datatype and has a maximum of 30 characters. The sa or dbo can specify another @username.

@dbname

Specifies the database name to run the query on. If a database name is not given, @dbname defaults to the current database. The dbname variable is of varchar datatype and has a maximum of 30 characters.

@templatefile

Specifies the path of the template file used to generate the HTML document. The template file contains information about formatting characteristics for HTML documents and contains the tag <%insert_data_here%>, which indicates the position to add the query results in an HTML table. There are no spaces between the less than sign (<) and the "%i" of "%insert" and between the "e%" of "here%" and the greater than sign (>). The templatefile variable is of varchar datatype and has a maximum of 255 characters.

There are two ways to specify the location of the results of a query in a template file:

1.	Include the tag <%insert_data_here%>, which indicates the position to add the query results in an HTML table. There are no spaces between the less than sign (<) and the "%i" of "%insert" and between the "e%" of "here%" and the greater than sign (>).

2.	Specify a complete row format between the keywords <%begindetail%> and <%enddetail%> including <TR>, </TR>, <TD>, and </TD> HTML tags. For each column to display in the results set, include the tag <%insert_data_here%> inside the row format keywords. Specifying the complete row format produces a more precise layout of the results set. When used with this complete row format, @colheaders is ignored.

If @templatefile is specified, the following parameters are ignored when the HTML file is generated:

@bold	@singlerow
@fixedfont	@tabborder
@HTMLHeader	@table_urls
@italic	@URL
@lastupdated	@url_query
@reftext	@webpagetitle
@resultstitle
@webpagetitle

Specifies the title of the HTML document. The default is SQL Server Web Assistant. The webpagetitle variable is of varchar datatype and has a maximum of 255 characters.

@resultstitle

Specifies the title displayed above the query results in the HTML document. The default title is Query Results. The resultstitle variable is of varchar datatype and has a maximum of 255 characters.

@URL

Specifies a hyperlink to another HTML document. The hyperlink is placed after the query results and at the end of the HTML document. If this parameter is specified, @reftext must also be specified, and @table_urls and @url_query cannot be specified. The URL variable is of varchar datatype and has a maximum of 255 characters.

Important  If @table_urls = 1, then @url_query must be included to specify the query to be executed for retrieving hyperlink information, and @URL and @reftext cannot be specified. Information is specified either in @URL and @reftext, or in @url_query and @table_urls.

@reftext

Specifies the hyperlink that describes to what HTML document the hyperlink should take the user. The hyperlink text describes the destination and the hyperlink address comes from the URL in the @URL parameter. The reftext variable is of varchar datatype and has a maximum of 255 characters.

@table_urls

Specifies whether hyperlinks will be included on the HTML document (1) and whether the hyperlinks will come from a SELECT statement executed on Microsoft SQL Server. A value of 0 (the default) indicates that there is no query that will generate hyperlinks for the HTML. @URL and @reftext may still be specified for a single hyperlink. A value of 1 indicates that a list of hyperlinks will be created by using @url_query. The table_urls variable is of tinyint datatype.

Important  If @table_urls = 1, then @url_query must be included to specify the query to be executed for retrieving hyperlink information, and @URL and @reftext cannot be specified. Information is specified either in @URL and @reftext, or in @url_query and @table_urls.

@url_query

Specifies the SELECT statement to create the URL and its hyperlink text. URLs and hyperlink text come from a SQL Server table. With this parameter, it is possible to generate multiple URLs with associated hyperlinks. Use @url_query with @table_urls. The url_query variable is of varchar datatype with a maximum of 255 characters. The url_query variable must return a results 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

Specifies when to run the task that creates the HTML document. The whentype variable is of tinyint datatype. These are the possible values.

Value	Description
1	Create page now. The web task will be created, executed immediately, and deleted immediately after execution. This is the default.
2	Create page later. The stored procedure for creating the HTML document will be created immediately, but execution of the web task is deferred until the date and time specified by @targetdate and @targettime (optional). If no @targettime is specified, the web task will be executed at 12:00 a.m. @targetdate is required when @whentype = 2. This web task will be deleted automatically after the targeted date and time has passed.
3	Create page every n day(s) of the week. The HTML document will be created on day(s) specified in @dayflags and at the time specified by @targettime (optional), beginning with the date in @targetdate. If no @targettime value is specified, the default is 12:00 A.M. The @targetdate parameter is required when @whentype = 3. The day(s) of the week are specified in the @dayflags parameter. More than one day of the week can be specified with the @dayflags parameter. Web tasks created with @whentype = 3 will not be deleted automatically and continue to run on the specified day(s) of the week until the user deletes them by using 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 (optional). If no @targettime is specified, the Web task will be executed at 12:00 A.M. The @targetdate parameter is required in this case. The task will run automatically every n minutes, hours, days, or weeks as specified by the @numunits and @unittype parameters. The tasks will run until the user deletes them by using 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 by using sp_dropwebtask.
6	Create page now and later. The HTML document is created immediately and re-created according to @whentype = 2.
7	Create page now and every n day(s) of the week. The HTML document is created immediately and re-created according to @whentype = 3, except no @targetdate is required.
8	Create page now and periodically thereafter. The HTML document is created immediately and re-created according to @whentype = 4, except no @targetdate is required.
9	Create page now and upon request. The HTML document is created immediately and re-created according to @whentype = 5. The task must be deleted manually.
@targetdate

Specifies the date the page should be built. The format is YYYYMMDD. In @whentype > 3 cases where @targetdate is important but not supplied, the current date is used. For @whentype = 2 (later), 3 (dayofweek), 4 (periodic), and 6 (now and later), the @targetdate parameter is required. The targetdate variable is of int datatype.

@targettime

Specifies the time the HTML document should be created. When a starting time is important but not supplied, 12:00 A.M. is the default. The format is HHMMSS. The targettime variable is of int datatype.

@dayflags

Specifies what days to update the HTML document. To specify certain days, add the values together. To specify Monday and Thursday, for example, use @dayflags = 18. The dayflags variable is of tinyint datatype. This parameter is required for @whentype = 3 (dayofweek), @whentype = 7 (now and dayofweek); and in cases in which @whentype = 4 (periodic) and @whentype = 8 (now and periodic) where the @unittype = 3 (weeks). These are the values and their descriptions.

Value	Day of the week
1	Sunday
2	Monday
4	Tuesday
8	Wednesday
16	Thursday
32	Friday
64	Saturday
@numunits

Specify how often to update the HTML document. Values range from 1 to 255. This parameter is used only when @whentype = 4 (periodic) or @whentype = 8 (now and periodically thereafter). For example, if @whentype = 4, @numunits = 6, and @unittype = 1 (hours), the specified HTML document will be updated every six hours. The numunits variable is of tinyint datatype.

@unittype

Specifies how often the HTML document should be updated for @numunits = 4 (periodic) or @whentype = 8 (now and later). Use 1 (hours), 2 (days), 3 (weeks), or 4 (minutes). The unittype variable is of tinyint datatype.

@procname

Specifies the procedure or task name for the HTML document. If no @procname is specified, the procedure name generated by sp_makewebtask is in the form of Web_YYMMDDHHMMSS<spid>. If it is user-specified, the procedure name must meet the conditions for valid procedure names and the procedure name must be unique. The procname variable is of varchar datatype and has a maximum of 28 characters.

@maketask

Specifies whether a task should be created to execute an internal stored procedure that generates an HTML document. The default is to build the task (1). A value of 0 creates the stored procedure. The maketask variable is of tinyint datatype.

@rowcnt

Specifies the maximum number of rows to display in the generated HTML document. The default is to specify that all rows that satisfy the given query will be displayed in the HTML document (0). The rowcnt variable is of int datatype.

@tabborder

Specifies whether a border should be drawn around the results table (1, the default) or no border should be drawn around the results table (0). The taborder variable is of tinyint datatype.

@singlerow

Specifies whether the results are to be displayed as one row per page. If @singlerow is 0 (the default) all results appear on the same page and in the same table. With a value of 1, @singlerow causes a new HTML page to be generated for every qualifying row in the results 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 filename, by using @singlerow = 1, pages are called web1.html, web2.html, and so on. The singlerow variable is of tinyint datatype.

@blobfmt

Specifies whether all columns of text or image datatypes should be embedded in the same results page (NULL, the default) or whether these fields should be saved in another page and linked to the main HTML document by an URL. To place the text or image data in a separate HTML page, use the following format:

"%n% FILE=output_filename TPLT=template_filename
URL=url_link_name..."

where

n

Is the column number in the results list corresponding to a text field, and n+1 is the URL hyperlink text to the separate text or image HTML file. If a template_filename is provided, the <%insert_data_here%> marker should be used to indicate the data insertion point.

Output filenames end with a number indicating successive rows similar to @singlerow. The output_filename parameter is required, but the template_filename and url_link_name parameters are optional. The FILE output_filename is the full path to the output_file location. If provided, the url_link_name is the http:// link to the file that is accessible through the World Wide Web. If the url_link_name parameter is not provided, then the full physical filename preceeded with the "file:///" tag will be used as the url_link_name. The same syntax in @blobfmt ("%n% FILE=...") can be repeated for multiple text or image columns.

Note  Do not add spaces before or after the equal sign (=) and do not put filenames in quotation marks (').

The URL text is part of the results set and is always the column after the original text or image column. This URL text column will not be displayed as a separate column in the results set. The blobfmt variable is of text or image datatype.

Remarks

For scheduled tasks, all errors are reported in the Windows NT event log on the computer running SQL Server and will have a source of xpsqlweb.

'

Important  The sp_dropwebtask, sp_makewebtask, and sp_runwebtask stored procedures can be run only on Microsoft SQL Server version 6.5 databases. Running these procedures on a database of a previous version will return errors.

The SQL Server Web Assistant provides an interface for using the sp_makewebtask stored procedure.

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.

Examples

A.	Create Multiple Queries Using a Template File

This example creates an HTML document now and upon request and retrieves five book titles and prices, five author first and last names, five publisher names, and five author first and last names. In this document, placement of data is specified by the <%insert_data_here%> marker.

This is the template file:

<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.w3.org.pub/WWW/">The World Wide Web Consortium</A><P>

<A HREF = "http://www.w3.org/hypertext/WWW/MarkUp/html3/contents.html">HTML 3 specs</A><P>

<A HREF = "http://www.microsoft.com">MICROSOFT</A><P>

</BODY>

</HTML>

This is 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

This is the results 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.99</B></TD> </TR>

<TR> <TD><I> Cooking with Computers: Surreptitious Balance Sheets </I> </TD>

    <TD ALIGN=RIGHT><B> $11.95</B></TD> </TR>

<TR> <TD><I> You Can Combat Computer Stress! </I> </TD>

    <TD ALIGN=RIGHT><B> $2.99</B></TD> </TR>

<TR> <TD><I> Straight Talk About Computers </I> </TD>

    <TD ALIGN=RIGHT><B> $19.99</B></TD> </TR>

<TR> <TD><I> Silicon Valley Gastronomic Treats </I> </TD>

    <TD ALIGN=RIGHT><B> $19.99</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 NOWRAP><TT>White</TT></TD><TD NOWRAP><TT>Johnson</TT></TD></TR>

<TR><TD NOWRAP><TT>Green</TT></TD><TD NOWRAP><TT>Marjorie</TT></TD></TR>

<TR><TD NOWRAP><TT>Carson</TT></TD><TD NOWRAP><TT>Cheryl</TT></TD></TR>

<TR><TD NOWRAP><TT>O'Leary</TT></TD><TD NOWRAP><TT>Michael</TT></TD></TR>

<TR><TD NOWRAP><TT>Straight</TT></TD><TD NOWRAP><TT>Dean</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 NOWRAP><TT>White</TT></TD><TD NOWRAP><TT>Johnson</TT></TD></TR>

<TR><TD NOWRAP><TT>Green</TT></TD><TD NOWRAP><TT>Marjorie</TT></TD></TR>

<TR><TD NOWRAP><TT>Carson</TT></TD><TD NOWRAP><TT>Cheryl</TT></TD></TR>

<TR><TD NOWRAP><TT>O'Leary</TT></TD><TD NOWRAP><TT>Michael</TT></TD></TR>

<TR><TD NOWRAP><TT>Straight</TT></TD><TD NOWRAP><TT>Dean</TT></TD></TR>

</TABLE>

<HR>

<P>

<A HREF = "http://www.w3.org.pub/WWW/">The World Wide Web Consortium</A><P>

<A HREF = "http://www.w3.org/hypertext/WWW/MarkUp/html3/contents.html">HTML 3 specs</A><P>

<A HREF = "http://www.microsoft.com">MICROSOFT</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.

This is the query:

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

INSERT my_favorite_web_sites(url_def, display_text)
VALUES ('http://www.w3.org.pub/WWW/', 'The World Wide Web Consortium')

INSERT my_favorite_web_sites(url_def, display_text)
VALUES ('http://www.nasa.gov', 'NASA  Home Page')

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

This is the results set:

<HTML>

<HEAD>

<TITLE>Microsoft SQL Server Web Assistant</TITLE>

<BODY>

<H1>Query Results</H1>

<HR>

<P>

<P><TABLE BORDER=0>

<TR><TD NOWRAP><TT>But Is It User Friendly?</TT></TD><TD NOWRAP><TT>22.95</TT></TD></TR>

<TR><TD NOWRAP><TT>Computer Phobic AND Non-Phobic Individuals: Behavior Variations</TT></TD><TD NOWRAP><TT>21.59</TT></TD></TR>

<TR><TD NOWRAP><TT>Onions, Leeks, and Garlic: Cooking Secrets of the Mediterranean</TT></TD><TD NOWRAP><TT>20.95</TT></TD></TR>

<TR><TD NOWRAP><TT>Secrets of Silicon Valley</TT></TD><TD NOWRAP><TT>20.00</TT></TD></TR>

<TR><TD NOWRAP><TT>The Busy Executive's Database Guide</TT></TD><TD NOWRAP><TT>19.99</TT></TD></TR>

<TR><TD NOWRAP><TT>Straight Talk About Computers</TT></TD><TD NOWRAP><TT>19.99</TT></TD></TR>

<TR><TD NOWRAP><TT>Silicon Valley Gastronomic Treats</TT></TD><TD NOWRAP><TT>19.99</TT></TD></TR>

<TR><TD NOWRAP><TT>Prolonged Data Deprivation: Four Case Studies</TT></TD><TD NOWRAP><TT>19.99</TT></TD></TR>

<TR><TD NOWRAP><TT>Sushi, Anyone?</TT></TD><TD NOWRAP><TT>14.99</TT></TD></TR>

<TR><TD NOWRAP><TT>Cooking with Computers: Surreptitious Balance Sheets</TT></TD><TD NOWRAP><TT>11.95</TT></TD></TR>

<TR><TD NOWRAP><TT>Fifty Years in Buckingham Palace Kitchens</TT></TD><TD NOWRAP><TT>11.95</TT></TD></TR>

<TR><TD NOWRAP><TT>Is Anger the Enemy?</TT></TD><TD NOWRAP><TT>10.95</TT></TD></TR>

<TR><TD NOWRAP><TT>Emotional Security: A New Algorithm</TT></TD><TD NOWRAP><TT>7.99</TT></TD></TR>

<TR><TD NOWRAP><TT>Life Without Fear</TT></TD><TD NOWRAP><TT>7.00</TT></TD></TR>

<TR><TD NOWRAP><TT>You Can Combat Computer Stress!</TT></TD><TD NOWRAP><TT>2.99</TT></TD></TR>

<TR><TD NOWRAP><TT>The Gourmet Microwave</TT></TD><TD NOWRAP><TT>2.99</TT></TD></TR>

<TR><TD NOWRAP><TT>The Psychology of Computer Cooking</TT></TD><TD NOWRAP>n/a</TD></TR>

<TR><TD NOWRAP><TT>Net Etiquette</TT></TD><TD NOWRAP>n/a</TD></TR>

</TABLE>

<HR>

<A HREF = "http://www.microsoft.com">Microsoft Home Page</A><P>

<A HREF = "http://www.yahoo.com">http://www.yahoo.com</A><P>

<A HREF = "http://www.w3.org.pub.WWW/">The World Wide Web Consortium</A><P>

</BODY>

</HTML>

C.	Execute Multiple Queries with Single Row Mode

This example creates four 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 results set called C:\WEB\SROW1.HTM:

<HTML>

<HEAD>

<TITLE>Single row SQL Web Assistant</TITLE>

<BODY>

<H1>One row per page results</H1>

<HR>

<PRE>Last updated: Jun 5 1996  3:15PM</PRE>

<P>

<P><TABLE BORDER=1>

<TR><TH ALIGN=LEFT>title</TH><TH ALIGN=LEFT>price</TH></TR>

<TR><TD NOWRAP>But Is It User Friendly?</TD><TD NOWRAP>22.95</TD></TR>

</TABLE>

<HR>

<A HREF = "http://www.microsoft.com">Microsoft Home Page</A><P>

</BODY>

</HTML>

This is the second file of the results set called C:\WEB\SROW2.HTM:

<HTML>

<HEAD>

<TITLE>Single row SQL Web Assistant</TITLE>

<BODY>

<H1>One row per page results</H1>

<HR>

<PRE>Last updated: Jun 5 1996  3:15PM</PRE>

<P>

<P><TABLE BORDER=1>

<TR><TH ALIGN=LEFT>title</TH><TH ALIGN=LEFT>price</TH></TR>

<TR><TD NOWRAP>Computer Phobic AND Non-Phobic Individuals: Behavior Variations</TD><TD NOWRAP>21.59</TD></TR>

</TABLE>

<HR>

<A HREF = "http://www.microsoft.com">Microsoft Home Page</A><P>

</BODY>

</HTML>

This is the third file of the results set called C:\WEB\SROW3.HTM:

<HTML>

<HEAD>

<TITLE>Single row SQL Web Assistant</TITLE>

<BODY>

<H1>One row per page results</H1>

<HR>

<PRE>Last updated: Jun 5 1996  3:15PM</PRE>

<P>

<P><TABLE BORDER=1>

<TR><TH ALIGN=LEFT>au_lname</TH><TH ALIGN=LEFT>au_fname</TH></TR>

<TR><TD NOWRAP>White</TD><TD NOWRAP>Johnson</TD></TR>

</TABLE>

<HR>

<A HREF = "http://www.microsoft.com">Microsoft Home Page</A><P>

</BODY>

</HTML>

This is the fourth file of the results set called C:\WEB\SROW4.HTM:

<HTML>

<HEAD>

<TITLE>Single row SQL Web Assistant</TITLE>

<BODY>

<H1>One row per page results</H1>

<HR>

<PRE>Last updated: Jun 5 1996  3:15PM</PRE>

<P>

<P><TABLE BORDER=1>

<TR><TH ALIGN=LEFT>au_lname</TH><TH ALIGN=LEFT>au_fname</TH></TR>

<TR><TD NOWRAP>Green</TD><TD NOWRAP>Marjorie</TD></TR>

</TABLE>

<HR>

<A HREF = "http://www.microsoft.com">Microsoft Home Page</A><P>

</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:

<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.w3.org.pub/WWW/">The World Wide Web Consortium</A><P>

<A HREF = "http://www.w3.org/hypertext/WWW/MarkUp/html3/contents.html">HTML 3 specs</A><P>

<A HREF = "http://www.microsoft.com">MICROSOFT</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 results 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.99</B></TD> </TR>

</TABLE>

<P>

<HR>

<A HREF = "http://www.w3.org.pub/WWW/">The World Wide Web Consortium</A><P>

<A HREF = "http://www.w3.org/hypertext/WWW/MarkUp/html3/contents.html">HTML 3 specs</A><P>

<A HREF = "http://www.microsoft.com">MICROSOFT</A><P>

</BODY>

</HTML>

This is the second file of the results 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.95</B></TD> </TR>

</TABLE>

<P>

<HR>

<A HREF = "http://www.w3.org.pub/WWW/">The World Wide Web Consortium</A><P>

<A HREF = "http://www.w3.org/hypertext/WWW/MarkUp/html3/contents.html">HTML 3 specs</A><P>

<A HREF = "http://www.microsoft.com">MICROSOFT</A><P>

</BODY>

</HTML>

E.	Execute Query Using @blobfmt

This example executes a single query and places the information into 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.BMP', @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.bmp">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.bmp">0877</A></TD></TR>

</TABLE>

<HR>

</BODY>

</HTML>

This is the first file of the results set called 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, Massachusettes.

This is sample text data for New Moon Books, publisher 0736 in the pubs database. New Moon Books is located in Boston, Massachusettes.

This is sample text data for New Moon Books, publisher 0736 in the pubs database. New Moon Books is located in Boston, Massachusettes.

This is sample text data for New Moon Books, publisher 0736 in the pubs database. New Moon Books is located in Boston, Massachusettes.

This is sample text data for New Moon Books, publisher 0736 in the pubs database. New Moon Books is located in Boston, Massachusettes.

This is sample text data for New Moon Books, publisher 0736 in the pubs database. New Moon Books is located in Boston, Massachusettes.

This is sample text data for New Moon Books, publisher 0736 in the pubs database. New Moon Books is located in Boston, Massachusettes.

This is sample text data for New Moon Books, publisher 0736 in the pubs database. New Moon Books is located in Boston, Massachusettes.

This is sample text data for New Moon Books, publisher 0736 in the pubs database. New Moon Books is located in Boston, Massachusettes.

This is sample text data for New Moon Books, publisher 0736 in the pubs database. New Moon Books is located in Boston, Massachusettes.

This is sample text data for New Moon Books, publisher 0736 in the pubs database. New Moon Books is located in Boston, Massachusettes.

This is sample text data for New Moon Books, publisher 0736 in the pubs database. New Moon Books is located in Boston, Massachusettes.

This is sample text data for New Moon Books, publisher 0736 in the pubs database. New Moon Books is located in Boston, Massachusettes.

This is sample text data for New Moon Books, publisher 0736 in the pubs database. New Moon Books is located in Boston, Massachusettes.

This is sample text data for New Moon Books, publisher 0736 in the pubs database. New Moon Books is located in Boston, Massachusettes.

This is sample text data for New Moon Books, publisher 0736 in the pubs database. New Moon Books is located in Boston, Massachusettes.

This is sample text data for New Moon Books, publisher 0736 in the pubs database. New Moon Books is located in Boston, Massachusettes.

This is sample text data for New Moon Books, publisher 0736 in the pubs database. New Moon Books is located in Boston, Massachusettes.

This is sample text data for New Moon Books, publisher 0736 in the pubs database. New Moon Books is located in Boston, Massachusettes.

This is sample text data for New Moon Books, publisher 0736 in the pubs database. New Moon Books is located in Boston, Massachusettes.

This is sample text data for New Moon Books, publisher 0736 in the pubs database. New Moon Books is located in Boston, Massachusettes.

This is sample text data for New Moon Books, publisher 0736 in the pubs database. New Moon Books is located in Boston, Massachusettes.

This is sample text data for New Moon Books, publisher 0736 in the pubs database. New Moon Books is located in Boston, Massachusettes.

This is sample text data for New Moon Books, publisher 0736 in the pubs database. New Moon Books is located in Boston, Massachusettes.

This is sample text data for New Moon Books, publisher 0736 in the pubs database. New Moon Books is located in Boston, Massachusettes.

This is sample text data for New Moon Books, publisher 0736 in the pubs database. New Moon Books is located in Boston, Massachusettes.

This is sample text data for New Moon Books, publisher 0736 in the pubs database. New Moon Books is located in Boston, Massachusettes.

This is sample text data for New Moon Books, publisher 0736 in the pubs database. New Moon Books is located in Boston, Massachusettes.

This is sample text data for New Moon Books, publisher 0736 in the pubs database. New Moon Books is located in Boston, Massachusettes.

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

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.

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>

Permission

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 privileges to write the generated HTML document to the specified location. Only the system administrator can impersonate other users.


sp_rename
sp_rename (version 6.5)

Changes the name of a user-created object (for example, table, column, user datatype) in the current database.

For additional syntax information for sp_rename, see the Microsoft SQL Server Transact-SQL Reference.

Syntax

sp_rename oldname, newname [, COLUMN | INDEX | OBJECT | USERDATATYPE]

where

oldname

Is the name of the object to rename. The database owner or system administrator can change the name of user-created objects without using SETUSER. A fully qualified object can be specified.

newname

Is the new name for the specified object. The database owner or system administrator can change the name of user-created objects without using SETUSER. A fully qualified object name can be specified.

COLUMN | INDEX | OBJECT | USERDATATYPE]

Specifies whether the object being renamed is a column, index, object, or user-defined datatype.

Value	Definition
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 datatype added by executing sp_addtype.
Remarks

This procedure 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, consider dropping and re-creating all dependent stored procedures and views. Some patterns of renaming may confuse the behavior of the dependent objects.

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.

Caution  Using sp_rename to rename textual objects may put the new object name in the name column of the sysobjects system table and leave the previous name for the object in the text column of the syscomments system table.

Example

In this example, the database owner renames a Primary Key constraint owned by another user.

IF user_id()=1

EXECUTE sp_rename 'dab32.usr_sally.cns_tab44_pky', 'pky44', 'object'

Permission

The system administrator, the database owner, or the object owner can execute this system stored procedure.


sp_runwebtask
sp_runwebtask (version 6.5)

Executes a previously defined web task and generates the HTML document. The task to run is identified by the output filename, by the procedure name, or by both parameters.

Syntax

sp_runwebtask {@procname = procname@= | @outputfile = outputfile@= |
@procname = procname@=, @outputfile = outputfile@=}

where

@outputfile

Specifies the name of the web task to run. The outputfile variable is of varchar datatype and has a maximum of 255 characters.

@procname

Specifies the name of the web task procedure to run. The named procedure defines the query for the web task. The procname variable is of varchar datatype and has a maximum of 28 characters.

Remarks

This stored procedure must be executed in the same database specified in the @dbname parameter of sp_makewebtask.

Output produced by sp_runwebtask is the actual HTML source. You can view the source document with most word processing software.

Important  The sp_dropwebtask, sp_makewebtask, and sp_runwebtask stored procedures can be run only on Microsoft SQL Server version 6.5 databases. Running these procedures on a database of an earlier version will return errors.

Example

This example runs a web task by using the @outputfile of C:\WEB\MYFILE.HTML and an @procname of MYHTML.

sp_runwebtask @procname = MYHTML @outputfile = 'C:\WEB\MYFILE.HTML',

Permission

The user must have SELECT permissions to run the specified query.


sp_serveroption
sp_serveroption (version 6.5)

Sets server options. You can set the server as a DSN server.

For additional syntax information for sp_serveroption, see the Microsoft SQL Server Transact-SQL Reference.

Syntax

sp_serveroption [server_name, optname, {true | false}]

where

optname

Is the type of server. Can be one of these:

dist	Distribution server
dpub	Remote publisher to this distribution server.
dsn	DSN server
fallback	Fallback server
pub	Publication server
rpc	Remote server
sub	Subscription server
The default is rpc.

true | false

Specifies whether to set the option. Choose true to set the option; choose false to turn it off.

Remarks

The DSN is the ODBC data source name for the server. A DSN is a server that receives replication data through ODBC. This DSN can be accessed only through Microsoft SQL Server because replication is being used.

Example

This example identifies the ACCOUNTS server as a DSN server.

sp_serveroption ACCOUNTS, dsn, true

Permission

Only the system administrator can use this procedure to set server options.


sp_setnetname
sp_setnetname (version 6.5)

Sets the network names in sysservers to their actual network machine names for remote computers running SQL Server. Names can include hyphens and other non-alphabetic characters. This procedure can be used to enable execution of remote stored procedure calls to machines that have network names containing invalid SQL Server identifiers.

Syntax

sp_setnetname @server [ = 'server'], @netname [ = 'netname']

where

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

@netname

Is the network name of the computer to which remote stored procedure calls will be made. This name must match the Windows NT machine name, and it can include characters, such as hyphens, that are not allowed in SQL Server identifiers. In most cases, setting the @netname to the network machine name enables remote stored procedure calls to a SQL Server running on a remote machine with a name that is not legal in SQL Server.

If a DB-Library alias matching the @netname is defined on the SQL Server machine, the connection string information in that alias is used to connect to the remote SQL Server.

Remarks

Because Transact-SQL syntax does not usually recognize characters such as a hyphen in an object name, some remote stored procedure calls to Windows NT computers that have a machine name containing a hyphen can cause problems. Use this procedure to differentiate the values in sysservers.srvname versus sysservers.srvnetname.

For example, if your Windows NT Server machine name is MY-NT-PC, SQL Server Setup warns you that this computer name contains an invalid identifier, the hyphen (-). If your network system administrator requires MY-NT-PC to remain the machine name, then the system administrator can use sp_addserver and sp_setnetname to keep the server's network name MY-NT-PC while the computer's local name is another name that contains valid SQL Server identifiers.

For example:

sp_addserver 'MY_NT_PC', 'local'

sp_setnetname 'MY_NT_PC', 'MY-NT-PC'

This procedure aids replication in situations where Windows NT machines with invalid SQL Server names are involved.

Example

This example is a typical administrative sequence on the SQL Server that issues the remote stored procedure call.

EXECUTE sp_addserver 'Win_NT1'

EXECUTE sp_setnetname 'Win_NT1','Win-NT1'

EXECUTE Win_NT1.master.dbo.sp_who

Permissions

Only the system administrator can execute this procedure.


sp_tableoption

Sets option values for user-defined tables.

Syntax

sp_tableoption @TableNamePattern  [, '@OptionName'] [, '@OptionValue']

where

@TableNamePattern

Specifies the qualified or non-qualified name of a user-defined database table. This parameter can be any pattern appropriate for the LIKE operator. Use single quotation marks (') if specifying @TableNamePattern with the LIKE operator. Quotation marks are not necessary if a single tablename is specified. If a fully qualified table name, including a database name, is provided the database name must be the name of the current database.

@OptionName

Specifies a table option name. The default is NULL, which lists all available table options and the corresponding default values assigned to new tables (0 = false, 1 = true). These are the possible values for @OptionName.

@OptionName	Default	Description
insert row lock	false	Disables (false) or enables (true) the insert row locking (IRL) feature for the specified table.
pintable	false	Marks the table either as either no longer RAM-resident (false) or as RAM-resident (true).
@OptionValue

Specifies whether @OptionName is enabled or disabled. The possible values are true or false. The default is NULL, which lists the current settings for all matching tables.

Examples

A.	Enable insert row lock Option for All Tables of the Current Database

EXECUTE sp_tableoption '%.%', 'insert row lock', 'true'

B.	Disable insert row lock Option for sales Table

EXECUTE sp_tableoption 'sales', 'insert row lock', 'false'

C.	Report on insert row locking Status for All Tables of the Current Database

EXECUTE sp_tableoption '%.%', 'insert row lock'

Permissions

Only the system administrator can modify the pintable table option.

The system administrator or database owner can modify the insert row lock option for any user-defined table. Users other than the system administrator or database owner 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.


sp_who
sp_who (version 6.5)

Provides information about current SQL Server users and processes. The information returned can be filtered to return only those processes that are not idle.

For additional syntax information for sp_who, see the Microsoft SQL Server Transact-SQL Reference.

Syntax

sp_who [login_name | 'spid' | active]

where

active

Returns information on active processes. Specifying active will exclude idle processes from the report. Idle processes are sleeping and are not involved in blocking.

For more information about blocking, see the Microsoft SQL Server Administrator's Companion.

Remarks

This procedure reports information about a specific user, a specified SQL Server process, all users currently running a process, or all active processes. Executing sp_who without parameters reports which users are running what processes in all databases.

Example

A.	Display All Active Processes

sp_who active

B.	Display a Specific Process with Process ID

sp_who '10' --specifies the process_id

Permission

Execute permission defaults to the public group.


msdb Tables

In SQL Server 6.5, tables have been added to the msdb database to aid in maintaining backup information. These are the new tables.

Table name	Description
sysbackupdetail	Specifies a summary of the devices used to backup (dump).
sysbackuphistory	Specifies a summary of each backup operation (dump).
sysrestoredetail	Specifies a summary of the devices used to restore (load).
sysrestorehistory	Specifies a summary of each restore operation (load).
SQL Server automatically maintains a complete online backup and restore history in the msdb database. This information includes who performed the backup, at what time, and on which devices or files it is stored.

Backup and restore events are recorded even if they were created with custom applications or third-party tools. A Visual Basic application that calls SQL-DMO objects to perform backup and restore operations will cause the events to be logged in these tables.

After each DUMP statement is executed, a description of the dump is saved in sysbackuphistory and the dump device details are saved in sysbackupdetail as part of a single transaction.

After each LOAD statement is executed, a description of the restore is saved in sysrestorehistory and the device details are saved in sysrestoredetail. If for any reason the history cannot be written to msdb database, a message is written to the Windows NT event log and to the SQL Server error log.


sysbackupdetail
sysbackupdetail (version 6.5)

Contains a row for each device comprising a dump.

These are the columns in the sysbackupdetail table.

Column	Datatype	Description
backup_id	int	Specifies the foreign key corresponding to the sysbackuphistory record. Cannot be NULL.
device_type	smallint	Represents a device type. Cannot be NULL. These are the supported numerical values: 2  Disk 3  Floppy 5  Tape 6  Pipe +100 if backing up to a named device.
device_name	varchar(255)	Specifies the device name. Cannot be NULL.
backup_size	int	Specifies the size of the backup on this device in kilobytes.
volume_name	varchar(6)	Specifies a volume ID or label.
expiration_date	datetime	Specifies the expiration date for the volume.
Foreign Key

In the sysbackupdetail table there is a Foreign Key constraint, fk_backup_id, on the backup_id column of the sysbackuphistory table.


sysbackuphistory
sysbackuphistory (version 6.5)

Contains one row for each completed dump operation.

These are the columns in the new sysbackuphistory table.

Column	Datatype	Description
backup_id	int identity(1,1)	Specifies the primary key.
id_number	smallint	Specifies the position of the backup on the volume.
backup_type	smallint	Represents the type of backup. The supported numerical values are: 1  Database  2  Transaction  3  Table
database_name	varchar(30)	Specifies the database name.
table_owner	varchar(30)	Specifies the table owner for table backups.
table_name	varchar(30)	Specifies the table name for table backups.
operator_name	char(30)	Specifies the name of the person who performed the backup.
backup_start	datetime	Specifies the date and time of the oldest committed transaction for TRANSACTION dumps. Otherwise, specifies the date and time the dump was performed.
backup_finish	datetime	Specifies the date and time of the last committed transaction for TRANSACTION dumps. Otherwise, specifies the date and time the dump was performed.
server_sort	smallint	Specifies the sort order for the database server that performed the dump.
server_code_page	smallint	Specifies the character code page for the database server that performed the dump.
striped_backup	smallint	Specifies whether the backup is striped. These are the supported numerical values: 1  striped 0  not striped Cannot be NULL
stripe_count	smallint	Specifies the number of devices in the stripeset. Cannot be NULL.
stripe_set_name	varchar(30)	Specifies the stripeset name.
total_backup_size	int	Specifies the size of the backup in kilobytes. Cannot be NULL.
current_sequence	char(14)	Specifies the current or old sequence number. This number matches the Curseq column number returned by the LOAD HEADERONLY statement. Cannot be NULL.
new_sequence	char(14)	Specifies the new sequence number. This number matches the Newseq column number returned by the LOAD HEADERONLY statement.
Index

The clustered index, pk_backup_id, is created on the primary key, backup_id, of the sysbackuphistory table.


sysrestorehistory
sysrestorehistory (version 6.5)

Contains one row for each completed load operation. The columns match those of sysbackuphistory except that the identity column is called restore_id rather than backup_id and an additional column is added.

These are the columns in the sysrestorehistory table.

Column	Datatype	Description
restore_id	int	Specifies the foreign key that corresponds to the sysbackuphistory record.
id_number	smallint	Specifies the position of the backup on the volume.
backup_type	smallint	Represents the type of backup. These are the supported numerical values: 1  Database 2  Transaction 3  Table
source_database_name	varchar(30)	Specifies the source, original, database name. Cannot be NULL.
new_database_name	varchar(30)	Specifies the new destination database name.
table_owner	varchar(30)	Specifies the name of the person who is the owner of this specific table.
table_name	varchar(30)	Specifies the name of the table to be used for table backups.
operator_name	char(30)	Specifies the name of the person who performed the last backup.
backup_start	datetime	Specifies the date and time of the oldest committed transaction. Cannot be NULL.
backup_finish	datetime	Specifies the date and time of the last committed transaction. Cannot be NULL.
server_sort	smallint	Specifies the database server's sort order. Cannot be NULL.
server_code_page	smallint	Specifies the database server's code page. Cannot be NULL.
striped_backup	smallint	Specifies whether the backup is striped. These are the supported numerical values: 1  striped 0  not striped Cannot be NULL.
stripe_count	smallint	Specifies the number of devices in the stripeset. Cannot be NULL.
stripe_set_name	varchar(30)	Specifies the stripeset name.
total_backup_size	int	Specifies the size of the backup in kilobytes. Cannot be NULL.
current_sequence	char(14)	Specifies the current or old sequence number. This number matches the Curseq column number returned by the LOAD HEADERONLY statement. Cannot be NULL.
new_sequence	char(14)	Specifies the new sequence number. This number matches the Newseq column number returned by the LOAD HEADERONLY statement.
restore_date	datetime	Specifies the date and time that the restore operation was performed. Cannot be NULL.
Index

The clustered index pk_restore_id is created on the primary key restore_id of the sysrestorehistory table.


sysrestoredetail
sysrestoredetail (version 6.5)

Contains a row for each device that comprises a dump.

Note that the columns are the same as for sysbackupdetail except that the backup_id column is called restore_id, and it refers to the corresponding row in sysrestorehistory.

These are the columns in the sysrestoredetail table.

Column	Datatype	Description
restore_id	int	Specifies the foreign key that corresponds to the sysbackuphistory record.
device_type	smallint	Represents a device type. The supported numerical values: 2  Disk 3  Floppy 5  Tape 6  Pipe +100 if restoring from a named device. Cannot be NULL.
device_name	varchar(255)	Specifies the device or Universal Naming Convention (UNC) name.
backup_size	int	Specifies, in kilobytes, the size of the backup on this device. Cannot be NULL.
volume_name	varchar(6)	Specifies a volume ID or label.
expiration_date	datetime	Specifies the expiration date for the volume.
Foreign Key

In the sysrestoredetail table there is a Foreign Key constraint  fk_restore_id on the restore_id column of the sysrestorehistory table.


MSsubscriber_info Table
MSsubscriber_info Table (version 6.5)

A description column has been added to the distribution table MSsubscriber_info.

Column	Datatype	Description
description	varchar(255)	A description column that can hold user-generated descriptions. The description column has a maximum of 255 characters and a varchar datatype. Existing rows in the MSsubscriber_info table will initialize the description column to SQL Server 6.0.


syscolumns System Table
syscolumns System Table (version 6.5)

In SQL Server 6.5, two status bits have been added to the status column in syscolumns.

New status bits	Description
16	Indicates ANSI_PADDING was in affect when a varchar or a varbinary column was created. Indicates that trailing blanks are preserved when varchar data is updated or inserted; and that trailing zeroes are preserved when varbinary data is updated or inserted.
32	Indicates that a varchar or a varbinary column is a fixed-length datatype that accepts NULLS. varchar data is padded with blanks to the maximum length and varbinary data is padded with zeroes.


sysindexes System Table
sysindexes System Table (version 6.5)

An updatestamp column has been added to the sysindexes table.

Column	Datatype	Description
UpdateStamp	varbinary	This column is used for internal synchronization of changes to row and page counts.


sysprocesses System Table
sysprocesses System Table (version 6.5)

Columns have been added to the sysprocesses table. The sysprocesses table holds information about processes running on the SQL Server. These processes can be client processes or system processes.

These are the columns in the sysprocesses table.

Column	Datatype	Description
last_batch	char(8)	The 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.
login_time	char(8)	The time at which a client process logged into the server. For system processes, the time at which SQL Server startup occurred is stored.
nt_domain	char(30)	The Windows NT domain for the client (if using integrated security) or a trusted connection.
nt_username	char(30)	The Windows NT username for the process if (if using integrated security) or a trusted connection.
net_address	char(12)	The 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	char(12)	The 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.


sysprotects System Table
sysprotects System Table (version 6.5)

The protecttype column in sysprotects adds a new value for granting permission to grant permissions. This is referred to as GRANT WITH GRANT. The new value for GRANT WITH GRANT is 204.

The system table sysprotects now has an additional column called grantor. This column has a smallint datatype.

The sysprotects table also has a clustered index on the columns id, action, grantor, uid, and protecttype. The value of grantor defaults to that of the object owner. The create database objects privilege is NULL.

Column	Datatype	Description
protecttype	tinyint	The protecttype column can have these values: 204  GRANT_W_GRANT 205  GRANT 206  REVOKE
grantor	smallint	The user_id of the user who issued the GRANT or REVOKE permission.