Example:: Transact-SQL Functions 135
Example:: Transact-SQL Functions 135
135
Example:
SQL
EXEC sp_addtype empidtype , 'DEC(4)' , 'NULL' CREATE TABLE emps2 ( empid empidtype PRIMARY KEY, -- makes it NOT NULL ename VARCHAR(20) ) INSERT INTO emps2 VALUES ( 1111 , 'James Bond' ) EXEC sp_help empidtype
Result
Type_name -----------empidtype
SQL
Storage_type ---------------decimal
Length -------5
Prec ----4
Scale -----0
Nullable ----------yes
EXEC sp_help emps2 -- Partial listing to show the new data type for empid column
Result
2.6 TRANSACT-SQL FUNCTIONS Microsoft SQL Server 2000 has a large number of built-in functions available for SQL programming, database administration and other purposes. The major categories are listed in Table 2-51. The following sections contain detailed explanations for each of the categories from Table 2-51, categorizing the functions and describing their general pur-
136
Table 2-51
Built-in Functions
Description Perform a calculation on a set of values and return a single summarizing value, e.g., COUNT(), SUM(), AVG() Returns information about cursors. Returns information about the current conguration. Performs an operation on a date and time input value and returns either a string, numeric or date and time value. Performs a calculation based on input values provided as parameters to the function, and returns a numeric value. Returns information about the database and database objects. Returns an object that can be used in an SQL statement like a table. Returns information about users and roles. Performs an operation on a string (CHAR or VARCHAR) input value and returns a string or numeric value. Performs operations and returns information about values, objects and settings in Microsoft SQL Server. Returns statistical information about the system. Performs an operation on a text or image input values or column and returns information about the value.
Function Category Aggregate Functions Cursor Functions Conguration Functions Date and Time Functions Mathematical Functions Metadata Functions Rowset Functions Security Functions String Functions System Functions System Statistical Functions Text and Image Functions
pose. Some of the commonly used functions are covered in greater detail, with examples. All functions can be found in Books Online. See also Deterministic and Nondeterministic Functions, page 162. 2.6.1 Aggregate Functions
Aggregate functions perform a calculation on a set of values and return a single summarizing value. Table 2-52 lists the function names and their details.COUNT(), AVG(), MIN(), MAX() and SUM() are ANSI SQL-92 and 99 standard. All are deterministic (see page 162). Aggregate functions are only allowed as expressions in the following cases. The select list of a SELECT statement (either a subquery or an outer query). A COMPUTE or COMPUTE BY clause. A HAVING clause.
Transact-SQL Functions
137
Table 2-52
Aggregate Functions
Description and Syntax Returns the average of the values in a group. Null values are ignored. Returns the binary checksum value computed over a row of a table or over a list of expressions. It can be used to detect changes to a row of a table. Syntax: BINARY_CHECKSUM ( * | expression [ ,...n ] ) Returns the checksum value computed over a row of a table, or over a list of expressions. CHECKSUM is intended for use in building hash indices. Syntax: CHECKSUM ( * | expression [ ,...n ] ) Returns the checksum of the values in a group. Null values are ignored. Syntax: CHECKSUM_AGG ( [ ALL | DISTINCT ] expression ) Returns the number of items in a group as an INT data type value. Syntax: COUNT ( { [ ALL | DISTINCT ] expression ] | * } ) Returns the number of items in a group as a BIGINT data type value. Syntax: COUNT_BIG ( { [ ALL | DISTINCT ] expression } | * ) Works only in SELECT statement with GROUP BY plus either ROLLUP or CUBE to determine whether a NULL in the result set was generated by ROLLUP/CUBE or comes from NULL value(s) in the underlying data. Syntax: GROUPING ( column_name ) returns 1 if a NULL under column_name is from ROLLUP or CUBE returns 0 if a NULL under column_name is from the data See examples with ROLLUP and CUBE. Returns the maximum value in the expression. Syntax: MAX ( [ ALL | DISTINCT ] expression ) Returns the minimum value in the expression. Syntax: MIN ( [ ALL | DISTINCT ] expression )
CHECKSUM
CHECKSUM_AGG
COUNT
COUNT_BIG
GROUPING
MAX
MIN
SUM
Returns the sum of the values in the expression. SUM can be used with numeric columns only. Null values are ignored. Syntax: SUM ( [ ALL | DISTINCT ] expression ) Returns the sample statistical standard deviation of all values in the given expression. For sample statistics the divisor is (n-1). Syntax: STDEV ( expression ) ) Returns the population statistical standard deviation for all values in the given expression. For population statistics the divisor is (n). Syntax: STDEVP ( expression ) )
STDEV
STDEVP
138
Table 2-52
VAR
VARP
2.6.2
Cursor Functions
Cursor Functions, listed in Table 2-53, return cursor status information. All are nondeterministic (see page 162).
Table 2-53 Cursor Functions
Description and Syntax Returns the number of rows in the last cursor opened on the connection. Returns the status of the last cursor FETCH statement issued against any cursor currently opened by the connection. Global function to all cursors in the connection, so use it immediately after the FETCH whose status youre interested in. A scalar function that allows the caller of a stored procedure to determine whether or not the procedure has returned a cursor and result set.
CURSOR_STATUS
These functions are discussed in more detail in Cursors, page 638. 2.6.3 Conguration Functions
Conguration functions, listed in Table 2-54, return information about the current server and database conguration settings. All are nondeterministic (see page 162).
Table 2-54 Conguration Functions
Description (Syntax is just the Function Name since all are read-only and none take parameters.) Returns the current value of the SET DATEFIRST parameter, which indicates the specied rst day of each week: 1 for Monday, 2 for Wednesday, and so on through 7 for Sunday. The U.S. English default is 7, Sunday.
Transact-SQL Functions
139
Table 2-54
@@DBTS
Returns the value of the current timestamp data type for the current database. This timestamp is guaranteed to be unique in the database. Syntax: @@DBTS Returns local language identier (ID) of the language currently in use. Returns the name of the language currently in use. Returns the current lock time-out setting, in milliseconds, for the current session. Returns the maximum number of simultaneous user connections allowed on a Microsoft SQL Server. The number returned is not necessarily the number currently congured. Returns the precision level used by decimal and numeric data types as currently set in the server. Returns the nesting level of the current stored procedure execution (initially 0). Returns information about current SET options. See description page 204. Returns the name of the remote Microsoft SQL Server database server as it appears in the login record. It enables a stored procedure to check the name of the database server from which the procedure is run. Returns the name of the local server running Microsoft SQL Server. Returns the name of the registry key under which Microsoft SQL Server is running. @@SERVICENAME returns MSSQLServer if the current instance is the default instance; this function returns the instance name if the current instance is a named instance.
@@MAX_CONNECTIONS
@@MAX_PRECISION
@@NESTLEVEL
@@OPTIONS
@@REMSERVER
@@SERVERNAME @@SERVICENAME
140
Table 2-54
@@VERSION
Example:
SQL
Result
Server ---------------AMY
Service ----------------------MSSQLServer
2.6.4
Date and time functions perform an operation on a date and time input value and return either a string, numeric or date and time value. See Table 2-55. These functions are deterministic and nondeterministic. See details page 163.
DATENAME, GETDATE and GETUTCDATE are nondeterministic. DATEPART is deterministic unless used with dw datepart. The rest are deterministic. Table 2-55
Date Function Name DATEADD
Description and Syntax Returns a new datetime value after adding an interval (number argument) to the specied date argument. The interval is an integer whose date/time units are specied by the datepart argument as in DATEDIFF below. Syntax: DATEADD ( datepart , number, date )
Transact-SQL Functions
141
Table 2-55
Date Function Name
Description and Syntax Example: SQL: SELECT DATEADD(week, 1, '1 Jan, 2002' ) As '2d week in 2002' Result: 2d week in 2002 -------------------------------2002-01-08 00:00:00.000
DATEDIFF
Returns the integer difference between two DATETIME arguments in the date or time increments specied by the datepart argument (year, quarter, ..., minute, ...). Syntax: ( datepart , startdate , enddate ) Example: SQL: SELECT DATEDIFF (week, '1 Jan, 2002', '19 Jan, 2002' )
As NumWeeks
Result: NumWeeks ----------2 DATENAME Returns a character string representing the specied datepart of the specied date. Syntax: DATENAME ( datepart , date ) Example: SQL: SELECT DATENAME (month, '1 Jan, 2002' ) As '1st Month in 2002' Result: 1st Month in 2002 -----------------------------January Returns an integer representing the specied datepart of the specied date. Syntax: DATEPART ( datepart , date ) Example: SQL: SELECT DATEPART ( month, '1 Jan, 2002' ) As '1st Month in 2002' Result: 1st Month in 2002 ----------------1
DATEPART
142
Table 2-55
Date Function Name DAY
Description and Syntax Returns an integer representing the day datepart of the specied date. Syntax: DAY ( date ) Example: SQL: SELECT DAY( '1 Jan, 2002' ) As 'Day of Month' Result: Day of Month -----------1 Note: DAY( date ) is equivalent to: DATEPART( dd, date ) Returns an integer that represents the month part of a specied date. Syntax: MONTH ( date ) Example: SQL: SELECT MONTH( '1 Jan, 2002' ) As 'Month Number' Result: Month Number -----------1 Note: MONTH( date ) is equivalent to: DATEPART( mm, date ) Returns an integer that represents the year part of a specied date. Syntax: YEAR ( date ) Example: SQL: SELECT YEAR( '1 Jan, 2002' ) As Year Result: Year ----------2002 Note: YEAR( date ) is equivalent to: DATEPART( yy, date ) Returns the current system date and time in the Microsoft SQL Server standard internal format for datetime values. Syntax: GETDATE ( ) Example: SQL: SELECT GETDATE() As Today Result: Today -----------------------------2002-03-27 17:26:14.723
MONTH
YEAR
GETDATE
Transact-SQL Functions
143
Table 2-55
Date Function Name GETUTCDATE
Description and Syntax Returns the datetime value representing the current UTC time (Universal Time Coordinate or Greenwich Mean Time). The current UTC time is derived from the current local time and the time zone setting in the operating system of the computer on which SQL Server is running. Syntax: GETUTCDATE() Example: SQL: SELECT GETDATE() As Now , GETUTCDATE() As NowUTC
-- From PST
Result: Now NowUTC ------------------------------ ------------------------------2002-03-27 16:29:13.250 2002-03-27 23:29:13.250
2.6.5
Mathematical Functions
A mathematical function performs a calculation based on input values provided as parameters to the function and returns a numeric value (Table 2-56). All are deterministic except RAND. See listing page 162.
Table 2-56
Math Function Name ABS
Mathematical Functions
Description and Syntax Returns the absolute, positive value of the given numeric expression. Syntax: ( numeric_expression ) Returns the angle, in radians, (arccosine) whose cosine is the given oat expression. Syntax: ACOS ( float_expression ) Returns the angle, in radians, (arcsine) whose sine is the given oat expression. Syntax: ASIN ( float_expression ) Returns the angle in radians (arctangent) whose tangent is the given oat expression. Syntax: ATAN ( float_expression ) Returns the angle, in radians, whose tangent is between the two given oat expressions. Syntax: ATN2 ( float_expression , float_expression ) Returns the smallest integer greater than, or equal to, the given numeric expression. E.g., CEILING( 2.67 ) is 3. Syntax: CEILING ( numeric_expression )
ACOS
ASIN
ATAN
ATN2
CEILING
144
Table 2-56
Math Function Name COS
Description and Syntax A mathematical function that returns the trigonometric cosine of the given angle (in radians) in the given expression. Syntax: COS ( float_expression ) A mathematic function that returns the trigonometric cotangent of the specied angle (in radians) in the given oat expression. Syntax: COT ( float_expression ) Returns the angle in degrees for an input angle in radians. E.g., DEGREES( PI()/2 ) is 90.0. Syntax: DEGREES ( numeric_expression ) Returns the exponential value of the given oat expression. That is, the natural logarithm base (approx. 2.71) raised to the exponent passed as argument. E.g., EXP(1) is 2.71. Syntax: EXP ( float_expression ) Returns the largest integer less than or equal to the given numeric expression. E.g., FLOOR( 2.67 ) is 2. Syntax: FLOOR ( numeric_expression ) Returns the natural logarithm of the given oat expression. Syntax: LOG ( float_expression ) Returns the base-10 logarithm of the given oat expression. Syntax: LOG10 ( float_expression ) Returns the constant value of PI. I.e., PI() is 3.14159. Syntax: PI ( ) Returns the value of the given expression to the specied power. Syntax: POWER ( numeric_expression , y ) Returns radians when a numeric expression, in degrees, is entered. Syntax: RADIANS ( numeric_expression ) Returns a random oat value from 0 through 1. Syntax: RAND ( [ seed ] ) Returns a numeric expression, rounded to the specied length or precision. Syntax: ROUND ( numeric_expression , length [ , function ] ) Returns the positive (+1), zero (0), or negative (1) sign of the given expression. Syntax: SIGN ( numeric_expression )
COT
DEGREES
EXP
FLOOR
LOG
LOG10
PI
POWER
RADIANS
RAND
ROUND
SIGN
Transact-SQL Functions
145
Table 2-56
Math Function Name SIN
Description and Syntax Returns the trigonometric sine of the given angle (in radians) in an approximate numeric (oat) expression. Syntax: SIN ( float_expression ) Returns the square root of the given expression. Syntax: SQRT ( float_expression ) Returns the square of the given expression. Syntax: SQUARE ( float_expression ) Returns the tangent of the input expression which is an angle in radians. Syntax: TAN ( float_expression )
SQRT
SQUARE
TAN
Example:
SQL
SELECT CEILING(2.13) Ceil , LOG(10) Log , LOG10(10) Log10 , PI() Pi , SIN(1) Sine
Result
Ceil ----3 Log -----------------------------2.3025850929940459 Log10 -------------1.0 Pi ------------------------3.1415926535897931 Sine ----------------------------0.8414709848078965
2.6.6
Metadata Functions
A metadata function returns information about the database and database objects (Table 2-57). All are nondeterministic (see page 163).
Table 2-57
Function
@@PROCID COL_LENGTH
Metadata Functions
Description and Syntax Returns the current stored procedure identier (ID). Returns the dened length (in bytes) of a column. Syntax: COL_LENGTH ( 'table' , 'column' )
146
Table 2-57
Function
COL_NAME
COLUMNPROPERTY
DATABASE-PROP- Returns named database property value for the given database and property name for ERTY SQL Server 7.0 and before.
Returns named database property value for the given database and property name for SQL Server 2K and later. Syntax: DATABASEPROPERTYEX( database , property ) Returns the database identication (ID) number. Syntax: DB_ID ( [ 'database_name' ] ) Returns the database name. Syntax: DB_NAME ( database_id ) Returns the le identication (ID) number for the given logical le name in the current database. Syntax: FILE_ID ( 'file_name' ) Returns the logical le name for the given le identication (ID) number. Syntax: FILE_NAME ( file_id ) Returns the legroup identication (ID) number for the given legroup name. Syntax: FILEGROUP_ID ( 'filegroup_name' ) Returns the legroup name for the given legroup identication (ID) number. Syntax: FILEGROUP_NAME ( filegroup_id ) Returns the specied legroup property value when given a legroup and property name. Syntax: FILEGROUPPROPERTY ( filegroup_name , property ) Returns the specied le name property value when given a le name and property name. Syntax: FILEPROPERTY ( file_name , property )
DB_ID
DB_NAME
FILE_ID
FILE_NAME
FILEGROUP_ID
FILEGROUP_NA ME FILEGROUPPROPERTY
FILEPROPERTY
Transact-SQL Functions
147
Table 2-57
Function
fn_listextendedproperty
| | | | | |
} } } } } }
FULLTEXTCATALOGPROPERTY
FULLTEXTSERVI- Returns information about full-text service-level properties. CEPROPERTY Syntax: FULLTEXTSERVICEPROPERTY ( property ) INDEX_COL
Returns the indexed column name. Syntax: INDEX_COL ( 'table' , index_id , key_id ) Returns information about the index key. Syntax:
INDEXKEY_ PROPERTY
property )
INDEXPROPERTY Returns the named index property value given a table identication number, index
property )
Returns the database object identication number. Syntax: OBJECT_ID ( 'object' ) Returns the database object name. Syntax: OBJECT_NAME ( object_id ) Returns information about objects in the current database. Syntax: OBJECTPROPERTY ( id , property ) Returns the base data type and other information about an sql_variant value. Syntax: SQL_VARIANT_PROPERTY ( expression, property ) Returns information about a data type. Syntax: TYPEPROPERTY ( type , property )
OBJECT_NAME
148
2.6.7
Rowset Functions
A rowset is a set of rows that contain columns of data and can be used like a table in SQL. Rowsets are central objects that enable all OLE DB data providers to expose result set data in tabular form. Rowset Functions return rowsets (Table 2-58). All are nondeterministic (see page 163). A rowset is a set of rows that contain columns of data. Rowsets are central objects that enable all OLE DB data providers to expose result set data in tabular form.
Table 2-58 Rowset Functions
Description and Syntax Returns a table of zero or more rows after doing a full-text type query based on precise or near (fuzzy) match criteria. CONTAINSTABLE can be referenced in the FROM clause of a SELECT statement as if it were a regular table name. Syntax:
CONTAINSTABLE ( table , { column | * } , ' < contains_search_condition > ' [ , top_n_by_rank ] ) FREETEXTTABLE
Returns a table of zero or more rows after doing a full-text type query based on meaning of the text. FREETEXTTABLE can be referenced in the FROM clause of a SELECT statement as if it were a regular table name. Syntax:
Provides ad hoc connection information as part of a four-part object name without using a linked server name. See Books Online. Syntax: OPENDATASOURCE ( provider_name, init_string ) Executes the specied pass-through query on the given linked server, which is an OLE DB data source. The OPENQUERY function can be referenced in the FROM clause of a query as though it is a table name or as the target table of an INSERT, UPDATE or DELETE statement, subject to the OLE DB provider. Syntax: OPENQUERY ( linked_server , 'query' )
OPENQUERY
Transact-SQL Functions
149
Table 2-58
OPENROWSET ( 'provider_name' , { 'datasource' ; 'user_id' ; 'password' | 'provider_string' } , { [ catalog. ] [ schema. ] object | 'query' } )
OPENXML
Opens an XML document and returns the data as a rowset which may be used as a table in a read-only SQL statement. Often used with sp_xml_preparedocument as in the example below. Syntax:
OPENXML ( idoc int [in], -- the document handle created by sp_xml_preparedocument rowpattern nvarchar[in] -- XPATH pattern to identify XML document nodes to be used as rows [, flags byte[in]] -- XML mapping: 0 (default) attribute-centric, 1 - attribute-centric then can use XML_ELEMENTS, 2 - element-centric then can use XML_ATTRIBUTES, 8 - combine XML_ELEMENTS and XML_ATTRIBUTES )[WITH (SchemaDeclaration | TableName)] -- may specify nodes to display in result set
Example: Use OPENQUERY requires a link be made to remote server. See page 66.
SQL
FROM pubs.dbo.authors')
Result
state -----CA CA
150
This example uses the link CAT2_Link created on page 47. That version is repeated below as it seems more direct than the OPENQUERY method above.
SQL
SELECT
TOP 2
FROM
CAT2_Link.pubs.dbo.authors
Result
Example:
SQL
'SELECT
Result
Example: Use OPENXML Create an xml document with sp_xml_preparedocument, then read it with OPENXML. Create an internal representation of an XML data document and assign the document handle value to the idoc handle variable so it can be passed in to OPENXML to read.
DECLARE @idoc int -- Declare an int variable for the xml document handle
EXEC sp_xml_preparedocument @idoc OUTPUT, '<ROOT> <Customer > <CustomerID>12</CustomerID> <Name>Amy Darling</Name> <Telephone>111-2222</Telephone> </Customer>
Transact-SQL Functions
151
<Customer > <CustomerID>36</CustomerID> <Name> Torie Dearest </Name> <Telephone>333-4444</Telephone> </Customer> </ROOT>'
Do a query using OPENXML to read the desired parts of the XML data document.
SQL
SELECT * FROM OPENXML (@idoc, '/ROOT/Customer', 2) WITH (CustomerID varchar(10), Name varchar(20))
Result
With the XML data thus available at a virtual table in SQL, it may be inserted into a database table as in this example run in the same batch as the previous statements.
SQL
SELECT * INTO table1 FROM OPENXML (@idoc, '/ROOT/Customer', 2) WITH (CustomerID varchar(10), Name varchar(20)) go SELECT * FROM table1
152
SQL
(cont.)
Result
2.6.8
Security Functions
A security function returns information about users and roles. All are nondeterministic (see Table 2-59 and page 162).
Table 2-59 Security Functions
Description and Syntax Returns information about the events traced. Syntax: fn_trace_geteventinfo ( [ @traceid = ] trace_id ) Returns information about the lters applied to a specied trace. Syntax: fn_trace_getfilterinfo( [ @traceid = ] trace_id ) Returns information about a specied trace or existing traces. Syntax: fn_trace_getinfo( [ @traceid = ] trace_id ) Returns trace le information in a table format. Syntax: fn_trace_gettable( [ @filename = ] filename ,
fn_trace_getlterinfo
fn_trace_getinfo
fn_trace_gettable
[ @numfiles = ] number_files )
HAS_DBACCESS
Indicates whether the user has access to the specied database. Returns int 0 if no, 1 if yes, NULL if database name is invalid. Syntax: HAS_DBACCESS ( 'database_name' ) Indicates whether the current user is a member of the specied Microsoft Windows NT group or Microsoft SQL Server role. Returns int 0 if no, 1 if yes, NULL if group or role is invalid. Syntax: IS_MEMBER ( { 'group' | 'role' } ) Indicates whether the current or specied user login is a member of the specied server role. Returns int 0 if no, 1 if yes, NULL if role or login is invalid. Syntax: IS_SRVROLEMEMBER ( 'role' [ , 'login' ] )
IS_MEMBER
IS_SRVROLEMEMBER
Transact-SQL Functions
153
Table 2-59
SUSER_SID
Returns the login identication name for the current user or from the users security identication number (SID) if specied. Syntax: SUSER_SNAME ( [ server_user_sid ] ) Example:
Allows a system-supplied value for the current users database username to be inserted into a table when no default value is specied. Syntax: USER Example:
2.6.9
A string function for CHAR or VARCHAR expressions performs an operation on a string input value and returns a string or numeric value (Table 2-60). All are deterministic except CHARINDEX and PATINDEX (see page 162).
Table 2-60
String Fcn
ASCII
String Functions
Description and Syntax Returns the ASCII code value of the leftmost character of a char expression. Syntax: ASCII ( character_expression ) SQL: PRINT ASCII('abc') -- The ASCII value of the letter "a" is 97 Result: 97
154
Table 2-60
String Fcn
CHAR
SQL: PRINT CHAR(97) -- 97 is the ASCII value of the letter "a" Result: a
CHARINDEX
Returns the starting position of expr1 in a character string expr2. Search begins with 1st character unless start_location is given and is > 1. Syntax: CHARINDEX ( expr1 , expr2 [ , start_location ] ) Returns the difference between the SOUNDEX values of two character expressions as an integer. See Books Online. Syntax: DIFFERENCE ( character_expression ,
DIFFERENCE
character_expression )
LEFT
Returns the leftmost integer_expression characters of character_expr. Syntax: LEFT ( character_expr , integer_expression )
Returns the number of characters (may not be the number of bytes) of the given string expression, excluding trailing blanks. Syntax: LEN ( string_expression )
LEN('abc')
Returns the character_expression string in all lower case. Syntax: LOWER ( character_expression )
Returns a character expression after removing leading blanks. Syntax: LTRIM ( character_expression ) Returns the Unicode character with the given integer code. Syntax:NCHAR ( integer_expression ) Returns the starting position of the rst occurrence of a pattern in the char_expr or zero if the pattern is not found (text or character data types). Syntax:PATINDEX ( '%pattern%' , char_expr ) Example:
NCHAR
PATINDEX
Transact-SQL Functions
155
Table 2-60
String Fcn
QUOTENAME
REPLACE
'string_expr3' )
Example:
Repeats a character expression for a specied number of times. Syntax: REPLICATE ( character_expression ,
integer_expression )
REVERSE
Returns the reverse of a character expression. Syntax: REVERSE ( character_expression ) Returns the rightmost <integer_expr> characters of <character_expr>. Syntax:RIGHT ( character_expr , integer_expr ) Returns a character expression after removing trailing blanks. Syntax: RTRIM ( character_expression ) Returns a four-character (SOUNDEX) code to evaluate the similarity of two strings. Syntax: SOUNDEX ( character_expression ) Returns a string of repeated spaces. Syntax: SPACE ( integer_expression ) Returns character data converted from numeric data. Syntax: STR ( float_expression [ , length [ , decimal ] ] ) Replaces characters in char_expr1 from start to start plus length with char_expr2. Syntax: STUFF ( char_expr1 , start , length , char_expr2 ) Returns part of a character, binary, text, or image expression. Syntax: SUBSTRING ( expression , start , length ) Returns the integer Unicode value for the rst character of the expression. Syntax: UNICODE ( 'ncharacter_expression' ) Returns the character_expression string in all upper case. Syntax: UPPER ( character_expression )
RIGHT
RTRIM
SOUNDEX
SPACE
STR
STUFF
SUBSTRING
UNICODE
UPPER
156
2.6.10 System Functions System functions, listed in Table 2-61, perform operations and return information about values, objects and settings in Microsoft SQL Server. Some are deterministic and some are not. See list page 162.
Table 2-61 System Functions
Description and Syntax Returns the error number for the last Transact-SQL statement executed. Syntax: @@ERROR Returns the last-inserted identity value. Syntax: @@IDENTITY Returns the number of rows affected by the last statement. Syntax: @@ROWCOUNT Returns the number of active transactions for the current connection. Syntax: @@TRANCOUNT Returns the application name for the current session if set. Syntax: APP_NAME ( ) Evaluates a list of conditions and returns one of multiple possible result expressions. See explanation and examples, page 165. Explicitly converts an expression of one data type to another. CAST and CONVERT provide similar functionality. See explanation and examples, page 167. Syntax:
CAST ( expression AS data_type ) CONVERT ( data_type [ ( length ) ] , expression [ , style ] ) COALESCE
@@IDENTITY
@@ROWCOUNT
@@TRANCOUNT
APP_NAME
CASE expression
Returns the rst nonnull expression among its arguments. Syntax: COALESCE ( expression [ ,...n ] ) Returns the property of a given collation. Syntax: COLLATIONPROPERTY( collation_name, property ) Returns the current date and time. Equivalent to GETDATE(). Syntax: CURRENT_TIMESTAMP Returns the current user. This function is equivalent to USER_NAME(). Syntax: CURRENT_USER
COLLATIONPROPERTY
CURRENT_TIMESTAMP
CURRENT_USER
Transact-SQL Functions
157
Table 2-61
fn_helpcollations
fn_servershareddrives
fn_virtuallestats
FORMATMESSAGE
Constructs a message from an existing message in sysmessages. The functionality of FORMATMESSAGE resembles that of the RAISERROR statement; however, RAISERROR prints the message immediately. FORMATMESSAGE returns the edited message for further processing. Syntax: FORMATMESSAGE ( msg_number , param_value
[ ,...n ] )
GETANSINULL
Returns the effective default nullability for the database for this session. Syntax: GETANSINULL ( [ 'database' ] ) Books Online says this returns the client workstation identication number. This value appears to be the process id for each client program from the client host. Thus the value differs for each client program. Syntax: HOST_ID ( ) Returns the client workstation name. This name is the same for each connection from the client host. Syntax: HOST_NAME ( ) Returns the last identity value generated for a specied table in any session and any scope. Syntax: IDENT_CURRENT('table_name') Returns the numeric increment value specied during the creation of an identity column in a table or view that has an identity column. Syntax: IDENT_INCR ( 'table_or_view' ) Returns the numeric seed value specied during the creation of an identity column in a table or a view that has an identity column. Syntax: IDENT_SEED ( 'table_or_view' )
HOST_ID
HOST_NAME
IDENT_CURRENT
IDENT_INCR
IDENT_SEED
158
Table 2-61
ISDATE
Returns 1 if the expression is a valid date, 0 if not. Syntax: ISDATE ( expression ) If expr1 is NULL, it is replaced with expr2. That is, IF expr1 IS NOT NULL returns expr1 ELSE returns expr2 Syntax: ISNULL ( expr1 , expr2 ) Example: SQL: SELECT ISNULL( 'Hello', 'Null') , ISNULL
(NULL, 'Null word')
ISNULL
Returns 1 if the expression is a valid numeric type, 0 if not. Syntax: ISNUMERIC ( expression ) Creates a unique value of type uniqueidentier. Syntax: NEWID ( ) Returns NULL if the two expressions are equivalent. If not equivalent, returns the rst expression. See Books Online for meaningful example. Syntax: NULLIF ( expression , expression ) Returns the specied part of an object name. Parts of an object that can be retrieved are the object name, owner name, database name, and server name. Note: This function does not indicate whether or not the specied object exists. It just returns the specied piece of the given object name. Syntax: PARSENAME ( 'object_name' , object_piece ) object_piece (integer) Meaning 1 Object name 2 Owner name 3 Database name 4 Server name
NEWID
NULLIF
PARSENAME
Transact-SQL Functions
159
Table 2-61
PERMISSIONS
ROWCOUNT_BIG
SCOPE_IDENTITY
SERVERPROPERTY
SESSIONPROPERTY
SESSION_USER
STATS_DATE
SYSTEM_USER
As Sys
Result: ----dbo USER_NAME Sess ------sa Sys
Returns a user database username from a given identication number. Syntax: USER_NAME ( [ id ] )
160
2.6.11 System Statistical Functions A system statistical function, returns statistical information about the system. See Table 2-62 for details. All are nondeterministic (see page 162).
Table 2-62 System Statistical Functions
Description and Syntax Returns the number of connections, or attempted connections, since Microsoft SQL Server was last started. Returns the time in milliseconds (based on the resolution of the system timer) that the CPU has spent working since Microsoft SQL Server was last started. Returns the time in milliseconds (based on the resolution of the system timer) that Microsoft SQL Server has been idle since last started. Returns the time in milliseconds (based on the resolution of the system timer) that Microsoft SQL Server has spent performing input and output operations since it was last started. Returns the number of input packets read from the network by Microsoft SQL Server since last started. Returns the number of output packets written to the network by MicrosoftSQL Server since last started. Returns the number of network packet errors that have occurred on Microsoft SQL Server connections since SQL Server was last started. Returns the number of microseconds per tick. Returns the number of disk read/write errors encountered by Microsoft SQL Server since last started. Returns the number of disk reads (not cache reads) by Microsoft SQL Server since last started. Returns the number of disk writes by Microsoft SQL Server since last started. Returns I/O statistics for database les, including log les. Syntax: fn_virtualfilestats ( [@DatabaseID=]database_id
, [ @FileID = ] file_id )
@@IDLE @@IO_BUSY
Transact-SQL Functions
161
2.6.12 Text and Image Functions and Statements Text and image functions, listed in Table 2-63, perform an operation on a text or image input value or column and return information about the value. All are nondeterministic (see page 162).
Table 2-63 Text and Image Functions
Description and Syntax Returns the number of bytes used to represent any expression. Syntax: DATALENGTH ( expression ) Returns the starting position of the rst occurrence of a pattern in a specied expression or zero if the pattern is not found. All text and character data types. Syntax: PATINDEX ( '%pattern%' , expression ) Returns part of a character, binary, text, or image expression. See Books Online. Syntax: SUBSTRING ( expression , start , length ) Returns the text-pointer value that corresponds to a text, ntext, or image column in varbinary format. The retrieved text pointer value can be used in READTEXT, WRITETEXT, and UPDATETEXT statements. Syntax: TEXTPTR ( column ) Returns 1 if a given text, ntext, or image pointer is valid, 0 if not. Syntax: TEXTVALID ( 'table.column' , text_ ptr )
PATINDEX
SUBSTRING
TEXTPTR
TEXTVALID
See Text examples on page 109. Text and image statements are summarized in Table 2-64.
Table 2-64 Text and Image Statements
Description and Syntax Reads text, ntext, or image values from a text, ntext, or image column, starting from a specied offset and reading the specied number of bytes. Syntax: READTEXT { table.column text_ptr offset size } [
HOLDLOCK ]
SET TEXTSIZE Species the size of text and ntext data returned with a SELECT statement. Syntax: SET TEXTSIZE { number } Updates an existing text, ntext, or image eld. Use UPDATETEXT to change only a portion of a text, ntext or image column in place.
UPDATETEXT
162
Table 2-64
] { data }
2.6.13 Deterministic and Nondeterministic Functions All functions are either deterministic or nondeterministic. Deterministic functions always return the same result any time they are called with the same input values. For example, ABS(-2) always returns 2. Nondeterministic functions may return different results each time they are called even though input values are the same. For example, GETDATE() returns a different result each time its called. Indexed views or indexes on computed columns cannot include nondeterministic functions. An index cannot be created on a view which references any nondeterministic functions. An index cannot be created on a computed column if the computed_column_expression references any nondeterministic functions. 2.6.13.1 Listing of Deterministic and Nondeterministic Functions
Aggregate built-in functions (page 139) are all deterministic. String built-in functions (page 154) are all deterministic except CHARINDEX and PATINDEX. Tables 2-65 thorugh 2-68 identify characteristics of many functions.
Always Deterministic Table 2-65
ABS ACOS ASIN ATAN ATN2 CEILING COALESCE
Deterministic Functions
COS COT DATALENGTH DATEADD DATEDIFF DAY DEGREES EXP FLOOR ISNULL ISNUMERIC LOG LOG10 MONTH NULLIF PARSENAME PI POWER RADIANS ROUND SIGN SIN SQUARE SQRT TAN YEAR
Transact-SQL Functions
163
Sometimes Deterministic
These functions, listed in Table 2-67, are not always deterministic but can be used in indexed views or indexes on computed columns when they are specied in a deterministic manner.
Sometimes Deterministic Functions
Comments Deterministic unless used with datetime, smalldatetime or sql_variant. Deterministic unless used with datetime, smalldatetime or sql_variant. The datetime and smalldatetime data types are deterministic if style parameter is given. Deterministic, with the exception of CHECKSUM(*). Deterministic except when used as DATEPART (dw, date). The value returned by dw, weekday, depends on the value set by SET DATEFIRST. Deterministic only if used with the CONVERT function, the CONVERT style parame ter is specied and style is not equal to 0, 100, 9 or 109. RAND is deterministic only when a seed parameter is specied.
Table 2-67
Function CAST CONVERT CHECKSUM DATEPART ISDATE RAND
Never Deterministic
The System and Built-in Functions in Table 2-68 are always nondeterministic.
Nondeterministic Functions
fn_servershareddrives fn_virtuallestats FORMATMESSAGE GETANSINULL GETDATE GETUTCDATE HOST_ID IDENT_INCR IDENT_SEED IDENTITY NEWID PERMISSIONS ROWCOUNT_BIG SCOPE_IDENTITY SESSIONPROPERTY STATS_DATE SYSTEM_USER TEXTPTR TEXTVALID USER_NAME
Table 2-68
@@ERROR @@IDENTITY
164
Table 2-68
CURRENT_USER DATENAME
As discussed earlier, all conguration, cursor, meta data, rowset, security, and system statistical functions are nondeterministic. Functions that call extended stored procedures are nondeterministic because the extended stored procedures can cause side effects on the database. 2.6.14 CASE Expression CASE can be considered an expression or a function because it evaluates to a single scalar value of the same data type as the input expression. CASE has two formats: simple CASE and searched CASE. Simple CASE compares the input expression to a series of simple expressions.
CASE input-expression WHEN match-expression THEN result [ WHEN match-expression THEN result ] ... [ELSE result] END
END
2.6.14.1
Consider Table 2-69, which has a column containing a car manufacturer abbreviation.
Table 2-69
Make Buick Quattro
Autos
Manufacturer GM Au ... ...
Transact-SQL Functions
165
Table 2-69
Jeep Sebring
Autos (cont.)
DC DC
The following query uses CASE to convert the manufacturer abbreviation to the full name.
SQL
SELECT Make, CASE Manufacturer WHEN 'GM' THEN 'General Motors' WHEN 'Au'THEN 'Audi' WHEN 'DC'THEN 'Daimler-Chrysler' ELSE 'Manufacturer not found' END As Manufacturer FROM Autos;
Result
2.6.14.2 Example of Searched CASE This form of CASE can be used for inequalities, as in the example, as well as equalities. Consider Table 2-70, for which we want to do a query that assigns letter grades.
Table 2-70
Student Torie James Amy
Grades
Grade 87 76 93 Major Counselling Dog Husbandry Tae Kwon Do ...
166
Table 2-70
Student Tim Ina
Grades (cont.)
Grade 82 98 Major Jet Skiing Flower Gardening ...
SQL
90 80 70 60
Result
Student ---------Amy Ina James Tim Torie LetterGrade -------------A A C B B
2.6.15 CAST and CONVERT Both CAST and CONVERT functions are used to explicitly convert a value from one data type to another data type. CAST and CONVERT provide similar functionality but only CAST complies with ANSI SQL-92 and -99. CAST and CONVERT may be used anywhere a scalar valued expression may occur in an SQL statement. CAST Syntax
CAST ( expression AS datatype )
CONVERT Syntax
CONVERT (data_type[(length)], expression [, style])
Transact-SQL Functions
167
Example:
SQL
Error
SELECT Make, CASE Manufacturer WHEN 'GM' THEN 'General Motors' WHEN 'Au'THEN 'Audi' WHEN 'DC'THEN 'Daimler-Chrysler' ELSE 'Manufacturer not found' END As Manufacturer FROM Autos;
Result
Server: Msg 241, Level 16, State 1, Line 2 Syntax error converting datetime from character string.
S Q L SELECT
SELECT
Result
CONVERT Example:
SQL
SELECT
-- Okay
Result
168
2.7 SYSTEM STORED PROCEDURES AND DBCC System stored procedures and extended procedures are built-in commands that perform a variety of tasks to do database administration and to provide information. 2.7.1 System Stored Procedures
There are hundreds of system stored procedures and extended procedures. Some individual stored procedures will be described as needed throughout the book. You may check the index to see if a given stored procedure is described in the book. A complete list of system stored procedures may be found in Appendix A. Metadata stored procedures are discussed on p. 376. Additional details may be found by looking each up by name in Books Online. In general, system stored procedure names start with sp_ and return results within SQL Server. Extended stored procedure names start with xp_ and require doing work outside of SQL Server such as making calls to the operating system or an external process. Some useful system stored procedures and extended procedures are summarized in Table 2-71.
Table 2-71 System Stored Procedures
No argumentslists all current server settings in ve columns name minimum maximum cong_value run_value where cong_value is value congured but may not yet be effective until server restarts or recongure command is executed. 1 argumentshows its value; 2 argumentssets its value See page 177 for discussion and examples. Included for backward compatibility. Use ALTER DATABASE. No argumentslists all objects in the current database. 1 argumentreports information about the database object in the current database. Reports information about a specied database or all databases. Reports indexes on the table or view. Prints the code text of a rule, a default or an unencrypted stored procedure, user-dened function, trigger or view. Reports locks held by all processes or by spid (page 140).
169
Table 2-71
sp_who xp_cmdshell xp_grantlogin
xp_revokelogin
EXEC or EXECUTE keyword is optional if this is the rst statement in a batch. 2.7.1.1 The sp_ Procedures The stored procedures provided by SQL server that begin with sp_ are predened to provide administrative functions for managing SQL Server and displaying information about databases and users. Examples include the following: sp_helpdb, sp_help, sp_congure. See a complete list in Appendix A. Example:
SQL
EXEC
sp_helpdb
pubs
Result
owner -------sa
dbid -----5
2.7.1.2 The xp_ ProceduresProvided The procedures that begin with xp_, called extended stored procedures, allow creation of external routines in a programming language such as C.
170
They are used to do work outside of SQL Server, such as accessing the registry, etc. A competent user may create his or her own extended stored procedures with sp_addextendedproc. Some examples include the following: xp_cmdshell, xp_grantlogin, xp_revokelogin. For more details, see Books Online Index: xp_ . Example:
SQL
EXEC master..xp_cmdshell
'dir/w
C:\'
Result
output ---------------------------------------------------------------------Volume in drive C is AMY_C Volume Serial Number is 2CA0-6A55 Directory of C:\ boot.ini [Documents and Settings] [HySnap] [Inetpub] 1 File(s) 189 bytes 4 Dir(s) 9,494,585,344 bytes free
[WINNT]
Example:
SQL
USE pubs go EXEC sp_help -- List all database objects in pubs database
171
Nullable ----no no no
Example: Display the metadata for the authors table of the pubs database including column names.
SQL
EXEC sp_help authors -- Show structure and properties of "authors" table in pubs database
172
2.7.2
DBCC
The initials DBCC stand for Database Console Command (a k a Database Consistency Checker before SQL Server 2K). DBCC statements check the physical and logical consistency of a database. Many DBCC statements can x detected problems. The four categories of DBCC statements and descriptions are shown in Tables 2-72 through 2-75 below. See Books Online for details. 2.7.2.1 DBCC Maintenance Statements The commands listed in Table 2-72 will help you perform maintenance tasks on a database, index or legroup.
Table 2-72 DBCC Maintenance Statements
Rebuilds one or more indexes for a table in the specied database. Drops a damaged database. NOTE: DBCC DBREPAIR is included in Microsoft SQL Server 2000 for backward compatibility only and may not appear in future versions. DROP DATABASE is recommended to drop damaged databases. Defragments indexes of the specied table or view. Shrinks the size of the data les in the specied database. Shrinks the size of the specied data le or log le for the related database. Reports and corrects inaccuracies in the sysindexes table. This may result in incorrect space usage reports by sp_spaceused.
DBCC UPDATEUSAGE
173
2.7.2.2
The commands in Table 2-73 will help you do miscellaneous tasks such as enabling rowlevel locking or removing a DLL from memory. Table 2-73 DBCC Miscellaneous Statements
Unloads the specied extended stored procedure dynamic-link library (DLL) from memory. Returns syntax information for the specied DBCC statement. Marks a table to be pinned, which means Microsoft SQL Server does not ush the pages for the table from memory. Does not affect the locking behavior of SQL Server 2K. It is included for backward compatibility for SS 6.5 scripts and may not appear in future versions. Disables the specied trace ag(s). Turns on (enables) the specied trace ag. Marks a table as unpinned. After a table is marked as unpinned, the table pages in the buffer cache can be ushed.
2.7.2.3
The commands listed in Table 2-74 allow you to perform status checks.
Table 2-74 DBCC Status Statements
Displays the last statement sent from a client to Microsoft SQL Server. Displays information about the oldest active transaction and the oldest distributed and nondistributed replicated transactions, if any, within the specied database. Results are displayed only if there is an active transaction or if the database contains replication information. An informational message is displayed if there are no active transactions. Returns the current output buffer in hexadecimal and ASCII format for the specied system process ID (SPID). Displays information in a table format about the procedure cache. Displays fragmentation information for the data and indexes of the specied table. Displays the current distribution statistics for the specied target on the specied table.
174
Table 2-74
2.7.2.4
The commands shown in Table 2-75 allow you to perform validation operations on a database, table, index, catalog, legroup, system tables or allocation of database pages.
Table 2-75 DBCC Validation Statements
Checks consistency of disk space allocation structures of specied database. Checks for consistency in and between system tables in specied database. Checks integrity of a specied constraint or all constraints on the specied table. Checks the allocation and structural integrity of all the objects in the specied database. Checks the allocation and structural integrity of all tables in the current database in the specied legroup. Checks the current identity value for the specied table and, if needed, corrects the identity value. Checks the integrity of the data, index, text, ntext and image pages for the specied table or indexed view. DBCC NEWALLOC is identical to DBCC CHECKALLOC which is recommended. DBCC NEWALLOC is included in SS 2000 for backward compatibility and may not appear in future versions.
DBCC CHECKALLOC DBCC CHECKCATALOG DBCC CHECKCONSTRAINTS DBCC CHECKDB DBCC CHECKFILEGROUP DBCC CHECKIDENT DBCC CHECKTABLE DBCC NEWALLOC
2.8 SERVER, DATABASE AND SESSION SETTINGS Server conguration settings, database conguration settings and session (or connection) property settings in some cases interact and in some cases are dis-
175
jointed. Because some settings interact, I have found it less confusing to consider them all together. 2.8.1 Settings Overview
Most people can live a long and happy life without delving into the morass of these settings. Microsoft has done an excellent job of designing the database engine to set appropriate default values and of self-tuning to keep performance at a peak for most applications. Nonetheless, I think they need to clean up the interfaces for setting and reading the settings (see Authors Opinion below). Generally speaking, server settings are of interest mainly to database administrators and most should be used only by experienced users and then on a test machine rst. Im not likely to change the number of max worker threads or nested triggers, but if you have a reason and know what youre doing, well show you how. The rest of us will defer. ;-) For database settings, one is likely to occasionally need to a change a database from MULTI_USER to RESTRICTED_USER in order to do maintenance. One may also want to set a specic database to READ_ONLY if its use does not require making data changes.Most database settings are best left as the default unless there is a specic reason to do otherwise. Most session (connection) settings are also best left as the default values unless one has a specic reason to make a change. Exceptions include the occasional guidance given for using OLE DB or ODBC library call to set a specic option to a certain value. In these cases, I just follow the guidance without asking questions. Session settings that can be quite useful for debugging or performance testing include NOEXEC, NOCOUNT, PARSEONLY, SHOWPLAN_xxx, STATISTICS xxx, etc. These options are well worth studying and testing to see the information they provide. Having an understanding of the differences between server, database and session conguration settings will facilitate your programming. The major differences are listed below. 2.8.1.1 Server Conguration
Server settings affect server-wide settings and some database settings. Methods to see and assign server settings are (see details page 178): sp_congure system stored procedure (sets all options) Enterprise Manager (sets only the most commonly used options)
176
2.8.1.2 Database Conguration Database settings affect database and default settings for connections to the database. Methods to see and assign database settings are (see details page 187): ALTER DATABASE with a SET clause Set all db settings. See page 188. DATABASEPROPERTYEX( 'dbname' , 'propertykeyword' ) Read db settings. See page 195. Enterprise Manager Set primary settings only EXEC sp_dboption obsolete (may not be in new versions). Use ALTER DATABASE. 2.8.1.3 Session (Connection) Conguration New sessions inherit server and database settings and the user may change some. Methods to see and assign session settings are (see details page 202): SET Set all session options. See page 204. SELECT @@OPTIONS Read all session options. See page 208. DBCC USEROPTIONS Read all session options. See page 210. SELECT SESSIONPROPERTY ( 'option' ) Read all session options. See page 211. Session settings for Query Analyzer can also be read and set from its Query menu: Query Current Connection Properties.
Authors Opinion The subject of Server, Database and Session settings on SQL Server is overly confusing and needs cleanup work by Microsoft to make it easier to understand and manage. For example, why must one use ALTER DATABASE pubs SET READ_ONLY, or READ_WRITE to change whether a database is updateable, but have to use SELECT DATABASEPROPERTYEX ( 'pubs' , 'Updateability' ) to read the current setting? And notice that pubs in the rst statement must have no quotation marks and in the second statement it must have them. The now-out-of-favor sp_dboption at least had a very consistent interface for changing and reading settings. Utilities to read current session settings also need cleanup work. @@OPTION is relatively complete but a bit awkward to use. SESSIONPROPERTY uses consistent keywords with SET, but only covers seven of them. DBCC USEROPTIONS only shows the ON settings, which is ne, but it doesnt report on all of the SET options. Oh, well!
177
2.8.1.4 Server Conguration Settings Figure 2-3 shows a brief summary of the settings for server conguration. The details of these settings are in the sections that follow. 2.8.1.5 sp_congure Use sp_congure to display or change global conguration settings for the current server. Table 2-76 summarizes the accessible settings. Syntax
sp_configure [ [ @configname = ] 'name' @configvalue = ] 'value' ] ] [ , [
sp_congure may be executed with 0, 1 or 2 arguments: 0 arguments: Lists all conguration setting names addressable with sp_congure 1 argument: Displays the current setting for the conguration name specied 2 arguments: Sets the specied conguration name to the specied value
Conguration settings for a SQL Server instance are observed and assigned with sp_congure system stored procedure (all options are available) (must then run recongure command to effect the changes. See recongure below.) See Exercise 1 at the end of Chapter 1 for using Enterprise Manager and Query Analyzer. Conguration settings for a SQL Server instance are also observed and assigned with Enterprise Manager (primary settings only) Right click on Server name and select Properties. When the dialog appears, explore each tab in turn. Figure 2-3 Summary of Server Configuration Statements Table 2-76 Server Conguration Settings Accessible with sp_congure
Requires 'show advanced options' Yes Requires Server Stop and Restart Yes
Minimum 0 0 0
Maximum 2147483647 1 1 0 0 0
Default
Yes
Yes
178
Table 2-76
Minimum 0
Maximum 1 0
Default
cost threshold for parallelism cursor threshold default full-text language default language ll factor (%) index create memory (KB) lightweight pooling locks max degree of parallelism max server memory (MB) max text repl size (B) max worker threads media retention min memory per query (KB) min server memory (MB) nested triggers network packet size (B)
32767 2147483647 2147483647 9999 100 2147483647 1 2147483647 32 2147483647 2147483647 32767 365 2147483647 2147483647 1 65536
Yes
Yes Yes
Yes
179
Table 2-76
sp_congure Conguration option open objects priority boost query governor cost limit query wait (s) recovery interval (min) remote access remote login timeout (s) remote proc trans remote query timeout (s) scan for startup procs set working set size show advanced options two digit year cutoff user connections user options (See page 202)
Minimum 0 0 0 1 0 0 0 0 0 0 0 0 1753 0 0
Maximum 2147483647 1 2147483647 2147483647 32767 1 2147483647 1 2147483647 1 1 1 9999 32767 32767 0 0 0
Default
1 0 1 20 0 600 0 0 0 2049 0 0
Yes Yes
Yes Yes
To see the listing and current settings, execute sp_congure with no arguments. By default only a partial listing is given unless show advanced options is enabled.
SQL
EXEC sp_configure -- Lists common configuration options. Enable 'advanced options' to see all.
180
SQL
(cont.)
Result
name --------------allow updates default language max text repl size (B) nested triggers remote access remote login timeout (s) remote proc trans remote query timeout (s) show advanced options user options
minimum ----------0 0 0 0 0 0 0 0 0 0
For a description of each item see Books Online: Setting Conguration Options. 2.8.1.6
sp_configure SHOW ADVANCED OPTIONS
To see all sp_congure options, not just the basic ones, enable show advanced options as shown here. Example:
SQL
EXEC sp_configure 'show advanced options' , 1 RECONFIGURE -- Must run this to make the change effective .
2.8.1.7
The sp_congure USER OPTIONS value is a single integer which is a bitset specifying global defaults for 15 settings that affect each users session (connection). A user may override each setting using the SET statement. See discussion and examples of sp_congure user options on page 202. Example:
SQL
EXEC sp_configure
181
minimum ----0 0
cong_value ----------1 0
2.8.1.8
Here is the short answer to this question: They become effective when run_value matches cong_value, which depends on the option. All sp_congure changes need RECONFIGURE to be run to become effective. - Two options ( 'allow updates' and 'recovery interval' ) sometimes require RECONFIGURE WITH OVERRIDE to be run (see RECONFIGURE below). Some options also require server stop and restart as indicated in Table 2-76. The following do not need server stop and restart. allow updates cost threshold for parallelism cursor threshold index create memory (KB) max degree of parallelism max server memory (MB) max text repl size (B) max worker threads min memory per query (KB) min server memory (MB) network packet size (B) query governor cost limit query wait (s) recovery interval (min) remote login timeout (s) remote proc trans remote query timeout (s) show advanced options user options default full-text language? default language? nested triggers? two digit year cutoff?
When using sp_congure, you must always run either RECONFIGURE (or RECONFIGURE WITH OVERRIDE for the two indicated above) after setting a conguration option.
182
Example 1: RIDE.
SQL
EXEC sp_configure
'allow updates'
Result
minimum -----------0
Result
minimum -----------0
Result
minimum -----------0
183
Example 2:
SQL
The 'll factor' option also requires server stop and restart
EXEC sp_configure
'fill factor'
Result
minimum ---------0
maximum -----------100
cong_value --------------0
run_value ---------0
Result
minimum ---------0
maximum -----------100
cong_value --------------80
run_value ----------0
Option ll factor requires recongure then server stop and restart so the cong_value is shown as changed but not the run_value.
SQL
'fill factor'
Result
minimum ---------0
maximum -----------100
cong_value --------------80
run_value ----------0
Still no change until we stop and restart the server, which we do now.
184
SQL
EXEC sp_configure
Result
minimum ---------0
maximum -----------100
cong_value --------------80
run_value ----------80
2.8.1.9
RECONFIGURE
The recongure command updates the currently congured value of a conguration option changed with the sp_congure system stored procedure (the cong_value column in the sp_congure result set). Some conguration options require a server stop and restart to update the currently running value. Therefore, RECONFIGURE does not always update the currently running value (the run_value column in the sp_congure result set) for a changed conguration value. Syntax
RECONFIGURE [ WITH OVERRIDE ]
2.8.1.10
The recongure command without the override option species that, if the conguration setting does not require a server stop and restart, the currently running value should be updated. Afterward the cong_value and run_value should be the same for those options not requiring server stop and restart. RECONFIGURE also checks the new conguration value for either invalid values or nonrecommended values. 2.8.1.11 RECONFIGURE WITH OVERRIDE
Without OVERRIDE, RECONFIGURE is for allow updates and recovery interval only. This allows invalid or nonrecommended values to be to be set for: allow updatesdefault of 0 does not allow updates to system tables using DML (INSERT, UPDATE, DELETE). System procedures must be used. Setting to 1 is not recommended and requires WITH OVERRIDE. recovery intervaldefault is 0 (self-conguring), recommended is 0 or 1 to 60. The value is the maximum number of minutes to recover each database. Over 60 minutes is not recommended and requires WITH OVERRIDE.
185
Example:
SQL
EXEC sp_configure
'recovery interval'
Result
minimum ----------0
maximum ----------32767
cong_value -----------0
run_value ---------0
EXEC sp_configure
Result
DBCC execution completed. If DBCC printed error messages, contact your system administrator. Conguration option 'recovery interval (min)' changed from 0 to 120. Run the RECONFIGURE statement to install.
SQL
EXEC sp_configure
'recovery interval'
Result
minimum ----------0
maximum ----------32767
cong_value -----------0
run_value ---------0
5.
186
SQL
Result
RECONFIGURE Server: Msg 5807, Level 16, State 1, Line 2 Recovery intervals above 60 minutes not recommended. Use the RECONFIGURE WITH OVERRIDE statement to force this conguration.
SQL
EXEC sp_configure
Result
minimum ----------0
maximum ----------32767
cong_value -----------120
run_value ---------0
SQL
Result
EXEC sp_configure
'recovery interval'
Result
maximum ----------32767
cong_value -----------120
run_value ---------120
187
2.8.1.12
Primary conguration settings for SQL Server are accessible in Enterprise Manager from the server properties dialog for a selected server as shown in the gure. In EM, right click on the server name and select Properties (see Figure 2-4). Examine the settings available on these tabs and see Books Online for further details.
Figure 2-4 The Server Properties Dialog box for the AMY server.
2.8.2
Most database settings are best left as the default unless there is a specic reason to change. Database settings that you may need to a change occasionally are MULTI_USER and RESTRICTED_USER or SINGLE_USER in order to do maintenance. One may also want to set a specic database to READ_ONLY if its users do not need to change the data. A summary of database conguration statements is given in Figure 2-5. For more detail see Books Online, Index: database options.
188
Conguration settings for each database are assigned with ALTER DATABASE with a SET clause (all settings) Conguration settings for each database are observed using SELECT DATABASEPROPERTYEX( 'dbname' , 'propertykeyword' ) - The propertykeyword is not the same as the ALTER DATABASE keyword. - A complete list of propertykeywords is provided below in Table 2-78 (and in Books Online). - The propertykeyword, if there is one, is repeated in Table 2-77 in the Description column on a separate line and in parentheses. Conguration settings for each database are observed and assigned with Enterprise Manager (primary settings only) - Right click on database name in EM - ServerName - Databases - Databasename and select Properties. When the dialog appears, click on the Options tab.
2.8.2.1
Only ALTER DATABASE with the SET clause, which may be used to change database settings, will be discussed in this section. See page 250 for the main coverage of ALTER DATABASE. See Table 2-77 for a summary of database conguration option keywords. SQL Server 2K database options are set using ALTER DATABASE with a SET clause. In previous versions of SQL Server, database options were set with the sp_dboption system stored procedure. SQL Server 2K continues to support sp_dboption, which has been rewritten to call ALTER DATABASE, but it may not do so in the future. DATABASEPROPERTYEX() may be used to show current settings for database options. Partial Syntax
ALTER DATABASE <termination>] databasename SET <optionspec> [WITH
189
See table
< termination > ::= ROLLBACK AFTER integer [ SECONDS ] | ROLLBACK IMMEDIATE | NO_WAIT
Table 2-77 ALTER Database Conguration Option Keywords
Has Session Setting
d
<optionspec> Keyword for both ALTER DATABASE and SET Database State Options abc
Database Default
Description (DATABASEPROPERTYEX keyword) See also Books Online: DATABASEPROPERTYEX and Setting Database Options
No
MULTI_ USER
Determines who may connect to the specied database. Example below. (UserAccess) When put OFFLINE the database is shutdown and can not be accessed. (Status) When put READ_ONLY users can not modify the database. (Updateability)
No
ONLINE
READ_ONLY | READ_WRITE
No
READ_ WRITE
Cursor Options CURSOR_CLOSE_ON_COMMIT { ON | OFF } Yes OFFb ON: (SQL-92) All open cursors are closed when a transaction is committed. OFF: Cursors must be closed explicitly and may cross transaction boundaries. (IsCloseCursorsOnCommitEnabled) GLOBALcursors default to GLOBAL LOCALcursors default to LOCAL. Cursors may always be explicitly dened as LOCAL or GLOBAL. See Cursors page 638. (IsLocalCursorsDefault)
No
GLOBAL
190
Table 2-77
<optionspec> Keyword for both ALTER DATABASE and SET Automatic Options AUTO_CLOSE { ON | OFF } Comment from Books Online The AUTO_CLOSE option is useful for desktop databases because it allows database les to be managed as normal les. They can be moved, copied to make backups, or even emailed to other users. The AUTO_CLOSE option should not be used for databases accessed by an application that repeatedly makes and breaks connections to SQL Server. The overhead of closing and reopening the database between each connection will impair performance. AUTO_CREATE_STATISTICS { ON | OFF }
No
ON for SS 2000 Desktop Engine (MSDE 2000) OFF for all other SS 2000 editions
ON: the database is closed and shut down cleanly when the last user of the database exits and when all processes in the database are complete, thereby freeing any resources. The database reopens automatically when a user tries to use the database again. OFF: the database remains open even if no users are currently using it. (IsAutoClose)
No
ON
ON: statistics are automatically created on columns without an index used in a predicate so as to speed the query. OFF: statistics not automatically created; but they can be manually created. (IsAutoCreateStatistics) ON: existing statistics are automatically updated when they become out-of-date. OFF: statistics are not automatically updated but can be manually updated. (IsAutoUpdateStatistics) ON: the database data and log les are periodically checked for unused space. OFF: les are not periodically checked for unused space. It is not possible to shrink a read-only database. (IsAutoShrink)
AUTO_UPDATE_STATISTICS { ON | OFF }
No
ON
AUTO_SHRINK { ON | OFF } Default: ON for SS 2000 Desktop Engine (MSDE 2000) OFF for all other SS 2000 editions
No
191
Table 2-77
<optionspec> Keyword for both ALTER DATABASE and SET ANSI SQL-92 Compliance Options ANSI_NULL_DEFAULT { ON | OFF} This keyword applies to ALTER DATABASE only. The corresponding session SET keywords are ANSI_NULL_DFLT_ON and ANSI_NULL_DFLT_OFF ANSI_NULLS { ON | OFF }
No
Sets Default Nullability of a column If ON is specied, CREATE TABLE follows SQL-92 rules to determine whether a column allows null values. OLE DB and ODBC set this to ON. (IsAnsiNullDefault)
Yes
ON: SQL-92 behavior, comparing to NULL with = and <> returns NULL. OFF: NULL = NULL returns TRUE. (IsAnsiNullsEnabled)
ANSI_PADDING { ON | OFF }
Yes
ON: Does NOT trim explicit trailing blanks in varchar and trailing zeros in varbinary columns. OFF: Does trim them. Books Online Recommendation: Leave t ON. (IsAnsiPaddingEnabled)
ANSI_WARNINGS { ON | OFF }
Yes
ON means SQL-92 standard behavior of raising error messages or warnings for conditions like divide-by-zero and arithmetic overow. (IsAnsiWarningsEnabled) ON: Terminates a query if overow or divide-by-zero occurs during query. OFF: Warning message displayed and processing continues. (IsArithmeticAbortEnabled)
ARITHABORT { ON | OFF } Default: Query Analyzer sets ARITHABORT to ON for each session Miscellaneous SET Options CONCAT_NULL_YIELDS_NULL
Yes
OFFc
Yes
ON: Concatenating NULL yields NULL (ON) versus empty string (OFF) (IsNullConcat)
192
Table 2-77
<optionspec> Keyword for both ALTER DATABASE and SET NUMERIC_ROUNDABORT { ON | OFF }
QUOTED_IDENTIFIER { ON | OFF }
Yes
No
No
See Recovery Models page 559. (Recovery) ON causes the database to be marked as suspect if a torn page is found during recovery. If a torn page is found the database should be restored. This option should be left ON. (IsTornPageDetectionEnabled)
TORN_PAGE_DETECTION { ON | OFF } A torn page occurs when not all 16 sectors (512 bytes) of the 8 KB database page can be written to disk, as in power loss. a. b. c. d.
No
OLE DB and ODBC explicitly set this to ON for each client connection overriding database setting. See p. 215. OLE DB and ODBC explicitly set this to OFF for each client connection overriding database setting. See p. 215. Query Analyzer sets ARITHABORT to ON for each of its connections overriding database setting. See p. 216. Database Options marked with Yes in the Session Setting column have corresponding session (connection) options which, if SET at the session level, take precedence over the database setting. See page 203.
ExamplesALTER DATABASE to Change UserAccess of a Database Database Access Modes determines who may connect to the specied database as follows. MULTI_USER: Allows all users with database access privilege to connect RESTRICTED_USER: Allows only members of db_owner, dbcreator and sysadmin SINGLE_USER: Allows only the user issuing the ALTER DATABASE statement
2.8.2.2
193
Examples:
SQL
You may read current access mode of the pubs database as shown.
Result
--------------------------MULTI_USER
Now set the access mode to any of the three values using ALTER DATABASE.
SQL
SET MULTI_USER
The following form waits indenitely if unqualied users are connected to the database.
S Q L ALTER DATABASE pubs
SET SINGLE_USER
WITH NO_WAIT causes the ALTER DATABASE to fail immediately if unqualied users are connected to the specied database.
SQL
This command returns immediately. The new access can be seen with the following.
SQL
Result
--------------------------SINGLE_USER
194
WITH ROLLBACK IMMEDIATE forces immediate rollback of open transactions and terminates the connections of all unqualied users of the database.
SQL
WITH ROLLBACK AFTER integer [SECONDS] rolls back transactions and breaks the connections of all unqualied database users after the specied number of seconds.
SQL
DATABASE pubs RESTRICTED_USER WITH ROLLBACK AFTER 60 DATABASE pubs SINGLE_USER WITH ROLLBACK AFTER 60 SECONDS
Example:
SQL
Example: Set database mydb1 access to RESTRICTED_USER (allowing only members of sysadmin and dbcreator xed server roles and db_owner xed database roles). Unauthorized users currently connected will be unceremoniously disconnected and open transactions rolled back 60 seconds from the time the statement is executed.
SQL
195
MULTI_USER
The code dbo stands for database owner, the predened user name in each database who is able to perform all database operations. Any sysadmin server role member becomes dbo inside each database. 2.8.2.3 DATABASEPROPERTYEXDisplays Database Settings This function returns the current setting of the specied property in the specied database. Syntax
SELECT DATABASEPROPERTYEX( 'dbname' , 'propertykeyword' )
Table 2-78 below lists all of the DATABASEPROPERTYEX property keywords, and some examples appear below the table. Most of these keywords were also listed above in the ALTER DATABASE keyword table (Table 2-77). A few examples were given there. Additional database options are listed in Table 2-78.
Table 2-78 Keywords for DATABASEPROPERTYEX
Description
Default collation name for the database. Database follows SQL-92 rules for allowing null values. All comparisons to a null evaluate to null.
Value Returned
Collation name 1=TRUE, 0=FALSE, NULL=Bad input 1=TRUE, 0=FALSE, NULL=Bad input 1=TRUE, 0=FALSE, NULL=Bad input 1=TRUE, 0=FALSE, NULL=Bad input 1=TRUE, 0=FALSE, NULL=Bad input 1=TRUE, 0=FALSE, NULL=Bad input
IsAnsiNullsEnabled
IsAnsiPaddingEnabled
Strings are padded to the same length before comparison or insert. Error or warning messages are issued when standard error conditions occur. Queries are terminated when an overow or divide-by-zero error occurs. Database shuts down cleanly and frees resources after the last user exits.
IsAnsiWarningsEnabled
IsArithmeticAbortEnabled
IsAutoClose
196
Table 2-78
Value Returned
1=TRUE, 0=FALSE, NULL=Bad input 1=TRUE, 0=FALSE, NULL=Bad input 1=TRUE, 0=FALSE, NULL=Bad input 1=TRUE, 0=FALSE, NULL=Bad input 1=TRUE, 0=FALSE, NULL=Bad input 1=TRUE, 0=FALSE, NULL=Bad input 1=TRUE, 0=FALSE, NULL=Bad input 1=TRUE, 0=FALSE, NULL=Bad input 1=TRUE, 0=FALSE, NULL=Bad input 1=TRUE, 0=FALSE, NULL=Bad input 1=TRUE, 0=FALSE, NULL=Bad input 1=TRUE, 0=FALSE, NULL=Bad input 1=TRUE, 0=FALSE, NULL=Bad input 1=TRUE, 0=FALSE, NULL=Bad input FULL = full recovery model BULK_LOGGED = bulk logged model SIMPLE = simple recovery model 0 = Database uses Windows collation >0 = SQL Server sort order ID
IsAutoShrink
IsAutoUpdateStatistics
IsCloseCursorsOnCommitEnabled IsFulltextEnabled
IsInStandBy
Database is online as read-only, with restore log allowed. Cursor declarations default to LOCAL.
IsLocalCursorsDefault
IsMergePublished
The tables of a database can be published for replication, if replication is installed. Null concatenation operand yields NULL.
IsNullConcat
IsNumericRoundAbortEnabled
Errors are generated when loss of precision occurs in expressions. Double quotation marks can be used on identiers. Recursive ring of triggers is enabled.
IsQuotedIdentiersEnabled
IsRecursiveTriggersEnabled
IsSubscribed
Database can be subscribed for publication. SQL Server detects incomplete I/O operations caused by power failures, etc. Recovery model for the database.
IsTornPageDetectionEnabled
Recovery
SQLSortOrder
197
Table 2-78
Value Returned
ONLINE = database is available OFFLINE = db was taken ofine RESTORING = db is being restored RECOVERING = db is recovering and not yet ready for queries SUSPECT = db cannot be recovered READ_ONLY READ_WRITE SINGLE_USER = only one user of db_owner, dbcreator, sysadmin RESTRICTED_USER = any of db_owner, dbcreator, sysadmin MULTI_USER = all users Integer = Database is open NULL = Database is closed
Updateability
UserAccess
Version
Database Version number for internal use only by SQL Server tools.
Example:
SQL
SELECT DATABASEPROPERTYEX(
'pubs' ,
'IsFulltextEnabled' )
Result
----------------0
This says that full text searches are not presently enabled on the pubs database. Many DATABASEPROPERTYEX keywords are also listed in the ALTER DATABASE table in the preceding section.
SQL
SELECT DATABASEPROPERTYEX(
'pubs' ,
'UserAccess' )
198
SQL
(cont.)
Result
----------------MULTI_USER
2.8.2.4 Database Level Settings in Enterprise Manager Primary conguration settings for SQL Server databases are accessible in Enterprise Manager from the server properties dialog for a selected server and database.
Expand the Console Tree in Enterprise Manager under the desired server. Select your Server Name Databases <database name> Right click on the <database name> and select Properties. The tabs available for the database Properties dialog are: General Data Files Transaction Log Filegroups Options Permissions
Options tabThe options tab, shown in Figure 2-6, has some settings that can be set from this tab or from the command line using ALTER DATABASE (see page 187).
Access Restrict Access: db_owner, dbcreator, sysadmin only Read-only Recovery Model: Simple or Bulk-Logged or Full or Single user
Settings to allow or disallow features such as ANSI NULL default. Compatibility Level: 60 or 65 or 70 or 80 sp_dboptionBrief Description as It Is Replaced by ALTER DATABASE The stored procedure sp_dboption displays or changes database options. It is provided only for backward compatibility and might not appear in future releases of SQL Server. ALTER DATABASE is now recommended. sp_dboption should not be used on either the master or tempdb databases.
2.8.2.5
Syntax
sp_dboption [ [ @dbname = ] 'database' ] [ , [ @optname = ] 'option_name' ] [ , [ @optvalue = ] 'value' ]
199
These settings display or change global conguration settings for the current server. sp_dboption may be executed with 0, 1 or 2 arguments as follows. 0 arguments: Lists all conguration setting names addressable with sp_dboption 1 argument: Displays the current settings that are set for the database specied 2 arguments: Displays the current setting of the specied option in the named database 3 arguments: Sets the specied option in the named database to the specied value
200
Examples:
SQL
EXEC sp_dboption
Result
Settable database options: ----------------------------------ANSI null default ... dbo use only ...
SQL
pubs
Result
The following options are set: ----------------------------------trunc. log on chkpt. torn page detection auto create statistics auto update statistics
SQL
Result
201
SQL
turn in on'
Result
2.8.2.6 Database Compatibility Level sp_dbcmptlevel MSS 2000 (version 8.0) implements SQL-92 more thoroughly than earlier versions, and it also adds new keywords. When upgrading a database from an earlier version of MSS, especially MSS 6.0 or 6.5, some of these changes may conict with your existing application code. Though running on SQL Server 2K, you may set a database to behave like an earlier version of SQL by using sp_dbcmptlevel system stored procedure. This will keep your production database operational while giving you a chance to rewrite your code. See Table 2-79.
Table 2-79 Compatibility Levels
Version SQL Server 2K (version 8.0) SQL Server 7.0 SQL Server 6.5 SQL Server 6.0
Compatibility Level 80 70 65 60
sp_dbcmptlevel sets the specied database to behave according to the specied version of SQL Server.
Syntax
sp_dbcmptlevel [ [ @dbname = ] name ] [ , [ @new_cmptlevel = ] version ]
Argument version The version of SQL Server with which the database is to be made compatible. The value must be 80, 70, 65 or 60. References Books Online: sp_dbcmptlevel; compatibility issues, overview
202
2.8.3
Session or connection settings are values that apply to the current connection of a client program for the SQL Server database engine. They will remain in effect until the end of the session (when the connection is closed) or a SET statement is issued as described below. Session settings that can be quite useful for debugging or performance testing include NOEXEC, NOCOUNT, PARSEONLY, SHOWPLAN_xxx, STATISTICS xxx, etc. These options are well worth studying and testing to see the information they provide. To determine how your current session settings are determined, I suggest starting with the OLE DB and ODBC driver connection settings (see page 215) and Query Analyzer connection settings (see page 216) and then reading the section on Which Session Setting Is in Effect? (see page 219). Some session settings will be changed by the client libraries (OLE DB and ODBC) and by Query Analyzer, if that is the client program. And all session option settings may be changed by the user using the SET command. Figure 2-7 is a summary of session conguration statements. The pages that follow contain detailed information about the information in the box. 2.8.3.1 sp_congure user options sp_congure is a server setting that affects future sessions. The options allow a user to set all 15 default session query processing options applicable ONLY FOR NEW LOGIN SESSIONS (CONNECTIONS). Anyone currently logged in is not affected until the next time they log in. The sp_congure USER OPTIONS value is a single integer representing a bitset specifying global defaults for 15 settings that affect each users session (connection). A user may override any setting by changing it with the SET statement. Executing sp_congure 'user options', value assigns default settings for new logins. Any user may use SET to override any setting for the current session. If a user has SET an option then that setting is used for the current session Recall ODBC and OLE DB set some options when connecting or if the current database has a setting for the option then it will be used or if sp_congure 'user options' for the option is in effect it will be used or the default setting for the option will be used. The options settable by sp_congure 'user options' and the setting value are the same as those visible with @@OPTIONS (page 208) and are listed in Table 2-80.
203
New sessions inherit server or database options and may change some of them. Conguration settings for the current session or connection are changed using sp_congure 'user options' Assigns default session settings, which are in effect unless overridden by a SET command. See full description page 204. Client libraries often issue SET statements for each connection. See OLE DB and ODBC driver connection settings, page 215. Query Analyzer additionally assigns SET options, which may be congured by the user. See Query Analyzer connection settings, page 216. SET (page 204) Conguration settings for each session or connection are observed using @@OPTIONS Displays integer bitset of set options (page 209) DBCC USEROPTIONSDisplays all options currently set (page 210) SELECT SESSIONPROPERTY ( 'option' ) Displays an option setting (page 211) Session Conguration Functions Each displays an option setting (page 214) Primary settings for each Query Analyzer connection are observed and changed using Query Analyzer primary session settings. See also Books Online: SET Options That Affect Results. Figure 2-7 Session Conguration Statements Summary.
Syntax
sp_configure 'user options' [ , [ @configvalue = ] value ]
value = The sum of the values of all options desired to be set for future new logins. Remember to run RECONFIGURE to make the change effective.
Table 2-80
Value
1 2
DISABLE_DEF_CNST_CHK IMPLICIT_TRANSACTIONS
CURSOR_CLOSE_ON_COMMIT
ANSI_WARNINGS
204
Table 2-80
Value
16 32 64
128
ARITHIGNORE
256
QUOTED_IDENTIFIER
512
NOCOUNT
1024
ANSI_NULL_DFLT_ON
2048
ANSI_NULL_DFLT_OFF
4096
CONCAT_NULL_YIELDS_NULL
8192
NUMERIC_ROUNDABORT
16384
XACT_ABORT
For an example of the use of sp_congure 'user options', see page 219. 2.8.3.2 SET The SET statement assigns current session (connection) option settings. These settings are listed in Table 2-81.
Table 2-81 SET Statement Options
@@ OPTIONS
Default Setting
a,b
valued
See p. 209
Description
7 (Sunday)
205
Table 2-81
Default Setting
mdy
valued
See p. 209
Description
Sets the order of (month/day/year) for entering datetime or smalldatetime data. Ex: SET DATEFORMAT mdy
Locking Options DEADLOCK_PRIORITY { LOW | NORMAL | @deadlock_var } NORMAL Controls how session reacts if in deadlock. LOW Current session is victim NORMAL Let SQL Server decide @deadlock_var - 3=LOW, 6=NORMAL Species the number of milliseconds a statement waits for a lock to be released. See also Books Online: SET Options OFFa 4096 ON means concatenating with NULL yields NULL versus empty string (OFF) OLE DB and ODBC set this to ON when making a new connection. For backward compatibility only Species checking for compliance with the FIPS 127-2 standard, and species SQL-92 Entry, Full or Intermediate Level or None. OFF ON allows explicit values to be inserted into an identity column. Species the session language including datetime formats and system messages. EXEC sp_helplanguage list languages Example: SET LANGUAGE Deutsch PRINT CAST ( '2003-05-10 14:35' As DATETIME ) Okt 5 2003 2:35PM SET LANGUAGE us_english PRINT CAST ( '2003-05-10 14:35' As DATETIME ) May 10 2003 2:35PM OFFSETS keyword_list Use only in DB-Library applications. See Books Online.
OFF
IDENTITY_INSERT
206
Table 2-81
Default Setting
valued
See p. 209
Description
OFFc
64
Terminates a query if overow or divideby-zero occurs during query. ON means Error Message is returned from overow or divide-by-zero. Returns only meta data, no data
OFF
128
FMTONLY NOCOUNT
Stops the message with number of rows affected from being returned. Parse and compile but do not execute.
NOEXEC NUMERIC_ROUNDABORT
Sets level of error reporting when rounding causes a loss of precision. Parse but do not execute from now on. sysadmin setting to disallow queries whose estimated run time exceeds the spec ied number of seconds. Default is 0, unlimited time, so all queries run. Stops processing the query after the specied number of rows. Species the size in bytes of text and ntext data returned from a SELECT Either 0 or 4096 sets to default of 4 KB.
ROWCOUNT integervalue
0 (unlim)
TEXTSIZE integervalue
4 KB
SQL-92 Settings Statements ANSI_DEFAULTS n/a ON sets all options in this section to ON except ANSI_NULL_DFLT_OFF to OFF. OFF leaves ANSI_NULL_DFLT_OFF unchanged and sets rest to OFF ANSI_NULLS OFFa 32 Sets ANSI SQL-92 compliant behavior in effect when comparing to NULL with equals (=) and not equal to (<>) . Only one of these two can be ON at a time. So setting one ON sets the other OFF. Both may be set to OFF at the same time.
ANSI_NULL_DFLT_ON
OFFa
1024
207
Table 2-81
Default Setting
OFF ONa
valued
See p. 209
Description
2048 16 Set blank padding for values shorter than the dened size of the column and for values that have trailing blanks in char and binary data. ON means SQL-92 standard behavior of raising error messages or warnings for conditions like divide-by-zero and arithmetic overow. As described by the name when ON 256 See QUOTED_IDENTIFIER discussion with examples page 44. See details with Transactions below.
ANSI_WARNINGS
OFFa
CURSOR_CLOSE_ON_COMMIT QUOTED_IDENTIFIER
OFF
Makes the query optimizer process a join in the same order as tables appear in the FROM clause of a SELECT statement. ON: does not execute SQL statements but instead returns the detailed execution plan and estimates of the resource requirements to execute the statements. ON: does not execute SQL statements but instead returns the execution plan for the statements. ON: displays the disk activity generated by Transact-SQL statements when executed. ON: Displays prole information for a statement including number of rows produced and number of times the query ran. Displays the time in milliseconds to parse, compile and execute each statement.
SHOWPLAN_ALL
OFF
SHOWPLAN_TEXT
OFF
STATISTICS IO
OFF
STATISTICS PROFILE
OFF
STATISTICS TIME
OFF
208
Table 2-81
Default Setting
valued
See p. 209
d
Description
See Transaction Control, page 529. IMPLICIT_TRANSACTION mode ON requires an explicit COMMIT/ROLL BACK for each transaction. OLE DB and ODBC set this to OFF when making a new connection. When OFF, AUTOCOMMIT MODE is in effect. See Transaction Control, page 529. Species that when a local transaction is active, executing a remote stored procedure starts a Transact-SQL distributed transac tion managed by the Microsoft Distributed Transaction Manager (MS DTC). Controls the default locking behavior for the session (connection). See Transaction Control, p. 529.
OFFb
REMOTE_PROC_TRANSACTIONS
OFF
TRANSACTION ISOLATION LEVEL { READ UNCOMMITTED | READ COMMITTED | REPEATABLE READ | SERIALIZABLE } XACT_ABORT
READ COMMITTED
OFF
16384
ON: rolls back the entire transaction if a statement raises a run-time error OFF: rolls back just the statement and the transaction continues.
a. b. c. d.
OLE DB and ODBC explicitly set this to ON for each client connection overriding database setting. See p. 215. OLE DB and ODBC explicitly set this to OFF for each client connection overriding database setting. See p. 215. Query Analyzer sets ARITHABORT to ON for each of its connections overriding database setting. See p. 216. See @@OPTIONS, p. 208.
2.8.3.3
@@OPTIONS
The value @@OPTIONS returns a bitmask of session options from Table 282 SET for the current connection. The value includes all options currently SET by virtue of server settings including sp_congure 'user options' and SET operations including those set by OLE DB and ODBC drivers (see page 215). Bit positions in @@OPTIONS are identical to those in sp_congure 'user options' but the @@OPTIONS value represents current session settings of the options. @@OPTIONS reports on the following 15 settings which includes the 7 options that SESSIONPROPERTY() reports. So @@OPTIONS is more complete.
209
Table 2-82
@@OPTIONS Settings
Option Default a,b OFF OFFb OFFb OFFa ONa OFFa OFFc OFF OFFa OFF OFFa OFF ONa OFF OFF 1 2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 @@OPTIONS Value
DISABLE_DEF_CNST_CHK IMPLICIT_TRANSACTIONS CURSOR_CLOSE_ON_COMMIT ANSI_WARNINGS ANSI_PADDING ANSI_NULLS ARITHABORT ARITHIGNORE QUOTED_IDENTIFIER NOCOUNT ANSI_NULL_DFLT_ON ANSI_NULL_DFLT_OFF CONCAT_NULL_YIELDS_NULL NUMERIC_ROUNDABORT XACT_ABORT
a. b. c.
OLE DB and ODBC explicitly set this to ON for each client connection overriding database setting. See p. 215. OLE DB and ODBC explicitly set this to OFF for each client connection overriding database setting. See p. 215. Query Analyzer sets ARITHABORT to ON for each of its connections overriding database setting.. See p. 216.
See more examples displaying current session (connection) settings on page 220.
SQL
SELECT @@OPTIONS & 4096 -- Shows that CONCAT_NULL_YIELDS_NULL is currently ON
Result
4096
210
SQL
SELECT @@OPTIONS -- Shows the integer bitmask which includes all @@OPTIONS currently ON
Result
5496
SQL
SET CONCAT_NULL_YIELDS_NULL OFF SELECT @@OPTIONS & 4096 -- Shows that CONCAT_NULL_YIELDS_NULL is currently OFF
Result
0
SQL
SELECT @@OPTIONS -- Shows the integer bitmask which includes all @@OPTIONS currently ON
Result
1400
2.8.3.4
DBCC USEROPTIONS
DBCC USEROPTIONS returns all SET options which are active (set) for the current session (connection). Syntax
DBCC USEROPTIONS
Example:
SQL
DBCC USEROPTIONS
211
SQL
(cont.)
Result
Set Option Value -------------------------------------------------------------textsize 64512 language us_english dateformat mdy daterst 7 quoted_identier SET ansi_null_dt_on SET ansi_defaults SET ansi_warnings SET ansi_padding SET ansi_nulls SET concat_null_yields_null SET DBCC execution completed. If DBCC printed error messages, contact your system administrator.
2.8.3.5 SESSIONPROPERTY SESSIONPROPERTY returns the current setting of one of the seven session options listed in Table 2-83. Returns on the setting are listed in Table 2-84. Returns 1 if SET, 0 if NOT SET and NULL if the input option name was invalid. Syntax
SESSIONPROPERTY ( 'option' )
Arugment option The SESSIONPROPERTY option names are the same as for ALTER DATABASE.
Table 2-83 SESSIONPROPERTY Options
Option Name ANSI_NULLS ANSI_PADDING ANSI_WARNINGS ARITHABORT Option Name CONCAT_NULL_YIELDS_NULL NUMERIC_ROUNDABORT QUOTED_IDENTIFIER
212
For the meaning of each option see ANSI SQL-92 Compliance Options, see page 191.
Table 2-84 Returns
Option Is Currently ON OFF Invalid Option name Return Value 1 O NULL
SELECT
SESSIONPROPERTY( 'QUOTED_IDENTIFIER' )
-- Option ON returns 1
Result
-------1
SQL
SELECT
SESSIONPROPERTY( 'NUMERIC_ROUNDABORT' )
Result
-------0
SQL
SELECT NULL SESSIONPROPERTY( 'Foo_Foo' ) -- Invalid input option name, returns
Result
-------NULL
2.8.3.6 Comparing @@OPTIONS, DBCC USEROPTIONS and SESSIONPROPERTY() The following methods show current session settings as indicated:
213
@@OPTIONS enables you to determine the setting of a specic option but it requires looking up the option number of interest and doing a bitwise AND to determine if a specic setting is on or off. Only the settings that have a value in the @@OPTIONS column of Table 2-81, page 204, may be read with this function. DBCC USEROPTIONS is convenient since it reports all options that are currently set. It is silent on options not currently set. SESSIONPROPERTY() returns the one option setting specied, as does @@OPTIONS, and it uses the same option keyword as SET, so its more consistent in its use. But it is less complete than @@OPTIONS because it only reports on the seven options listed in Table 2-83. Examples Comparing the Three:
SQL
is currently ON
Result
-------1024
SQL
Result
-------4096
SQL
SELECT
Result
-------NULL
214
SQL
SELECT SESSIONPROPERTY( 'CONCAT_NULL_YIELDS_NULL' ) -- Option ON returns 1
Result
-------1
SQL
DBCC USEROPTIONS
Result
Set Option Value --------------------------------------------------------------ansi_null_dt_on SET ... concat_null_yields_null SET DBCC execution completed. If DBCC printed error messages, contact your system administrator.
2.8.3.7 Session Conguration Functions These built-in scalar functions return the current session setting indicated by the name. Table 2-85 provides a description.
Table 2-85 Session Conguration Functions
Description Returns the current value of the SET DATEFIRST parameter, which indicates the specied rst day of each week: 1 for Monday, 2 for Wednesday, and so on through 7 for Sunday. Returns the value of the current timestamp data type for the current database. This timestamp is guaranteed to be unique in the database. Returns the local language identier (ID) of the language currently in use. Returns the name of the language currently in use. Returns the current lock time-out setting, in milliseconds, for the current session.
215
Table 2-85
@@SPID @@TEXTSIZE
@@VERSION
Example:
SQL
SELECT @@SPID -- Returns the id SQL Server has assigned the current session (connection)
Result
51
2.8.3.8 OLE DB and ODBC Driver Connection Settings OLE DB and ODBC drivers make the following settings for every new connection.
216
ON
CONCAT_NULL_YIELDS_NULL ANSI_NULL_DEFAULT ANSI_DEFAULTS -- which set all of the following to ON ANSI_NULLS BOL -- 'SET Options' for ANSI_DEFAULTS ANSI_NULL_DFLT_ON -- sets ANSI_NULL_DFLT_OFF to OFF ANSI_PADDING -- See page 112. ANSI_WARNINGS QUOTED_IDENTIFIER
OFF
CURSOR_CLOSE_ON_COMMIT IMPLICIT_TRANSACTIONS
See each item under SETTING DATABASE OPTIONS SET CONCAT_NULL_YIELDS_NULL for ODBC/OLE DB sessions settings. ODBC and OLE DB rst turn on the above settings identied as ON. Then they turn off the two items identied as OFF (they were set to ON when ANSI_DEFAULTS was set ON). See SET ANSI_DEFAULTS for ODBC/OLE DB sessions settings. These settings will be in effect for every ODBC and OLE DB client unless you change them with an explicit SET statement. See Query Analyzer additions next. 2.8.3.9 Query Analyzer Connection Settings
Query Analyzer uses ODBC, so it starts with the ODBC settings listed above in effect, then it sets the following additional options as shown. ON
ARITHABORT
OFF
NOCOUNT NOEXEC PARSEONLY SHOWPLAN_TEXT STATISTICS TIME STATISTICS IO
The net result of these default actions can be conrmed by executing this statement in Query Analyzer.
217
SQL
Result
Set Option -------------------------------textsize language dateformat daterst quoted_identier arithabort ansi_null_dt_on ansi_defaults ansi_warnings ansi_padding ansi_nulls concat_null_yields_null
Value -------------64512 us_english mdy 7 SET SET SET SET SET SET SET SET
These settings, except the rst four, are set explicitly by ODBC and Query Analyzer as just described. The rst four were inherited from the defaults as summarized in the next section. See also Books Online: Using SET Options in SQL Query Analyzer. 2.8.3.10 Changing Query Analyzer Default Connection Settings
You may change the default connection settings for your own Query Analyzer from QueryCurrent Connection Properties, which opens the dialog shown in Figure 2-8. Check a box for ON or uncheck for OFF and click Apply. Table 286 lists the default SET session settings made by Query Analyzer.
Table 2-86 Summary of All Default SET Session Settings Made by Query Analyzer
Option Set nocount Set noexec Set parseonly OFF OFF OFF Setting
218
Summary of All Default SET Session Settings Made by Query Analyzer (cont.)
Option Setting ON 0 ON ON OFF OFF OFF
Set concat_null_yields_null Set rowcount Set ansi_defaults Set arithabort Set showplan_text Set statistics time Set statistics 10
219
Table 2-86
Summary of All Default SET Session Settings Made by Query Analyzer (cont.)
Option Setting ON ON ON ON OFF OFF ON
Set ansi_nulls Set ansi_null_dt_on Set ansi_padding Set ansi_warnings Set cursor_close_on_commit Set implicit_transactions Set quoted_identier
2.8.3.11 Which Session Setting Is in Effect? See Which Setting Is the One in Effect? on page 184. What follows is my version of SQL Servers algorithm to decide which setting to use. If a user has SET an option then that setting is used for the current session else if it is an option set by ODBC, OLE DB or Query Analyzer then it will be used (page 215) else if sp_congure 'user options' for the option is in effect it will be used (page 202) else if the current database has a setting for the option then it will be used (page 187) else the SQL Server default setting for the option will be used (page 203). The case numbers are given below to identify what is happening in the following examples. 1. An explicit session SET statement takes precedence and lasts until changed by a new SET statement or the end of the session (connection). 2a. OLE DB and ODBC drivers make the following settings for each new connection. ON
CONCAT_NULL_YIELDS_NULL ANSI_NULL_DEFAULT ANSI_DEFAULTS (which set esach of the following to ON) ANSI_NULLS ANSI_NULL_DFLT_ON (which sets ANSI_NULL_DFLT_OFF to OFF) ANSI_PADDING (see page 102) ANSI_WARNINGS CURSOR_CLOSE_ON_COMMIT IMPLICIT_TRANSACTIONS QUOTED_IDENTIFIER
220
OFF
CURSOR_CLOSE_ON_COMMIT IMPLICIT_TRANSACTIONS
So these settings will be in effect for every ODBC and OLE DB client until you change them with an explicit SET statement. This is true regardless of sp_congure 'user options' or database options assigned with ALTER DATABASE. 2b. Query Analyzer sets ARITHABORT to ON (see page 216). 3. In the absence of 1 or 2, any option set with sp_congure 'user options' will be used. 4. Database default is next (can be set with ALTER DATABASE, pages 189 and 250). 5. Lastly, the SQL Server default will be used, page 202.
Examples Showing which Session Setting Is in Effect Examples are given here to demonstrate Case 1, 2a, 2b, 3 and 4. Each example starts with a new connection and shows user actions, if any, to change a setting and the result.
Example:
SQL
CASE 1Explicit SET CONCAT_NULL_YIELDS_NULL to OFF Open a new database connection to the pubs database.
Result
------0
SQL
SET
COmAT_NULL_YIELDS_NULL
OFF
Result
221
SQL
Result
------0
Table 2-87 contains a summary of actions in order of precedence. The rst Yes from the left takes precedence.
Table 2-87 Case 1 Explicit SET of CONCAT_NULL_YIELDS_NULL Option
Set by OLE DB/ODBC YesON but overridden User Option Would be overridden even if set Database Default OFF but overridden
Example: CASE 2aOLE DB sets CONCAT_NULL_YIELDS_NULL to ON. Open a new database connection to the pubs database.
SQL
SELECT SESSIONPROPERTY( 'CONCAT_NULL_YIELDS_NULL' ) -- Session setting is ON -- (Im using Query Analyzer and OLE DB set it ON)
Result
------1
SQL
222
SQ
(cont.)
Result
------4096
SQL
Result
------0
Table 2-88 contains a summary of actions in order of precedence. The rst Yes from the left takes precedence.
Table 2-88 Case 2aODBC Set of CONCAT_NULL_YIELDS_NULL option
Set by OLE DB/ ODBC Yes ON User Option Would be overridden even if set Database Default OFF but overridden
Explicit SET No
Example:
CASE 2bQuery Analyzer sets ARITHABORT to ON. See Query Analyzer Connection Settings on page 216.
Example: CASE 3NUMERIC_ROUNDABORT, well change User Option to ON. NUMERIC_ROUNDABORT is one of the few options not set by OLE DB or ODBC, so setting the default user option will have a visible effect. In Session 1 below we rst demonstrate that no user options settings are in effect and that NUMERIC_ROUNDABORT defaults to OFF. Then we use sp_congure to set the new user default to ON. Session 1 wont be affected, so we open a new connection as Session 2 and see the new setting is ON.
Session 1 This session observes and changes the sp_congure 'user options',
but only new login sessions will see the effect. Open a new database connection to the pubs database.
223
SQL
EXEC sp_configure
-- (run value is 0)
Result
minimum -----------0
maximum -------------32767
cong_value ----------------0
run_value ----------0
-- For fun, show that the setting in this session is off before and after the user option is changed SELECT SESSIONPROPERTY( 'NUMERIC_ROUNDABORT' ) -- Session setting is OFF
Result
------0
-- Set option for NUMERIC_ROUNDABORT to ON EXEC sp_configure 'user options' , 8192 RECONFIGURE -- Dont forget that reconfigure is required to make the change effective EXEC sp_configure 'user options' -- NUMERIC_ROUNDABORT 'user options is set' (8192)
Result
minimum -----------0
maximum -------------32767
cong_value ----------------8192
run_value ----------8192
224
SQL
-- The setting is on for new sessions, but our NUMERIC_ROUNDABORT option setting is still OFF. SELECT SESSIONPROPERTY( 'NUMERIC_ROUNDABORT' )
Result
------0
Session 2 New Login Sessions (Connections) will see the Change Open NEW Query Analyzer CONNECTION. The session setting is now ON.
SQL
Again show that the Database default for IsNumericRoundAbortEnabled = OFF SELECT DATABASEPROPERTYEX( 'pubs' , 'IsNumericRoundAbortEnabled')
Result
------1
SQL
SELECT
Result
------8192
SQL
-- Show that the Database default for IsNumericRoundAbortEnabled = OFF SELECT DATABASEPROPERTYEX( 'pubs' , 'IsNumericRoundAbortEnabled')
Result
------0
225
-- Clean up by returning User Options to 0 for future sessions EXEC sp_configure 'user options' , 0 RECONFIGURE -- Dont forget that reconfigure is required to make the change effective
Summary of actions in order of precedence: The rst Yes from the left takes precedence.
Table 2-89 Case 3NUMERIC_ROUNDABORT Option Recall 'user option' Affects Only New Sessions
Explicit SET No Set by OLE DB/ ODBC No User Option ON Database Default OFF
Example: CASE 4NUMERIC_ROUNDABORT option, uses the Database default. Open a new database connection to the pubs database.
SQL
Result
------0
SQL
Result
------0
226
SQL
SELECT
Result
------0
Summary of actions in order of precedence: The rst Yes from the left takes precedence.
Table 2-90 Case 4NUMERIC_ROUNDABORT Option Uses Database Option Unless Explicitly Set
Explicit SET No Set by OLE DB/ ODBC No User Option Not set Database Default OFF
2.8.3.12
Example: This example starts with a new SQL Server instance with all default settings. No Options Set: Use isql to connect to the new SQL Server instance using (old) DB-Lib
C:> isql -Usa -P 1> SELECT @@OPTIONS As 2> go OptionSettings ------ -----------0 1> DBCC USEROPTIONS 2> go Set Option Value -------------------------textsize 4096 language us_english dateformat mdy OptionSettings
227
datefirst 7 (4 row(s) affected) DBCC execution completed. If DBCC printed error messages, contact your system administrator.
Add ODBC initial settings: The osql utility uses ODBC to connect to SQL Server. This shows the added options set by ODBC (and OLE DB).
C:> osql -Usa -P OptionSettings
1> SELECT @@OPTIONS As 2> go OptionSettings ------------------5176 1> DBCC USEROPTIONS 2> go
Set OptionValue -----------------------------------textsize 2147483647 language us_english dateformatmdy datefirst 7 ansi_null_dflt_onSET ansi_warningsSET ansi_paddingSET ansi_nullsSET concat_null_yields_nullSET (9 row(s) affected) DBCC execution completed. If DBCC printed error messages, contact your system administrator.
Other examples of SET, DBCC USEROPTIONS, @@OPTIONS, SESSIONPROPERTY()
SQL
PRINT @@OPTIONS
Result
5496
228
SQL
Result
64
SQL
Result
------1
Now turn one option off and re-run the display statements.
SQL
SET
arithabort
OFF
DBCC USEROPTIONS
Result
Set Option ---------------------------textsize language dateformat daterst quoted_identier ansi_null_dt_on ansi_defaults ansi_warnings ansi_padding ansi_nulls concat_null_yields_null (11 row(s) affected)
Value -----------64512 us_english mdy 7 SET SET -- arithabort is missing now SET SET SET SET SET
229
SQL
PRINT @@OPTIONS
Result
5432
SQL
Result
0
SQL
Result
------0
SQL
Result
------0
230
SQL
(cont.)
Result
ARITHABORT: OFF
SQL
SET ARITHABORT ON PRINT 'ARITHABORT: ' + CASE WHEN @@OPTIONS & 64 > 0 THEN 'ON' ELSE 'OFF' END
Result
ARITHABORT: ON
2.8.4
This subject seems unduly complex. Leaving everything default as it comes out of the box seems most useful and is certainly easiest, as in the example CREATE TABLE t below. But here are the details for those who enjoy confusing topics. What I call the default nullability setting means that if a user executes CREATE TABLE or ALTER TABLE to add a new column to a table and does not specify either NULL or NOT NULL explicitly, the default nullability setting determines the nullability of the new column, that is, whether it will be created as NULL or NOT NULL. ANSI SQL-92 standard species default nullability to be nullable, that is, default is NULL. Default nullability is determined by database and session settings. Session setting for ANSI_NULL_DFLT_ON or ANSI_NULL_DFLT_OFF determines the default nullability if either is ON. (Setting one ON sets the other OFF.) Database setting ANSI_NULL_DEFAULT will rule if both session settings are OFF. Bottom line: ODBC drivers and OLE DB providers set ANSI_NULL_DFLT_ON to ON for each connection, so the Query Analyzer and other clients using these libraries behave with new columns defaulting to nullable. ANSI_NULL_DFLT_ON will thus be ON unless you explicitly issue either SET ANSI_NULL_DFLT_ON OFF or SET ANSI_NULL_DFLT_OFF ON This setting will remain in effect for the rest of your connection unless you change it. It is suggested that you do not issue either of these statements and so leave the out-of-the-box defaults intact. In this case, use the following CREATE TABLE statement.
231
CREATE TABLE t ( col1 INT NOT NULL,-- col1 will NOT allow NULL and col2 INT NULL ,-- col2 will allow NULL regardless of settings col3 INT )-- col3 heeds the settings
This would result in col3 being nullable as if it had been created just like col2. If you do issue either of the two SET statements above, then col3 would be non-nullable as if it had been created like col1. The only way for the ANSI_NULL_DEFAULT database setting to have an effect is if SET ANSI_NULL_DFLT_ON OFF is executed, so this database option seems pretty much useless unless you want to issue that statement, or if you can nd a way to connect without using either OLE DB or ODBC. It should be noted for the record that, according to Books Online, Microsoft SQL Server 2000 defaults to NOT NULL. So the database option ANSI_NULL_DEFAULT will be found to be OFF, but again, this is overridden by the OLE DB and ODBC drivers turning ON the ANSI_NULL_DFLT_ON option. 2.8.4.1 How to Set and Determine the Current Nullability Settings The remaining discussion in this section is for completeness and could easily be skipped. Three levels have a hand in determining the ultimate default nullability of a new column.
Server Conguration This affects session options of logins created after the
change.
sp_configure sp_configure 'user options' 'user options' , , 1024 2048 Turns on ANSI_NULL_DFLT_ON Turns on ANSI_NULL_DFLT_OFF
Only one may be ON or both OFF: Setting one ON sets the other OFF. These seem to have no effect since they assign the SET options of the session, but both ODBC and ODE DB set ANSI_NULL_DFLT_ON to true for each session.
Database Conguration
ANSI_NULL_DEFAULT {ON|OFF}
SET
ANSI_NULL_DFLT_ON
232
SET
ANSI_NULL_DFLT_OFF
{ON | OFF}
Only one may be ON or both OFF: Setting one ON sets the other OFF. Also, SET ANSI_DEFAULTS ON includes SET ANSI_NULL_DFLT_ON ON. Settings of the current session in the current database are visible with:
DBCC USEROPTIONS
Shows if ANSI_NULL_DFLT_ON or ANSI_NULL_DFLT_OFF is SET. Show effective nullability settings in specied database in current session.
SELECT GETANSINULL ( [ 'dbname' ] )
Returns 1 if NULL, 0 if NOT NULL is the effective nullability. This is what is used. Example:
SQL
SELECT GETANSINULL ( 'pubs' ) --Shows the default nullability is NULL in pubs db in this session
Result
------1
GETANSINULL() result shows what will be used in a CREATE TABLE. Table 2-91 shows how.
Table 2-91 Default Nullability
Session ANSI_NULL_DFLT_OFF
ON OFF
Session ANSI_NULL_DFLT_ON
ON ON
OFF
ON
OFF
OFF
233
2.8.5
Collation
A collation determines how sort order, case sensitivity and related issues are handled for columns of string data types, that is char, varchar, text, nchar, nvarchar and ntext. SQL Server is installed with a default server level collation. SS 2000 default is, "=Dictionary order, case-insensitive, for use with 1252 Character Set. SQL Server 2K supports different collations for each database down to the level of columns within a table. SQL Server 7.0 allows only a single collation for an instance. The server level default collation will usually be the collation of every database, and the database default will be the default collation of each table column of string data type. The COLLATE clause may specify collation for a database or for a column in a table. A COLLATE clause may be applied at several levels including to a database denition, column denition in a table or string expression These determine comparison and sorting characteristics. See examples of each below. New in SQL Server 2K is the capability to create a new database using the COLLATE clause to specify a different collation.
CREATE DATABASE ALTER DATABASE
<collation_name> <collation_name>
See Books Online for restrictions on changing an existing database collation. Also new with SQL Server 2K is the ability to set a collation for a single column of a table or table variable.
CREATE TABLE tablename ( columnname columndefinition ... ) COLLATE <collation_name>
The code collation_name can be a Windows collation name or SQL collation name, and is applicable only for columns of char, varchar, text, nchar, nvarchar and ntext data types.
234
For a list of all Windows and SQL collations, execute the following sequence.
SQL
Result
name ------------------------Albanian_BIN Albanian_CS_AS ... Latin1_General_CI_AS Latin1_General_CS_AS .... description ------------------------------------------------------------------------------------------Albanian, binary sort Albanian, case-sensitive, accent-sensitive, kanatype-insensitive, width-ins... Latin1-General, case-insensitive, accent-sensitive, kanatype-insensitive, ... Latin1-General, case-sensitive, accent-sensitive, kanatype-insensitive, ...
Note: Unicode was designed to eliminate the code page conversion difculties of the non-Unicode char, varchar and text data types. When you support multiple languages, use the Unicode data types nchar, nvarchar and ntext for all character data. Two example collations follow. Latin1_General_CI_ASCI means case insensitive Latin1_General_CS_ASCS means case sensitive Latin1_General is the Latin alphabet used by western European languages. It is also referred to as the 1252 character set. Example:
SQL
INT
A INT )
VALUES ( 1 , 2 ) WHERE a = 1
235
A -----2
WHERE
a = 2
Result
A ------
WHERE
A = 1
Result
A ------
Result
Server: Msg 208, Level 16, State 1, Line 1 Invalid object name 'table1'.
236
Example: Specify the collation of a string using CASTNotice that CI is for case insensitive and CS is for case sensitive. Without the CAST statement, the database collation is used for comparison.
SQL
USE pubs -- pubs has default case insensitive collation go IF 'abc' = 'ABC' -- We expect TRUE if case insensitive, FALSE if case sensitive PRINT 'TRUE. Yes, they compare' ELSE PRINT 'FALSE. Nope, not the same'
Result
USE mydb -- mydb was created above with case sensitive collation, so it should be FALSE go IF 'abc' = 'ABC' -- We expect TRUE if case insensitive, FALSE if case sensitive PRINT 'TRUE. Yes, they compare' ELSE PRINT 'FALSE. Nope, not the same'
Result
IF 'abc' = CAST( 'ABC' as VARCHAR(10) ) COLLATE PRINT 'Yes, they compare' ELSE PRINT 'Nope, not the same'
Latin1_General_CI_AS
Result
237
Example: Create table columns with a specied collation. Overrides database default.
CREATE TABLE t ( ci VARCHAR(10) COLLATE Latin1_General_CI_AS , cs VARCHAR(10) COLLATE Latin1_General_CS_AS ) INSERT INTO t VALUES ( 'aaa', 'aaa' ); INSERT INTO t VALUES ( 'AAA', 'AAA' ); Column ci is case insensitive for searches, column cs is case sensitive.
SQL
Result
ci ---------aaa AAA
SQL
cs ---------aaa AAA
Result
ci ---------aaa
cs ---------aaa
Use the string CAST on the column to get case insensitive search.
SQL
SELECT * FROM t WHERE 'aaa' =
CAST( cs
AS
VARCHAR(10) ) COLLATE
Latin1_General_CI_AS
238
ci ---------aaa AAA
cs ---------aaa AAA