The following changes should be made to the Microsoft SQL Server Transact-SQL Reference for Microsoft SQL Server 6.0.
There is a limit to the number of FOREIGN KEY constraints which is restricted by the number of unique joins between the tables involved in the join.
CASE expression
WHEN search_condition1 THEN result1
[[WHEN search_condition2 THEN result2] [...]]
-- Comment describing usage of the generic CASE expression -- WHEN search condition THEN result 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, 'Shortened Title' = CONVERT(varchar(30), title), Price = price FROM titles WHERE price IS NOT NULL ORDER BY type COMPUTE AVG(price) BY type go
IF Boolean_expression
{sql_statement | statement_block}
[ELSE
{sql_statement | statement_block}]
CREATE TABLE statements or SELECT INTO statements must refer to the same table name if the CREATE TABLE or SELECT INTO statements are used in both the IF and ELSE areas of the IF...ELSE Block.
RETURN [(integer_expression)]
Note If duplicate rows exist in the table, the CREATE TABLE command will fail.
To determine whether or not a table is contiguous, use the DBCC statement's SHOWCONTIG.
CREATE PROC[EDURE] [owner.]procedure_name[;number]
[(parameter1 [, parameter2]...[, parameter255])]
[{FOR REPLICATION WITH RECOMPILE} |
[{[WITH] | [,]} ENCRYPTION]]
[OUTPUT]
AS sql_statements
There is a limit to the number of FOREIGN KEY constraints, which is restricted by the number of unique joins between the tables involved in the join.
This example shows the generic syntax for using the IDENTITY property.
SET IDENTITY_INSERT tablename ON go DECLARE @minidentval column_type DECLARE @nextidentval column_type SELECT @minidentval = MIN(IDENTITYCOL) FROM tablename IF @minidentval = IDENT_SEED('tablename') SELECT @nextidentval = MIN(IDENTITYCOL) + IDENT_INCR('tablename') FROM tablename t1 WHERE IDENTITYCOL BETWEEN IDENT_SEED('tablename') AND MAX(column_type) AND NOT EXISTS (SELECT * FROM tablename t2 WHERE t2.IDENTITYCOL = t1.IDENTITYCOL + IDENT_INCR('tablename')) ELSE SELECT @nextidentval = IDENT_SEED('tablename') SET IDENTITY_INSERT tablename OFF
This example shows how to use the IDENTITY property on a table called image that has two columns: the first column called id_num, which is an increasing identification number, and the second column called company_name.
-- Create the image table CREATE TABLE image (id_num int IDENTITY(1,1), company_name varchar) INSERT image(company_name) VALUES ('A Company Name') INSERT image(company_name) VALUES ('Another Company Name') -- Set IDENTITY_INSERT on and utilize in image table SET IDENTITY_INSERT image ON go DECLARE @minidentval smallint DECLARE @nextidentval smallint SELECT @minidentval = MIN(IDENTITYCOL) FROM image IF @minidentval = IDENT_SEED('image') SELECT @nextidentval = MIN(IDENTITYCOL) + IDENT_INCR('image') FROM image t1 WHERE IDENTITYCOL BETWEEN IDENT_SEED('image') AND 32766 and NOT EXISTS (SELECT * FROM image t2 WHERE t2.IDENTITYCOL = t1.IDENTITYCOL + IDENT_INCR('image')) ELSE SELECT @nextidentval=IDENT_SEED('image') SET IDENTITY_INSERT image OFF
SELECT pkid = IDENTITY(int,1,1), type, name INTO #t1 FROM sysobjects WHERE type = 'U'
CREATE TRIGGER [owner.]trigger_name
ON [owner.]table_name
[WITH ENCRYPTION]
FOR {INSERT, UPDATE, DELETE}
The WRITETEXT and UPDATETEXT statements, whether logged or unlogged, do not activate a trigger.
This procedure will generate a short report of the DBCC output for all user tables within this database.
Apr[il] [19]96 15
is no longer supported.
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.
Are exact numeric datatypes that hold values from 1038 - 1 through - 1038 - 1.
Specify the binary precision with n, which must be from 1 through 15.
Storage size is 8 bytes unless n is 7 or less. If n is 7 or less, then storage size is only 4 bytes.
For example, 8 one-bit columns fit into 1 byte; 9 one-bit columns take 2 bytes.
Values in timestamp columns are not datetime data, but either binary(8) or varbinary(8) data and indicate the sequence of SQL Server activity on the row.
When image is data entered with an odd number of characters (but less than 255), it is padded with a leading zero.
SHOWCONTIG (table_id [, index_id]) |
TEXTALL [({database_name | database_id}[, 'FULL' | FAST])] |
TEXTALLOC [({table_name | table_id}[, 'FULL' | FAST])] |
To find the database_id of a database, specify the database name (db_name) in the following query:
SELECT dbid FROM sysdatabases WHERE name = 'db_name'
SHOWCONTIG (table_id [, index_id]) |
To find the database_id of a database, specify the database name (db_name) in the following query:
SELECT dbid FROM sysdatabases WHERE name = 'db_name'
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'
To find the table_id of a table, specify the table name (tbl_name) in the following query:
SELECT id FROM sysobjects WHERE name = 'tbl_name'
To find the database_id of a database, specify the database name (db_name) in the following query:
SELECT dbid FROM sysdatabases WHERE name = 'db_name'
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'
To find the table_id of a table, specify the table name (tbl_name) in the following query:
SELECT id FROM sysobjects WHERE name = 'tbl_name'
This statement allows a DLL to be unloaded without shutting down SQL Server.
If you are not careful, a large table could consume all the data cache, the server would need to be restarted, and then the table unpinned.
To understand the output of SHOW_STATISTICS, see the examples later in this topic, and the UPDATE STATISTICS statement.
To find the database_id of a database, specify the database name (db_name) in the following query:
SELECT dbid FROM sysdatabases WHERE name = 'db_name'
To find the table_id of a table, specify the table name (tbl_name) in the following query:
SELECT id FROM sysobjects WHERE name = 'tbl_name'
That is, new_size must be equal to or greater than the minimum size returned by DBCC SHRINKDB plus any number of 512K increments (each of which is 256 2K pages).
SQLPERF ({IOSTATS | LRUSTATS | NETSTATS | RASTATAS [, CLEAR]} | {THREADS} | {LOGSPACE})
Logical pages written per physical write for transaction log.
Shows the logspace percentages for all databases. This statement is meaningful only if the log is on a separate device from its database. In the output from SQLPERF (LOGSPACE), a status of 0 indicates that the log device is separate from the database device. A status of 1 indicates that the log device is on the same device as the database.
Marks the table as no longer being RAM resident; however, the pages of the table will remain in cache until they are aged out of cache (and flushed to disk, if necessary).
To find the database_id of a database, specify the database name (db_name) in the following query:
SELECT dbid FROM sysdatabases WHERE name = 'db_name'
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'
To find the table_id of a table, specify the table name (tbl_name) in the following query:
SELECT id FROM sysobjects WHERE name = 'tbl_name'
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, 75 extents (75 * 16K = 1200K) is reserved and 137 pages (or 137 * 2K = 274K) are used by data and indexes. The reserved 75 extents include objects that have been created but not yet completely populated with data. Ref pages refer to those pages that do contain actual data or index pages.
This example shows the DBCC output for each index after 1500 rows are inserted and the statistics have been updated by using UPDATE STATISTICS.
USE sales go sp_dboption 'sales', 'single user', true go DBCC SHRINKDB(sales) go Current size of database Size database can be shrunk to ------------------------ ------------------------------ 5376 1024 (1 row(s) affected) DBCC execution completed. If DBCC printed error messages, see your System Administrator.
DBCC SHRINKDB reported a minimum size of 1024 pages. Because the absolute minimum is not always necessary, shrink the sales database to a new size of 6 MB.
DBCC SHRINKDB(sales, 3072) go DBCC SHRINKDB running on database "sales"... DBCC execution completed. If DBCC printed error messages, see your System Administrator.
Datatypes that cannot be created by using the DECLARE statement are text and image datatypes.
The functionality provided is similar to that of using a correlated subquery such as a search_condition in the WHERE clause of a standard delete.
A device is an operating system file that SQL Server pre-allocates for database use.
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. Directories will not be created if they do not already exist. They must be enclosed with single quotation marks (').
If you are planning to use the new database device to create a new database, the minimum size is 1 MB (512 2K blocks).
It cannot be an existing file but the path must already exist.
Is the logical name of the database device that you want to resume mirroring on.
Note The path to the G: drive and the SQLIMAGE directory must both exist before running the DISK REMIRROR example.
Note If this statement is not run immediately after the DISK REINIT statement, DISK REFIT will fail. To see the complete recovery steps (DISK REINIT and then DISK REFIT), see the DISK REINIT statement examples.
DISK RESIZE
NAME = 'logical_device_name',
SIZE = final_size
This example increases the size of DEVICE1 from its initial size of 12 MB to 20 MB.
To drop a database in recovery (sysdatabases..status & 128 = 128), use the sp_dbremove system stored procedure.
After 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. After you drop a default from a NOT NULL column, an error message is returned when rows are added and no value is explicitly supplied. These rows are added later as part of the normal INSERT behavior.
However, the database owner and system administrator can drop any default object by specifying the owner in the DROP DEFAULT statement.
Removes user-created stored procedures or user-created procedure groups from the current database.
Removes a user-defined rule from a database.
This example unbinds and then drops the pub_id_rule.
Any view on the dropped table must be explicitly dropped by using the DROP VIEW statement.
Any view on the dropped table (dropped by using the DROP TABLE statement) must be explicitly dropped by using the DROP VIEW statement.
A multivolume dump is when several dumps are appended to a file or tape, as opposed to each dump erasing the previous dump when the WITH INIT option is used. Multivolume and tape dumps require extra control over the storage of the data that is supported with files and tapes, that is not offered when sending the data to the pipe.
However, because DUMP DATABASE does not remove the inactive portion of the log, you must first use DUMP TRANSACTION WITH TRUNCATE_ONLY to purge the log of completed transactions.
These options are used with DISK and TAPE devices only and are ignored on FLOPPY and PIPE devices.
Specifies that only the clustered index (the data itself) is to be checked for user-defined tables.
Note DBCC SHRINKDB is not disk compaction. DBCC SHRINKDB provides an estimate of the smallest amount of disk space that the entire database, including indexes and user-defined objects, can occupy. Because indexes and user-defined objects such as views and tables consume disk space, the database may occupy more disk space than the data itself occupies. DBCC SHRINKDB is aware of the presence of indexes and user-defined objects and suggests what size the database can be reduced to given the index and objects in the database.
The dump captures the state of the data as it is at any moment the statement is executed; partial transactions are reflected and will automatically roll back when the dump is loaded.
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.
In addition, the user account must be a member of the NTGATEWAY Group and must have complete TRUSTEE rights to the directory where the SQL Server database dump will be written.
EXEC sp_addumpdevice 'disk', 'disk_dev1', 'c:\\dumps\diskdev1.dmp'
Specifies the variable that stores a parameter or a return parameter.
EXEC( 'USE pubs' + ' ' +'SELECT * FROM authors')
OR
EXEC( 'USE pubs' + ' SELECT * FROM authors')
OR
EXEC('USE pubs SELECT * FROM authors')
Note In the second EXEC example, there is a space between the left quotation mark and the "S" of SELECT.
EXEC ('DROP TABLE ' + @tablename)
EXECUTE xp_cmdshell 'dir *.exe'
Returns "true" when both expressions are true.
Returns "true" when either condition is true.
All numeric values with a decimal point are treated as numeric and those values without a decimal point are treated as int.
This is a list of the results of promoted datatypes when you use Aggregate Functions.
Datatype | SUM or AVG is of datatype |
---|---|
tinyint | int |
smallint | int |
int | int |
smallmoney | money |
money | money |
real | float |
float | float |
decimal | more precise decimal, if necessary |
numeric | more precise numeric, if necessary |
Returns a four-character (SOUNDEX) code to evaluate the similarity of two strings. The SOUNDEX function converts an alpha string to a four-character code to find similar sounding words or names.
Returning the SOUNDEX for "Smith" and "Smythe" will return the same SOUNDEX result because all vowels, the letter "y," doubled letters, and the letter "h," are not included.
To enforce or remove quoted identifier and string constant resolution at the session level, use the SET QUOTED_IDENTIFIER ON statement.
Strings passed as parameters to extended stored procedures can be enclosed in single or double quotation marks, regardless of the QUOTED_IDENTIFIER setting.
If any column of the table does not have a default and does not allow null, an error is returned and the INSERT statement is rejected.
In the following example, if you try to find NULL values in columns defined as NOT NULL, SQL Server will retrieve zero rows.
CREATE TABLE t (x int NOT NULL) go INSERT INTO t VALUES (1) go SELECT * FROM t WHERE x IS NULL
IDENTITY(datatype, n1, n2)
where
You can use GROUP BY for a column or expression that does not appear in the select_list. Any column referenced in the select_list must also be referenced in the GROUP BY clause unless the column is being used in an aggregate function. Null values in the GROUP BY column are put into a single group when the GROUP BY column is also contained in the select_list.
If SELECT DISTINCT is specified, the ORDER BY items must appear in the select_list.
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.
On a query-by-query basis, displays the number of scans, the number of logical reads (pages accessed in the cache), and the number of physical reads (number of times the disk was accessed) for each table referenced in the statement. Output from this procedure displays how many buffers were introduced into the cache for a particular table during a read ahead.
Note The SQL Enterprise Manager, NET STOP, and Control Panel methods of stopping SQL Server produce the identical service control message of SERVICE_CONTROL_STOP to SQL Server.
Each of these performs a checkpoint in all databases. All committed data from data cache is flushed, and then the server is stopped.
ATTRIBUTE_ID |
ATTRIBUTE_NAME description |
ATTRIBUTE_VALUE |
---|---|---|
13 | TABLE_LENGTH Specifies the maximum number of characters for a table name. |
30 |
14 | MAX_QUAL_LENGTH Specifies the maximum length of the name for a table qualifier (the first part of a three-part table name). |
30 |
15 | COLUMN_LENGTH Specifies the maximum number of characters for a column name. |
30 |
16 | IDENTIFIER_CASE Specifies the user-defined names (table names, column names, stored procedure names) in the database (the case of the objects in the system catalogs). |
MIXED or SENSITIVE, depending upon whether SQL Server is set to case-sensitive or case-insensitive. |
17 | TX_ISOLATION Specifies the initial transaction isolation level the server assumes, which corresponds to an isolation level defined in ANSI SQL-92. |
2 |
18 | COLLATION_SEQ Specifies the ordering of the character set for this server. |
charset ID |
19 | SAVEPOINT_SUPPORT Specifies whether the underlying DBMS supports named savepoints. |
Y |
20 | MULTI_RESULT_SETS Specifies whether the underlying database or the gateway itself supports multiple results sets (multiple statements can be sent through the gateway with multiple results sets returned to the client). |
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 |
100 | USERID_LENGTH Specifies the maximum number of characters for a username. |
30 |
101 | QUALIFIER_TERM Specifies the DBMS vendor term for a table qualifier (the first part of a three-part name). |
Database |
102 | NAMED_TRANSACTIONS Specifies whether the underlying DBMS supports named transactions. |
Y |
103 | SPROC_AS_LANGUAGE Specifies whether stored procedures can be executed as language events. |
Y |
104 | ACCESSIBLE_SPROC Specifies whether in the sp_stored_procedures stored procedure, the gateway returns only stored procedures that are executable by the current user. |
Y |
105 | MAX_INDEX_COLS Specifies the maximum number of columns in an index for the DBMS. |
16 |
106 | RENAME_TABLE Specifies whether tables can be renamed. |
Y |
107 | RENAME_COLUMN Specifies whether columns can be renamed. |
Y |
108 | DROP_COLUMN Specifies whether columns can be dropped. |
N |
109 | INCREASE_COLUMN_LENGTH Specifies whether column size can be increased. |
N |
110 | DDL_IN_TRANSACTION Specifies whether DDL statements can appear in transactions. |
Returns Y if SQL Server version 6.5 or later is running and N for earlier releases. |
111 | DESCENDING_INDEXES Specifies whether descending indexes are supported. |
N |
112 | SP_RENAME Specifies whether a stored procedure can be renamed. |
Y |
113 | REMOTE_SPROC Specifies whether stored procedures can be executed through the remote stored procedure functions in DB-Library. |
Y |
500 | SYS_SPROC_VERSION Specifies the version of the catalog stored procedures currently implemented. |
Current version number |
DECLARE @result int EXECUTE @result = xp_cmdshell 'dir *.exe' IF (@result = 0) PRINT 'Success' ELSE PRINT 'Failure'
The exit code of the invoked program, 'dir *.exe' in the example above is stored in the variable @return. If @result is 0, either no exit code was returned or a 0 was returned. In the example above, 'dir *.exe' can be replaced with 'myprog.exe'.
The default is false.
[, @unread = {'true' | 'false'} OUTPUT]
Specifies that a message has not been previously read.
There are two ways to use xp_readmail:
To return the contents of the Inbox as a result set to the client either set @msg_id to NULL or do not include @msg_id. In this situation, @type can be used to read specific messages. You can specify @peek and @supress_attach as input parameters to control the way the message is read.
To read a single message from the Inbox, supply a valid @msg_id that is returned by xp_findnextmsg as an input parameter to xp_readmail. You can specify @peek and @supress_attach as input parameters to control the way the message is read. When using @peek and @supress_attach with this method, all other parameters are optional output parameters that contain specific information from the message to be read.
You can view an example of using xp_findnextmsg as an input parameter to xp_readmail by executing the following command:
sp_helptext 'sp_processmail'
When used to read a single message, xp_readmail can read message text of longer than 255 bytes in sections. Use @msg_length and @skip_bytes to read message text of longer than 255 bytes in sections. Using @skip_bytes as both an input and output parameter allows easy coding of a loop to process the entire message text. The following code shows an example of such a loop, assuming @msg_id is set to a valid message identifier returned by xp_findnextmsg:
WHILE (1=1) BEGIN EXECUTE @status = xp_readmail @msg_id = @msg_id, @message = @message OUTPUT, @skip_bytes = @skip_bytes OUTPUT, @msg_length = @msg_length OUTPUT IF @status <> 0 BREAK SELECT 'msg_id' = @msg_id, 'msg_part' = @message IF @skip_bytes = @msg_length BREAK END
The xp_sendmail extended stored procedure runs in SQL Server's security context which is a local administrator account by default. A valid user of xp_sendmail can access files for attachment to a mail message in an administrator's security context. If non-system administrator users need access to xp_sendmail and you wish to guard against unsecured access to attachment files, the system administrator can create a stored procedure that calls xp_sendmail and provides the needed functionality but does not expose the @attachments parameter. This stored procedure must be defined in the master database. The system administrator then grants execute permission on the stored procedure to the users necessary without granting permssion to the underlying xp_sendmail procedure.
sp_addsubscription publication [, 'article'], subscriber [, destination_db]
[, @sync_type = {'automatic' | 'manual' | 'none'}]
[, @status = {'inactive' | 'active' | 'subscribed'}
If you use sp_articleview on a base table that is not vertically partitioned, the article view will be created.
For use with replication tasks only. Transact-SQL and CmdExec tasks are executed only locally.
sp_addtype ssn, 'VARCHAR(11)', 'NOT NULL'
It is recommended that this procedure be used to change the default database for all users other than the system administrator.
A status of 512 indicates Offline.
When reading image columns, ISQL/w internally limits the length of image columns to 255 characters. Reduction of the image length reduces the likelihood that Windows 95 - based text-drawing APIs and graphics drivers will exceed their character-per-line maximum.
A savepoint_name can be issued multiple times during a single transaction, and a rollback to that savepoint_name will roll back only to the most recent issuance point.
UPDATE titles SET ytd_sales = ytd_sales + qty FROM titles, sales WHERE titles.title_id = sales.title_id AND sales.ord_date = (SELECT MAX(sales.ord_date) FROM sales) UPDATE titles SET ytd_sales = (SELECT SUM(qty) FROM sales WHERE sales.title_id = titles.title_id AND sales.ord_date IN (SELECT MAX(ord_date) FROM sales)) FROM titles, sales
RAISERROR('No error, but we won't send anymore batches',0,127)
This error causes the isql script to terminate and the message stated is returned to the client.
Note It is recommended that you use a severity of 0 when printing a non-error message and that you allow SQL Server severity levels of 1 through 10.
A variable cannot be of image or text datatypes.
Carlos Hernandez
Rita Muller
Martine Rance
Martin Sommer