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?
Here, to reset the Identity column in SQL Server you can use DBCC CHECKIDENT method. Syntax : DBCC CHECKIDENT ('table_name', RESEED, new_value); Note : If we reset the existing records in the table and insert new records, then it will show an error.
To change the original seed value and reseed any existing rows, drop the identity column and recreate it specifying the new seed value. When the table contains data, the identity numbers are added to the existing rows with the specified seed and increment values.
Just like regular tables, a column in a table variable can also be declared as an IDENTITY column.
You can not update identity column. SQL Server does not allow to update the identity column unlike what you can do with other columns with an update statement. Although there are some alternatives to achieve a similar kind of requirement.
Truncating the table will dump ALL the data, and reset the identity seed.
Otherwise, you can use this call to reset the identity while retaining any of the data:
DBCC CHECKIDENT (yourtableName, reseed, @NewStartSeedValue)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With