Identity column
From Wikipedia, the free encyclopedia
An Identity column is a column ( also known as a field ) in a database table that (1) uniquely identifies every row in the table, and (2) is made up of values generated by the database. This is much like an AutoNumber field in Microsoft Access or a sequence in Oracle. Because the concept is so important in database science, all RDBMS systems implement some type of generated key, although each has its own terminology.
An identity column differs from a primary key in that its values are managed by the server and ( except in rare cases ) can't be modified. In many cases an identity column is used as a primary key, however this is not always the case.
Two types of identity columns are available in SQL Server: incremental ( where the user can set a seed and an increment ) and random ( where the server chooses a random numeric value and ensures that it hasn't already been used ).
[edit] Code Samples
CREATE TABLE Contacts ( FirstName varChar(30), LastName varChar(30), Phone varChar(16), ContactID identity(1, 1) )
or
CREATE TABLE Contacts ( FirstName varChar(30), LastName varChar(30), Phone varChar(16) ) GO ALTER TABLE Contacts ADD ContactID identity(1, 1)
[edit] Related Functions
It is often useful or necessary to know what identity value was generated by an INSERT command. SQL Server provides several functions to do this: @@Identity provides the last value generated on the current connection, while Scope_Identity(tablename) provides the last value generated, regardless of the connection it was created on.
Example:
INSERT INTO Contacts ( FirstName, LastName ) VALUES ( 'Test', 'User' ) -- SELECT @@Identity -- OR -- Declare @ID int SELECT @ID = @@Identity UPDATE Contacts SET Phone = 'XXX-YYY-ZZZZ' WHERE ContactID = @ID

