An identity column is an auto incrementing column An identity column is typically used as a primary key A primary key that’s an identity column is called a surrogate key A surrogate key is one that is not related to the contents of the row in any way An identity column must be NOT NULL You can tell if a column is an identity column by looking at the is_identity column of sys.columns or using the COLUMNPROPERTY function (TableObjectId, ColumnName, ‘IsIdentity’) An identity column has three parts. Data type, Seed, and Increment The data type of an identity column is typically an INT but can be most numeric data types. ie tinyint, smallint, int, bigint, decimal(p,0), or numeric(p,0) The seed defaults to 1 and is usually 1. It can however been any value that fits in the data type. IDENT_SEED returns the original seed value of a table To change the seed of a table use DBCC CHECKIDENT The increment is how much the identity column increases each time a new row is added If the increment is negative then the identity values do in fact go down Negative increments can be handy if your identity column has reached the max value of the data type. Reseed to 0 (assuming that is where you started) and set your increment to -1. IDENT_INCR returns the increment of a table Identity columns can have gaps in the sequence @@IDENTITY returns the last identity value generated within the current session but ignores scope Don’t use @@IDENTITY unless you know you should SCOPE_IDENTITY returns the last identity value generated within the current session and scope SCOPE_CURRENT returns the last identity value generated for a specific table or view Use SCOPE_IDENTITY when you want the identity value for the row you just inserted Use SCOPE_CURRENT to get the most recent identity value from a table before you do an insert Don’t use @@IDENTITY - Worth repeating twice To insert a row into a table with an identity column you must list the columns In general you don’t list the identity column (the insert will fail even if there is a null value being inserted into the column) If you want to insert a specific value into the identity column you have to use the IDENTITY_INSERT setting. SET IDENTITY_INSERT TableName ON Make sure you turn IDENTITY_INSERT back off when you are done. Only one table in a session can have IDENTITY_INSERT turned on at a time SET IDENTITY_INSERT TableName OFF Filed under: Microsoft SQL Server , SQLServerPedia Syndication , T-SQL Tagged: code language , language sql , microsoft sql server , sql statements , T-SQL
↧