Data Types in SQL Server 2008

Embed Size (px)

Citation preview

  • 8/3/2019 Data Types in SQL Server 2008

    1/22

    Data Types

    All the data values of a column must be of the same data type. (The only exception

    specifies the values of the SQL_VARIANT data type.) Transact-SQL uses different datatypes, which can be categorized as follows:

    Numeric data types

    Character data types

    Temporal (date and/or time) data types

    Miscellaneous data types

    DECIMAL with VARDECIMAL storage type

    The following sections describe all these categories.

    Numeric Data Types

    Numeric data types are used to represent numbers. The following table shows the list ofall numeric data types:

    Data Type Explanation

    INTEGER

    Represents integer values that can be stored in 4 bytes. The range of

    values is 2,147,483,648 to 2,147,483,647. INT is the short form for

    INTEGER.

    SMALLINTRepresents integer values that can be stored in 2 bytes. The range ofvalues is 32768 to 32767.

    TINYINTRepresents nonnegative integer values that can be stored in 1 byte. The

    range of values is 0 to 255.

    BIGINTRepresents integer values that can be stored in 8 bytes. The range ofvalues is 2^63 to 2^63 1.

    DECIMAL(p,[s])

    Describes fixed-point values. The argument p (precision) specifies the

    total number of digits with assumed decimal point s (scale) digits from

    the right. DECIMAL values are stored, depending on the value ofp, in5 to 17 bytes. DEC is the short form for DECIMAL.

    NUMERIC(p,[s]) Synonym for DECIMAL.

    REAL

    Used for floating-point values. The range of positive values is

    approximately 2.23E 308 to 1.79E +308, and the range of negative

    values is approximately 1.18E 38 to 1.18E + 38 (the value zero canalso be stored).

    FLOAT[(p)]

    Represents floating-point values, like REAL. p defines the precision

    with p < 25 as single precision (4 byte) and p >= 25 as double precision

    (8 byte).

    MONEY Used for representing monetary values. MONEY values correspond to8-byte DECIMAL values and are rounded to four digits after the

  • 8/3/2019 Data Types in SQL Server 2008

    2/22

    decimal point.

    SMALLMONEY Corresponds to the data type MONEY but is stored in 4 bytes.

    Character Data Types

    There are two general forms of character data types. They can be strings of single-byte

    characters or strings of Unicode characters. (Unicode uses several bytes to specify one

    character.) Further, strings can have fixed or variable length. The following characterdata types are used:

    Data Type Explanation

    CHAR[(n)]

    Represents a fixed-length string of single-byte characters, where n is

    the number of characters inside the string. The maximum value ofn is

    8000. CHARACTER(n) is an additional equivalent form for CHAR(n).Ifn is omitted, the length of the string is assumed to be 1.

    VARCHAR[(n)]

    Describes a variable-length string of single-byte characters (0 < n 8000). In contrast to the CHAR data type, the values for the

    VARCHAR data type are stored in their actual length. This data typehas two synonyms: CHAR VARYING and CHARACTER VARYING.

    NCHAR[(n)]

    Stores fixed-length strings of Unicode characters. The main difference

    between the CHAR and NCHAR data types is that each character of

    the NCHAR data type is stored in 2 bytes, while each character of theCHAR data type uses 1 byte of storage space. Therefore, the maximum

    number of characters in a column of the NCHAR data type is 4000.

    NVARCHAR[(n)]

    Stores variable-length strings of Unicode characters. The main

    difference between the VARCHAR and the NVARCHAR data types isthat each NVARCHAR character is stored in 2 bytes, while each

    VARCHAR character uses 1 byte of storage space. The maximum

    number of characters in a column of the NVARCHAR data type is4000.

    Note: The VARCHAR data type is identical to the CHAR data type except for one

    difference: if the content of a CHAR(n) string is shorter than n characters, the rest of the

    string is padded with blanks. (A value of the VARCHAR data type is always stored in its

    actual length.)

    Temporal Data Types

    Transact-SQL supports the following temporal data types:

    DATETIME

    SMALLDATETIME

  • 8/3/2019 Data Types in SQL Server 2008

    3/22

    DATE

    TIME

    DATETIME2

    DATETIMEOFFSET

    The DATETIME and SMALLDATETIME data types specify a date and time, with eachvalue being stored as an integer value in 4 bytes or 2 bytes, respectively. Values of

    DATETIME and SMALLDATETIME are stored internally as two separate numericvalues. The date value of DATETIME is stored in the range 01/01/1753 to 12/31/9999.

    The analog value of SMALLDATETIME is stored in the range 01/01/1900 to

    06/06/2079. The time component is stored in the second 4-byte (or 2-byte forSMALLDATETIME) field as the number of three-hundredths of a second (DATETIME)

    or minutes (SMALLDATETIME) that have passed since midnight.

    The use of DATETIME and SMALLDATETIME is rather inconvenient if you want to

    store only the date part or time part. For this reason, SQL Server 2008 introduces the new

    data types DATE and TIME, which store just the DATE or TIME component of aDATETIME, respectively. The DATE data type is stored in 3 bytes and has the range

    01/01/0001 to 12/31/9999. The TIME data type is stored in 35 bytes and has anaccuracy of 100 nanoseconds (ns).

    The DATETIME2 data type is also a new data type that stores high-precision date and

    time data. The data type can be defined for variable lengths depending on the

    requirement. (The storage size is 68 bytes). The accuracy of the time part is 100 ns. Thisdata type isn't aware of Daylight Saving Time.

    All the temporal data types described thus far don't have support for the time zone. The

    new data type called DATETIMEOFFSET has the time zone offset portion. For thisreason, it is stored in 68 bytes. (All other properties of this data type are analogous tothe corresponding properties of DATETIME2.)

    The date value in Transact-SQL is by default specified as a string in a format like 'mmm

    dd yyyy' (e.g., 'Jan 10 1993') inside two single quotation marks or double quotation

    marks. (Note that the relative order of month, day, and year can be controlled by the SETDATEFORMAT statement. Additionally, the system recognizes numeric month values

    with delimiters of / or .) Similarly, the time value is specified in the format 'hh:mm' and

    Database Engine uses 24-hour time (23:24, for instance).

    Note: Transact-SQL supports a variety of input formats for DATETIME values. As you

    already know, both objects are identified separately; thus, date and time values can be

    specified in any order or alone. If one of the values is omitted, the system uses the defaultvalues. (The default value for time is 12:00 AM.)

  • 8/3/2019 Data Types in SQL Server 2008

    4/22

    Examples 4.4 and 4.5 show the different ways, how date or time values can be written

    using the different formats.

    Example 4.4

    The following date descriptions can be used:

    '28/5/1959' (with SET DATEFORMAT dmy)

    'May 28, 1959'

    '1959 MAY 28'

    Example 4.5

    The following time descriptions can be used:

    '8:45 AM'

    '4 pm'

    Miscellaneous Data Types

    Transact-SQL supports several data types that do not belong to any of the data typegroups described previously:

    Binary data types

    BIT

    Large object data types CURSOR (discussed in Chapter 8)

    UNIQUEIDENTIFIER

    SQL_VARIANT

    TABLE (discussed in Chapter 8) XML (discussed in Chapter 28)

    Spatial (e.g., GEOGRAPHY and GEOMETRY) data types (discussed in Chapter29 )

    HIERARCHYID

    TIMESTAMP data type

    User-defined data types (discussed in Chapter 5)

    The following sections describe each of these data types (other than those designated as

    being discussed in another chapter).

    Binary and BIT Data Types

    BINARY and VARBINARY are the two binary data types. They describe data objects

    being represented in the internal format of the system. They are used to store bit strings.For this reason, the values are entered using hexadecimal numbers.

    The values of the BIT data type are stored in a single bit. Therefore, up to 8 bit columns

    are stored in 1 byte. The following table summarizes the properties of these data types:

  • 8/3/2019 Data Types in SQL Server 2008

    5/22

    Data Type Explanation

    BINARY[(n)]Specifies a bit string of fixed length with exactly n bytes (0 < n

    8000).

    VARBINARY[(n)]Specifies a bit string of variable length with up to n bytes (0 < n 8000).

    BITUsed for specifying the Boolean data type with three possible values:

    FALSE, TRUE, and NULL.

    Large Object Data Types

    Large objects (LOBs) are data objects with the maximum length of 2GB. These objects

    are generally used to store large text data and to load modules and audio/video files.

    Transact-SQL supports two different ways to specify and access LOBs:

    Use the data types VARCHAR(MAX), NVARCHAR(MAX), and

    VARBINARY(MAX) Use the so-called text/image data type

    The following subsections describe the two forms of LOBs.

    The MAX Specifier Starting with SQL Server 2005, you can use the same programmingmodel to access values of standard data types and LOBs. In other words, you can use

    convenient system functions and string operators to work with LOBs.

    Database Engine uses the MAX specifier with the data types VARCHAR, NVARCHAR,and VARBINARY to define variable-length columns. When you use MAX by default

    (instead of an explicit value), the system analyzes the length of the particular string anddecides whether to store the string as a convenient value or as a LOB. The MAX specifier

    indicates that the size of column values can reach the maximum LOB size of the currentsystem. (In a future version of SQL Server, it is possible that MAX will have a higher

    maximum value for strings.)

    Although the database system decides how a LOB will be stored, you can override this

    default specification using the sp_tableoption system procedure with the LARGE_VALUE_TYPES_OUT_OF_ROW option. If the option's value is set to 1, the data in

    columns declared using the MAX specifier will be stored separately from all other data.

    If this option is set to 0, Database Engine stores all values for the row size < 8060 bytes

    as regular row data.

    In SQL Server 2008, you can apply the new FILESTREAM attribute to a

    VARBINARY(MAX) column to store large binary data directly in an NTFS file system.

    The main advantage of this attribute is that the size of the corresponding LOB is limitedonly by the file system volume size.

  • 8/3/2019 Data Types in SQL Server 2008

    6/22

    TEXT, NTEXT, and IMAGE Data Types The data types TEXT, NTEXT, and IMAGE

    constitute the so-called text/image data types. Data objects of the type IMAGE can

    contain any kind of data (load modules, audio/video), while data objects of the data typesTEXT and NTEXT can contain any text data (that is, printable data).

    The text/image data types are stored by default separately from all other values of adatabase using a B-tree structure that points to the fragments of that data. (AB-treestructure is a treelike data structure in which all of the bottom nodes are the same numberof levels away from the root of the tree.) For columns of a text /image data type,

    Database Engine stores a 16-byte pointer in the data row that specifies where the data can

    be found.

    If the amount of text/image data is less than 32KB, the pointer points to the root node ofthe B-tree structure, which is 84 bytes long. The root node points to the physical blocks

    of the data. If the amount of the data is greater than 32KB, Database Engine builds

    intermediate nodes between the data blocks and the root node.

    For each table that contains more than one column with such data, all values of the

    columns are stored together. However, one physical page can hold only text/image data

    from a single table.

    Although text/image data is stored separately from all other data, you can modify thisusing the sp_tableoption system procedure with the TEXT_IN_ROW option. Using this

    option, you can specify the maximum number of bytes, which are stored together with the

    regular data.

    The text/image data types discussed this far have several limitations. You can't use them

    as local variables (in stored procedures or in groups of Transact-SQL statements). Also,they can't be a part of an index or can't be used in the following clauses of the SELECT

    statement: WHERE, ORDER BY, and GROUP BY. The biggest problem concerning alltext/image data types is that you have to use special operators (READTEXT,

    WRITETEXT, and UPDATETEXT) to work with such data.

    Note: The text/image data types are marked as a deprecated feature and will be removedin a future version of Database Engine. Use VARCHAR(MAX), NVARCHAR(MAX),

    and VARBINARY(MAX) instead.

    UNIQUEIDENTIFIER Data Type

    As its name implies, a value of the UNIQUEIDENTIFIER data type is a unique

    identification number stored as a 16-byte binary string. This data type is closely related tothe globally unique identifier (GUID), which guarantees uniqueness worldwide. Hence,

    using this data type, you can uniquely identify data and objects in distributed systems.

  • 8/3/2019 Data Types in SQL Server 2008

    7/22

    The initialization of a column or a variable of the UNIQUEIDENTIFIER type can be

    provided using the functions NEWID and NEWSEQUENTIALID, as well as with a

    string constant written in a special form using hexadecimal digits and hyphens. (Thefunctions NEWID and NEWSEQUENTIALID are described in the section "System

    Functions" later in this chapter.)

    A column of the UNIQUEIDENTIFIER data type can be referenced using the keyword

    ROWGUIDCOL in a query to specify that the column contains ID values. (This keyworddoes not generate any values.) A table can have several columns of the

    UNIQUEIDENTIFIER type, but only one of them can have the ROWGUIDCOL

    keyword.

    SQL_VARIANT Data Type

    The SQL_VARIANT data type can be used to store values of various data types at the

    same time, such as numeric values, strings, and date values. (The only types of values

    that cannot be stored are TIMESTAMP values.) Each value of an SQL_VARIANTcolumn has two parts: the data value and the information that describes the value. (This

    information contains all properties of the actual data type of the value, such as length,

    scale, and precision.)

    Transact-SQL supports the SQL_VARIANT_PROPERTY function, which displays theattached information for each value of an SQL_VARIANT column. For the use of the

    SQL_VARIANT data type, see Example 5.5 in Chapter 5.

    Note: Declare a column of a table using the SQL_VARIANT data type only if it is reallynecessary. A column should have this data type if its values may be of different types or if

    it is not possible to determine the type of a column during the database design process.

    HIERARCHYID Data Type

    The HIERARCHYID data type is used to store an entire hierarchy. It is implemented as a

    Common Language Runtime (CLR) user-defined type that comprises several systemfunctions for creating and operating on hierarchy nodes. The following functions, among

    others, belong to the methods of this data type: GetAncestor(), GetDescendant(),Read(), and Write(). (The detailed description of this data type is outside the scope of

    this book.)

    TIMESTAMP Data Type

    The TIMESTAMP data type specifies a column being defined as VARBINARY(8) or

    BINARY(8), depending on nullability of the column. The system maintains a current

    value (not a date or time) for each database, which it increments whenever any row witha TIMESTAMP column is inserted or updated and sets the TIMESTAMP column to that

  • 8/3/2019 Data Types in SQL Server 2008

    8/22

    value. Thus, TIMESTAMP columns can be used to determine the relative time when

    rows were last changed. (ROWVERSION is a synonym for TIMESTAMP.)

    Note: The value stored in a TIMESTAMP column isn't important by itself. This column isusually used to detect whether a specific row has been changed since the last time it was

    accessed.

    DECIMAL with VARDECIMAL Storage Format

    The DECIMAL data type is typically stored on the disk as fixed-length data. Since SQL

    Server 2005 SP2, this data type can be stored as a variable-length column by using thenew storage format called VARDECIMAL. Using VARDECIMAL, you can significantly

    reduce the storage space for a DECIMAL column in which values have significant

    difference in their lengths.

    Note: VARDECIMAL is a storage format and not a data type.

    The VARDECIMAL storage format is helpful when you have to specify the largest

    possible value for a field in which the stored values usually are much smaller. Table 4-1

    shows this.

    Note: The VARDECIMAL storage format works the same way for the DECIMAL datatype as the VARCHAR data type works for alphanumerical data.

    Precision No. of Bytes: VARDECIMAL No. of Bytes: Fixed Length

    0 or NULL 2 5

    1 4 5

    20 12 13

    30 16 17

    38 20 17

    Table 41 Number of Bytes for Storing VARDECIMAL and Fixed Length

    To enable the VARDECIMAL storage format, you first have to enable it for the database

    and then enable it for the particular table of that database. The sp_db_vardecimal_storage_format system procedure is used for the first step, as Example 4.6

    shows.

  • 8/3/2019 Data Types in SQL Server 2008

    9/22

    Example 4.6

    EXEC sp_db_vardecimal_storage_format 'sample', 'ON';

    The VARDECIMAL STORAGE FORMAT option of the sp_table option systemprocedure is used to turn on this storage for the table. Example 4.7 turns on the

    VARDECIMAL storage format for the project table.

    Example 4.7

    EXEC sp_tableoption 'project', 'vardecimal storage format', 1

    As you already know, the main reason to use the VARDECIMAL storage format is toreduce the storage size of the data. If you want to test how much storage space could be

    gained by using this storage format, use the dynamic management view called

    sys.sp_estimated_rowsize_reduction_for_vardecimal . This dynamic management viewgives you a detailed estimate for the particular table.

    Transact-SQL

    From Wikipedia, the free encyclopedia

    Jump to: navigation,search

    Transact-SQL (T-SQL) is Microsoft's andSybase's proprietary extension to SQL. SQL,

    often expanded to Structured Query Language, is astandardizedcomputer language that

    was originally developed by IBM for querying, altering and defining relational databases,

    using declarative statements. T-SQL expands on the SQL standard to includeprocedural

    programming,local variables, various support functions for string processing, dateprocessing, mathematics, etc. and changes to the DELETEandUPDATE statements.

    These additional features make Transact-SQLTuring complete.

    Transact-SQL is central to using Microsoft SQL Server. All applications thatcommunicate with an instance of SQL Server do so by sending Transact-SQL statements

    to the server, regardless of the user interface of the application.

    Contents

    [hide]

    1 Flow control

    2 Changes to DELETE and UPDATE statements

    3 BULK INSERT

    4 TRY CATCH

    5 See also

    6 External links

    http://en.wikipedia.org/wiki/Transact-SQL#mw-head%23mw-headhttp://en.wikipedia.org/wiki/Transact-SQL#mw-head%23mw-headhttp://en.wikipedia.org/wiki/Transact-SQL#p-search%23p-searchhttp://en.wikipedia.org/wiki/Microsofthttp://en.wikipedia.org/wiki/Microsofthttp://en.wikipedia.org/wiki/Sybasehttp://en.wikipedia.org/wiki/Sybasehttp://en.wikipedia.org/wiki/Sybasehttp://en.wikipedia.org/wiki/SQLhttp://en.wikipedia.org/wiki/SQL#Standardizationhttp://en.wikipedia.org/wiki/SQL#Standardizationhttp://en.wikipedia.org/wiki/SQL#Standardizationhttp://en.wikipedia.org/wiki/Declarative_programminghttp://en.wikipedia.org/wiki/Procedural_programminghttp://en.wikipedia.org/wiki/Local_variablehttp://en.wikipedia.org/wiki/Local_variablehttp://en.wikipedia.org/wiki/Delete_(SQL)http://en.wikipedia.org/wiki/Delete_(SQL)http://en.wikipedia.org/wiki/Update_(SQL)http://en.wikipedia.org/wiki/Update_(SQL)http://en.wikipedia.org/wiki/Turing_completehttp://en.wikipedia.org/wiki/Turing_completehttp://en.wikipedia.org/wiki/Turing_completehttp://en.wikipedia.org/wiki/Microsoft_SQL_Serverhttp://en.wikipedia.org/wiki/Microsoft_SQL_Serverhttp://en.wikipedia.org/wiki/Transact-SQL#%23http://en.wikipedia.org/wiki/Transact-SQL#Flow_control%23Flow_controlhttp://en.wikipedia.org/wiki/Transact-SQL#Changes_to_DELETE_and_UPDATE_statements%23Changes_to_DELETE_and_UPDATE_statementshttp://en.wikipedia.org/wiki/Transact-SQL#BULK_INSERT%23BULK_INSERThttp://en.wikipedia.org/wiki/Transact-SQL#TRY_CATCH%23TRY_CATCHhttp://en.wikipedia.org/wiki/Transact-SQL#See_also%23See_alsohttp://en.wikipedia.org/wiki/Transact-SQL#External_links%23External_linkshttp://en.wikipedia.org/wiki/Transact-SQL#mw-head%23mw-headhttp://en.wikipedia.org/wiki/Transact-SQL#p-search%23p-searchhttp://en.wikipedia.org/wiki/Microsofthttp://en.wikipedia.org/wiki/Sybasehttp://en.wikipedia.org/wiki/SQLhttp://en.wikipedia.org/wiki/SQL#Standardizationhttp://en.wikipedia.org/wiki/Declarative_programminghttp://en.wikipedia.org/wiki/Procedural_programminghttp://en.wikipedia.org/wiki/Local_variablehttp://en.wikipedia.org/wiki/Delete_(SQL)http://en.wikipedia.org/wiki/Update_(SQL)http://en.wikipedia.org/wiki/Turing_completehttp://en.wikipedia.org/wiki/Microsoft_SQL_Serverhttp://en.wikipedia.org/wiki/Transact-SQL#%23http://en.wikipedia.org/wiki/Transact-SQL#Flow_control%23Flow_controlhttp://en.wikipedia.org/wiki/Transact-SQL#Changes_to_DELETE_and_UPDATE_statements%23Changes_to_DELETE_and_UPDATE_statementshttp://en.wikipedia.org/wiki/Transact-SQL#BULK_INSERT%23BULK_INSERThttp://en.wikipedia.org/wiki/Transact-SQL#TRY_CATCH%23TRY_CATCHhttp://en.wikipedia.org/wiki/Transact-SQL#See_also%23See_alsohttp://en.wikipedia.org/wiki/Transact-SQL#External_links%23External_links
  • 8/3/2019 Data Types in SQL Server 2008

    10/22

    Flow control

    Keywords for flow control in Transact-SQL include BEGIN and END, BREAK, CONTINUE,

    GOTO, IF and ELSE, RETURN, WAITFOR, and WHILE.

    IF and ELSE allow conditional execution. This batch statement will print "It is theweekend" if the current date is a weekend day, or "It is a weekday" if the current date is a

    weekday.

    IF DATEPART(dw, GETDATE()) = 7 OR DATEPART(dw, GETDATE()) = 1PRINT 'It is the weekend.'

    ELSEPRINT 'It is a weekday.'

    BEGIN and END mark a block of statements. If more than one statement is to be controlled

    by the conditional in the example above, we can use BEGIN and END like this:

    IF DATEPART(dw, GETDATE()) = 7 OR DATEPART(dw, GETDATE()) = 1BEGIN

    PRINT 'It is the weekend.'PRINT 'Get some rest in weekend!'

    ENDELSEBEGIN

    PRINT 'It is a weekday.'PRINT 'Get to work in weekday!'

    END

    WAITFOR will wait for a given amount of time, or until a particular time of day. The

    statement can be used for delays or to block execution until the set time.

    RETURN is used to immediately return from astored procedure or function.

    BREAK ends the enclosing WHILE loop, while CONTINUE causes the next iteration of the

    loop to execute. An example of a WHILE loop is given below.

    DECLARE @i nvarchar(50)SET @i = 0WHILE @i < 5BEGIN

    PRINT 'Hello world.'SET @i = @i + 1

    END

    Changes to DELETE and UPDATE statements

    In Transact-SQL, both the DELETE and UPDATE statements allow a FROM clause to

    be added, which allows joins to be included.

    http://en.wikipedia.org/wiki/Stored_procedurehttp://en.wikipedia.org/wiki/Stored_procedurehttp://en.wikipedia.org/wiki/Stored_procedure
  • 8/3/2019 Data Types in SQL Server 2008

    11/22

    This example deletes all users who have been flagged with the 'Idle' flag.

    DELETE usersFROM users as uJOIN user_flags as fON u.id=f.id

    WHERE f.name = 'Idle'

    BULK INSERT

    BULK INSERT is a Transact-SQL statement that implements a bulk data-loading

    process, inserting multiple rows into a table, reading data from an external sequential file.

    Use of BULK INSERT results in better performance than processes that issue individual

    INSERT statements for each row to be added. Additional details are available onMicrosoft's MSDN page.

    TRY CATCHBeginning with SQL Server 2008, Microsoft introduced additional TRY CATCH logic to

    support exception type behaviour. This behaviour enables developers to simplify theircode and leave out @@ERROR checking after each SQL execution statement.

    -- begin transactionBEGIN TRANBEGIN TRY

    -- execute each statementINSERT INTO MYTABLE(NAME) VALUES ('ABC')INSERT INTO MYTABLE(NAME) VALUES ('123')

    -- commit the transactionCOMMIT TRAN

    END TRYBEGIN CATCH

    -- rollback the transaction because of errorROLLBACK TRAN

    END CATCH

    @@CONNECTIONS

    Syntax

    @@CONNECTIONS

    Return Types

    integer

    Remarks

    http://msdn2.microsoft.com/en-us/library/ms188365.aspxhttp://msdn2.microsoft.com/en-us/library/ms188365.aspx
  • 8/3/2019 Data Types in SQL Server 2008

    12/22

    Connections are different from users. Applications, for example, can open multipleconnections to SQL Server without the user observing the connections.

    To display a report containing several SQL Server statistics, including connectionattempts, run sp_monitor.

    Examples

    This example shows the number of login attempts as of the current date and time.

    SELECT GETDATE() AS 'Today''s Date and Time',@@CONNECTIONS AS 'Login Attempts'

    Here is the result set:

    Today's Date and Time Login Attempts--------------------------- ---------------1998-04-09 14:28:46.940 18http://msdn.microsoft.com/en-us/library/aa260387(v=SQL.80).aspx

    http://msdn.microsoft.com/en-us/library/aa933167(v=SQL.80).aspx

    http://msdn.microsoft.com/en-us/library/aa258259(v=SQL.80).aspx

    http://msdn.microsoft.com/en-us/library/aa933217(v=SQL.80).aspx

    @@IDENTITY

    Syntax

    @@IDENTITY

    Return Types

    numeric

    Remarks

    After an INSERT, SELECT INTO, or bulk copy statement completes, @@IDENTITY containsthe last identity value generated by the statement. If the statement did not affect any

    tables with identity columns, @@IDENTITY returns NULL. If multiple rows are inserted,generating multiple identity values, @@IDENTITY returns the last identity valuegenerated. If the statement fires one or more triggers that perform inserts that generateidentity values, calling @@IDENTITY immediately after the statement returns the lastidentity value generated by the triggers. If a trigger is fired after an insert action on atable that has an identity column, and the trigger inserts into another table that does nothave an identity column, @@IDENTITY will return the identity value of the first insert. The@@IDENTITYvalue does not revert to a previous setting if the INSERT or SELECT INTOstatementor bulk copy fails, or if the transaction is rolled back.

    http://msdn.microsoft.com/en-us/library/aa260387(v=SQL.80).aspxhttp://msdn.microsoft.com/en-us/library/aa933167(v=SQL.80).aspxhttp://msdn.microsoft.com/en-us/library/aa258259(v=SQL.80).aspxhttp://msdn.microsoft.com/en-us/library/aa933217(v=SQL.80).aspxhttp://msdn.microsoft.com/en-us/library/aa260387(v=SQL.80).aspxhttp://msdn.microsoft.com/en-us/library/aa933167(v=SQL.80).aspxhttp://msdn.microsoft.com/en-us/library/aa258259(v=SQL.80).aspxhttp://msdn.microsoft.com/en-us/library/aa933217(v=SQL.80).aspx
  • 8/3/2019 Data Types in SQL Server 2008

    13/22

    @@IDENTITY, SCOPE_IDENTITY, and IDENT_CURRENT are similar functions in that theyreturn the last value inserted into the IDENTITY column of a table.

    @@IDENTITY and SCOPE_IDENTITY will return the last identity value generated in anytable in the current session. However, SCOPE_IDENTITY returns the value only within thecurrent scope; @@IDENTITY is not limited to a specific scope.

    IDENT_CURRENT is not limited by scope and session; it is limited to a specified table.IDENT_CURRENT returns the identity value generated for a specific table in any sessionand any scope. For more information, see IDENT_CURRENT.

    The scope of the @@IDENTITY function is the local server on which it is executed. Thisfunction cannot be applied to remote or linked servers. To obtain an identity value on adifferent server, execute a stored procedure on that remote or linked server and havethat stored procedure, which is executing in the context of the remote or linked server,gather the identity value and return it to the calling connection on the local server.

    Examples

    This example inserts a row into a table with an identity column and uses @@IDENTITY todisplay the identity value used in the new row.

    INSERT INTO jobs (job_desc,min_lvl,max_lvl)VALUES ('Accountant',12,125)SELECT @@IDENTITY AS 'Identity'

    CREATE FUNCTION

    Creates a user-defined function, which is a saved Transact-SQL routine that returns avalue. User-defined functions cannot be used to perform a set of actions that modify the

    global database state. User-defined functions, like system functions, can be invoked froma query. They also can be executed through an EXECUTE statement like storedprocedures.

    User-defined functions are modified using ALTER FUNCTION, and dropped using DROPFUNCTION.

    Syntax

    Scalar Functions

    CREATE FUNCTION [ owner_name. ] function_name

    ( [ { @parameter_name [AS] scalar_parameter_data_type [ = default] } [ ,...n ] ] )

    RETURNS scalar_return_data_type

    [ WITH < function_option> [ [,] ...n] ]

    [ AS ]

    http://msdn.microsoft.com/en-us/library/aa933217(v=SQL.80).aspxhttp://msdn.microsoft.com/en-us/library/aa933217(v=SQL.80).aspx
  • 8/3/2019 Data Types in SQL Server 2008

    14/22

    BEGINfunction_bodyRETURN scalar_expression

    END

    Inline Table-valued Functions

    CREATE FUNCTION [ owner_name. ] function_name( [ { @parameter_name [AS] scalar_parameter_data_type [ = default] } [ ,...n ] ] )

    RETURNS TABLE

    [ WITH < function_option > [ [,] ...n ] ]

    [ AS ]

    RETURN [ ( ] select-stmt[ ) ]

    Multi-statement Table-valued Functions

    CREATE FUNCTION [ owner_name. ] function_name( [ { @parameter_name [AS] scalar_parameter_data_type [ = default] } [ ,...n ] ] )

    RETURNS @return_variableTABLE < table_type_definition >

    [ WITH < function_option > [ [,] ...n ] ]

    [ AS ]

    BEGINfunction_body

    RETURNEND

    < function_option > ::={ ENCRYPTION | SCHEMABINDING }

    < table_type_definition > :: =( { column_definition | table_constraint} [ ,...n ] )

    Arguments

    owner_name

    Is the name of the user ID that owns the user-defined function. owner_name must be anexisting user ID.

    function_name

    Is the name of the user-defined function. Function names must conform to the rules foridentifiers and must be unique within the database and to its owner.

  • 8/3/2019 Data Types in SQL Server 2008

    15/22

    @parameter_name

    Is a parameter in the user-defined function. One or more parameters can be declared in aCREATE FUNCTION statement. A function can have a maximum of 1,024 parameters. Thevalue of each declared parameter must be supplied by the user when the function isexecuted, unless a default for the parameter is defined. When a parameter of the functionhas a default value, the keyword "default" must be specified when calling the function inorder to get the default value. This behavior is different from parameters with defaultvalues in stored procedures in which omitting the parameter also implies the defaultvalue.

    Specify a parameter name using an at sign (@) as the first character. The parametername must conform to the rules for identifiers. Parameters are local to the function; thesame parameter names can be used in other functions. Parameters can take the placeonly of constants; they cannot be used in place of table names, column names, or thenames of other database objects.

    scalar_parameter_data_type

    Is the parameter data type. All scalar data types, including bigint and sql_variant, canbe used as a parameter for user-defined functions. The timestamp data type and user-defined data types are not supported. Nonscalar types such as cursor and table cannot bespecified.

    scalar_return_data_type

    Is the return value of a scalar user-defined function. scalar_return_data_type can be anyof the scalar data types supported by SQL Server, except text, ntext, image, andtimestamp.

    scalar_expression

    Specifies the scalar value that the scalar function returns.

    TABLE

    Specifies that the return value of the table-valued function is a table. Only constants and@local_variables can be passed to table-valued functions.

    In inline table-valued functions, the TABLE return value is defined through a single SELECTstatement. Inline functions do not have associated return variables.

    In multi-statement table-valued functions, @return_variable is a TABLE variable, used tostore and accumulate the rows that should be returned as the value of the function.

    function_body

    Specifies that a series of Transact-SQL statements, which together do not produce a sideeffect, define the value of the function. function_body is used only in scalar functions andmulti-statement table-valued functions.

    In scalar functions, function_bodyis a series of Transact-SQL statements that togetherevaluate to a scalar value.

  • 8/3/2019 Data Types in SQL Server 2008

    16/22

    In multi-statement table-valued functions, function_bodyis a series of Transact-SQLstatements that populate a table return variable.

    select-stmt

    Is the single SELECT statement that defines the return value of an inline table-valued

    function.

    ENCRYPTION

    Indicates that SQL Server will convert the original text of the CREATE FUNCTIONstatement to an obfuscated format. Note that obfuscated functions can be reverseengineered because SQL Server must de-obfuscate functions for execution. In SQL Server2000, the obfuscated text is visible in the syscomments system table and may besusceptible to de-obfuscation attempts.

    Using ENCRYPTION prevents the function from being published as part of SQL Serverreplication.

    SCHEMABINDING

    Specifies that the function is bound to the database objects that it references. If afunction is created with the SCHEMABINDING option, then the database objects that thefunction references cannot be altered (using the ALTER statement) or dropped (using aDROP statement).

    The binding of the function to the objects it references is removed only when one of twoactions take place:

    The function is dropped.

    The function is altered (using the ALTER statement) with the SCHEMABINDINGoption not specified.

    A function can be schema-bound only if the following conditions are true:

    The user-defined functions and views referenced by the function are also schema-bound.

    The objects referenced by the function are not referenced using a two-part name.

    The function and the objects it references belong to the same database.

    The user who executed the CREATE FUNCTION statement has REFERENCES

    permission on all the database objects that the function references.

    The CREATE FUNCTION statement with the SCHEMABINDING option specified will fail if theabove conditions are not true.

    table_type_definition

  • 8/3/2019 Data Types in SQL Server 2008

    17/22

    Defines the table data type. The table declaration includes column definitions, names,data types and constraints. The only constraint types allowed are PRIMARY KEY, UNIQUE,NULL and CHECK.

    Remarks

    User-defined functions are either scalar-valued or table-valued. Functions are scalar-valued if the RETURNS clause specified one of the scalar data types. Scalar-valuedfunctions can be defined using multiple Transact-SQL statements.

    Functions are table-valued if the RETURNS clause specified TABLE. Depending on how thebody of the function is defined, table-valued functions can be classified as inline or multi-statement functions.

    If the RETURNS clause specifies TABLE with no accompanying column list, the function isan inline function. Inline functions are table-valued functions defined with a single SELECTstatement making up the body of the function. The columns, including the data types, ofthe table returned by the function are derived from the SELECT list of the SELECTstatement defining the function.

    If the RETURNS clause specifies a TABLE type with columns and their data types, thefunction is a multi-statement table-valued function.

    The following statements are allowed in the body of a multi-statement function.Statements not in this list are not allowed in the body of a function:

    Assignment statements.

    Control-of-Flow statements.

    DECLARE statements defining data variables and cursors that are local to thefunction.

    SELECT statements containing select lists with expressions that assign values tovariables that are local to the function.

    Cursor operations referencing local cursors that are declared, opened, closed, anddeallocated in the function. Only FETCH statements that assign values to localvariables using the INTO clause are allowed; FETCH statements that return data tothe client are not allowed.

    INSERT, UPDATE, and DELETE statements modifying table variables local to thefunction.

    EXECUTE statements calling an extended stored procedures.

    Security Note Validate all user input. Do not concatenate user input beforevalidating it. Never execute a command constructed from unvalidated user input.For more information, see Validating User Input.

    Function Determinism and Side Effects

    http://msdn.microsoft.com/en-us/library/aa174437(v=SQL.80).aspxhttp://msdn.microsoft.com/en-us/library/aa174437(v=SQL.80).aspx
  • 8/3/2019 Data Types in SQL Server 2008

    18/22

    Functions are either deterministic or nondeterministic. They are deterministic when theyalways return the same result any time they are called with a specific set of input values.

    They are nondeterministic when they could return different result values each time theyare called with the same specific set of input values.

    Nondeterministic functions can cause side effects. Side effects are changes to someglobal state of the database, such as an update to a database table, or to some externalresource, such as a file or the network (for example, modify a file or send an e-mailmessage).

    Built-in nondeterministic functions are not allowed in the body of user-defined functions;they are as follows:

    @@CONNECTIONS @@TOTAL_ERRORS

    @@CPU_BUSY @@TOTAL_READ

    @@IDLE @@TOTAL_WRITE

    @@IO_BUSY GETDATE

    @@MAX_CONNECTIONS GETUTCDATE

    @@PACK_RECEIVED NEWID

    @@PACK_SENT RAND

    @@PACKET_ERRORS TEXTPTR

    @@TIMETICKS

    Although nondeterministic functions are not allowed in the body of user-defined functions,these user-defined functions still can cause side effects if they call extended storedprocedures.

    Functions that call extended stored procedures are considered nondeterministic becauseextended stored procedures can cause side effects on the database. When user definedfunctions call extended stored procedures that can have side effects on the database, donot rely on a consistent result set or execution of the function.

    Calling extended stored procedures from functions

    The extended stored procedure, when called from inside a function, cannot return resultsets to the client. Any ODS APIs that return result sets to the client will return FAIL. Theextended stored procedure could connect back to Microsoft SQL Server; however, itshould not attempt to join the same transaction as the function that invoked the extendedstored procedure.

    Similar to invocations from a batch or stored procedure, the extended stored procedurewill be executed in the context of the Windows security account under which SQL

  • 8/3/2019 Data Types in SQL Server 2008

    19/22

    Server is running. The owner of the stored procedure should consider this when givingEXECUTE privileges on it to users.

    Function Invocation

    Scalar-valued functions may be invoked where scalar expressions are used, including

    computed columns and CHECK constraint definitions. When invoking scalar-valuedfunctions, at minimum use the two-part name of the function.

    [database_name.]owner_name.function_name ([argument_expr][,...])

    If a user-defined function is used to define a computed column, the function'sdeterministic quality also defines whether an index may be created on that computedcolumn. An index can be created on a computed column that uses a function only if thefunction is deterministic. A function is deterministic if it always returns the same value,given the same input.

    Table-valued functions can be invoked using a single part name.

    [database_name.][owner_name.]function_name ([argument_expr][,...])

    System table functions that are included in Microsoft SQL Server 2000 need to beinvoked using a '::' prefix before the function name.

    SELECT *FROM ::fn_helpcollations()

    Transact-SQL errors that cause a statement to be stopped and then continued with thenext statement in a stored procedure are treated differently inside a function. Infunctions, such errors will cause the function execution to be stopped. This in turn willcause the statement that invoked the function to be stopped.

    Permissions

    Users should have the CREATE FUNCTION permission to execute the CREATE FUNCTIONstatement.

    CREATE FUNCTION permissions default to members of the sysadmin fixed server role,and the db_owner and db_ddladmin fixed database roles. Members ofsysadmin anddb_owner can grant CREATE FUNCTION permissions to other logins by using the GRANTstatement.

    Owners of functions have EXECUTE permission on their functions. Other users do not haveEXECUTE permissions unless EXECUTE permissions on the specific function are granted to

    them.

    In order to create or alter tables with references to user-defined functions in theCONSTRAINT, DEFAULT clauses, or computed column definition, the user must also haveREFERENCES permission to the functions.

    Examples

    A. Scalar-valued user-defined function that calculates the ISO week

  • 8/3/2019 Data Types in SQL Server 2008

    20/22

    In this example, a user-defined function, ISOweek, takes a date argument and calculatesthe ISO week number. For this function to calculate properly, SET DATEFIRST 1 must beinvoked before the function is called.

    CREATE FUNCTION ISOweek (@DATE datetime)RETURNS int

    ASBEGINDECLARE @ISOweek intSET @ISOweek= DATEPART(wk,@DATE)+1

    -DATEPART(wk,CAST(DATEPART(yy,@DATE) as CHAR(4))+'0104')--Special cases: Jan 1-3 may belong to the previous year

    IF (@ISOweek=0)SET @ISOweek=dbo.ISOweek(CAST(DATEPART(yy,@DATE)-1

    AS CHAR(4))+'12'+ CAST(24+DATEPART(DAY,@DATE) AS CHAR(2)))+1--Special case: Dec 29-31 may belong to the next year

    IF ((DATEPART(mm,@DATE)=12) AND((DATEPART(dd,@DATE)-DATEPART(dw,@DATE))>= 28))SET @ISOweek=1

    RETURN(@ISOweek)

    END

    Here is the function call. Notice that DATEFIRST is set to 1.

    SET DATEFIRST 1SELECT master.dbo.ISOweek('12/26/1999') AS 'ISO Week'

    Here is the result set.

    ISO Week----------------51

    B. Inline table-valued function

    This example returns an inline table-valued function.

    USE pubsGOCREATE FUNCTION SalesByStore (@storeid varchar(30))RETURNS TABLEASRETURN (SELECT title, qty

    FROM sales s, titles tWHERE s.stor_id = @storeid and

    t.title_id = s.title_id)

    C. Multi-statement table-valued function

    Given a table that represents a hierarchical relationship:

    CREATE TABLE employees (empid nchar(5) PRIMARY KEY,empname nvarchar(50),mgrid nchar(5) REFERENCES employees(empid),

  • 8/3/2019 Data Types in SQL Server 2008

    21/22

    title nvarchar(30))

    The table-valued function fn_FindReports(InEmpID), which -- given an Employee ID --returns a table corresponding to all the employees that report to the given employeedirectly or indirectly. This logic is not expressible in a single query and is a good

    candidate for implementing as a user-defined function.

    CREATE FUNCTION fn_FindReports (@InEmpId nchar(5))RETURNS @retFindReports TABLE (empid nchar(5) primary key,

    empname nvarchar(50) NOT NULL,mgrid nchar(5),title nvarchar(30))

    /*Returns a result set that lists all the employees who report to givenemployee directly or indirectly.*/ASBEGIN

    DECLARE @RowsAdded int-- table variable to hold accumulated resultsDECLARE @reports TABLE (empid nchar(5) primary key,

    empname nvarchar(50) NOT NULL,mgrid nchar(5),title nvarchar(30),processed tinyint default 0)

    -- initialize @Reports with direct reports of the given employeeINSERT @reportsSELECT empid, empname, mgrid, title, 0FROM employeesWHERE empid = @InEmpIdSET @RowsAdded = @@rowcount-- While new employees were added in the previous iterationWHILE @RowsAdded > 0BEGIN

    /*Mark all employee records whose direct reports are going to befound in this iteration with processed=1.*/

    UPDATE @reportsSET processed = 1WHERE processed = 0-- Insert employees who report to employees marked 1.INSERT @reportsSELECT e.empid, e.empname, e.mgrid, e.title, 0FROM employees e, @reports rWHERE e.mgrid=r.empid and e.mgrid e.empid and r.processed = 1SET @RowsAdded = @@rowcount/*Mark all employee records whose direct reports have been found

    in this iteration.*/UPDATE @reportsSET processed = 2WHERE processed = 1

    END

    -- copy to the result of the function the required columnsINSERT @retFindReportsSELECT empid, empname, mgrid, titleFROM @reportsRETURN

  • 8/3/2019 Data Types in SQL Server 2008

    22/22

    ENDGO

    -- Example invocationSELECT *FROM fn_FindReports('11234')GO

    week and weekday datepart Arguments

    When datepartis week (wk, ww) or weekday (dw), the return value depends on the valuethat is set by using SET DATEFIRST.

    January 1 of any year defines the starting number for the week datepart, for example:DATEPART (wk, 'Jan 1,xxxx') = 1, wherexxxxis any year.

    The following table lists the return value for week and weekday datepartfor '2007-04-21 'for each SET DATEFIRST argument. January 1 is a Sunday in the year 2007. April 21 is aSaturday in the year 2007. SET DATEFIRST 7, Sunday, is the default for U.S. English.

    ISO_WEEK datepart

    ISO 8601 includes the ISO week-date system, a numbering system for weeks. Each weekis associated with the year in which Thursday occurs. For example, week 1 of 2004(2004W01) ran from Monday 29 December 2003 to Sunday, 4 January 2004. The highestweek number in a year might be 52 or 53. This style of numbering is typically used inEuropean countries/regions, but rare elsewhere.

    The numbering system in different countries/regions might not comply with the ISOstandard. There are at least six possibilities as shown in the following table

    http://void%280%29/http://msdn.microsoft.com/en-us/library/ms181598.aspxhttp://void%280%29/http://void%280%29/http://msdn.microsoft.com/en-us/library/ms181598.aspxhttp://void%280%29/