Search code examples
sql-servert-sqltable-variable

How can I reseed an identity column in a T-SQL table variable?


I have a T-SQL table variable (not a table) which has an auto incrementing identity column. I want to clear all data from this variable and reset the identity column value to 1. How can this be done?


Solution

  • If you're using a table variable, you can't do it. If it were a table, you could truncate it or use DBCC CHECKIDENT. But, if you have to use a table variable, you have to use something other than an identity column. Or, more accurately, use the identity column in your table variable but output using ROWNUMBER:

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

    It's the best you can do with the table variable.