11 May 2010

MS SQL Identity Column

IDENTITY in MS SQL is like auto_increment in MySQL.

Create table

CREATE TABLE tablename (id int IDENTIY, title varchar(20))


Inserting data

INSERT INTO tablename (title) VALUES ('title')


Find the Identity Value that was inserted

INSERT INTO tablename (title) VALUES ('title')
SELECT SCOPE_IDENTITY() AS LastIdentity


Find the Identity Value for a particular table

SELECT IDENT_CURRENT('tablename') AS LastIdentity


Inserting Explicit Values into an Identity Column

SET IDENTITY_INSERT tablename ON
INSERT INTO tablename (id, title) VALUES(2, 'newtitle')
SET IDENTITY_INSERT tablename OFF

No comments:

Post a Comment