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

后端 未结 5 1424
梦毁少年i
梦毁少年i 2020-12-08 09:34

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 identi

5条回答
  •  温柔的废话
    2020-12-08 10:30

    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.

提交回复
热议问题