While creating some data scripts today I needed to find a way to insert values for Identity column - that's fine I can use 'SET IDENTITY_INSERT TableName ON' and specify the values but how do I know what value to start from?
Well after some searching I came across a snippet of code that gets the current value of the Identity column and the value that needs to be added to it to get the next valid number to use. Here's some sample code that demonstrates getting values and inserting data to prove that the values match what SQL Server would have done.
CREATE TABLE TestIdentity (
Id int NOT NULL IDENTITY (1, 5),
Value varchar(20)
)
SELECT IDENT_CURRENT('TestIdentity')
SELECT IDENT_INCR('TestIdentity')
--------------------------------------- ---------------------------------------
1 5
(1 row(s) affected)
SELECT IDENT_CURRENT('TestIdentity')+ IDENT_INCR('TestIdentity')
---------------------------------------
6
INSERT INTO TestIdentity VALUES ('Test1')
INSERT INTO TestIdentity VALUES ('Test2')
SELECT * FROM TestIdentity
Id Value
----------- --------------------
1 Test
6 Test
(2 row(s) affected)
0 comments:
Post a Comment