Monday, July 10, 2006

Setting Identity Value Back To 1 After Deleting All Rows From A Table

Sometimes you want the identity value to start from 1 again after you delete all the rows from a table
There are 2 ways to accomplish that
1 Use the TRUNCATE TABLE command instead of DELETE
2 If you do use DELETE then run DBCC CHECKIDENT and reseed the table

Here is some code to explain what I mean

CREATE TABLE TestValues (Id INT identity,DateVale DATETIME)
INSERT INTO TestValues VALUES(GETDATE())
INSERT INTO TestValues VALUES(GETDATE())
INSERT INTO TestValues VALUES(GETDATE())
INSERT INTO TestValues VALUES(GETDATE())
INSERT INTO TestValues VALUES(GETDATE())

SELECT *
FROM TestValues

-- This is the output
-- 1 2006-07-10 12:31:17.050
-- 2 2006-07-10 12:31:17.050
-- 3 2006-07-10 12:31:17.050
-- 4 2006-07-10 12:31:17.050
-- 5 2006-07-10 12:31:17.050



DELETE TestValues

INSERT INTO TestValues VALUES(GETDATE())

SELECT *
FROM TestValues

-- Output
-- 6 2006-07-10 12:31:29.143


TRUNCATE TABLE TestValues

INSERT INTO TestValues VALUES(GETDATE())

SELECT *
FROM TestValues

-- Output
-- 1 2006-07-10 12:31:38.317


INSERT INTO TestValues VALUES(GETDATE())

DELETE TestValues

DBCC CHECKIDENT(TestValues,RESEED,0)
-- Message
-- Checking identity information: current identity value '2', current column value '0'.
-- DBCC execution completed. If DBCC printed error messages, contact your system administrator.


INSERT INTO TestValues VALUES(GETDATE())

SELECT *
FROM TestValues

-- Output
-- 1 2006-07-10 12:31:52.503


DROP TABLE TestValues

No comments: