DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Jason has posted 22 posts at DZone. View Full User Profile

Reseeding An Identity Column In A Table Variable

01.20.2009
| 10932 views |
  • submit to reddit
        Closest thing to reseeding a T-SQL Table Variable.
If it was a real Table or a Temporary Table, you could use TRUNCATE TABLE or DBCC CHECKIDENT, but those do not work on Table Variables. Only works on SQL Server 2005 or later (needs OVER semantic).

DECLARE @t table (offset int IDENTITY(1,1), foo nvarchar(50))
INSERT INTO @t (foo) VALUES ('one')
INSERT INTO @t (foo) VALUES ('two')
INSERT INTO @t (foo) VALUES ('three')
SELECT row_number() OVER (ORDER BY offset), foo FROM @t
DELETE FROM @t
INSERT INTO @t (foo) VALUES ('four')
SELECT row_number() OVER (ORDER BY offset), foo FROM @t