Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 321
Nimesh Madhavan Avatar asked Sep 29 '08 01:09

Nimesh Madhavan


People also ask

How do I reseed an identity column in SQL?

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.

How do I reseed a column in SQL Server?

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.

Can we create identity column in table variable?

Just like regular tables, a column in a table variable can also be declared as an IDENTITY column.

How do you modify an identity column in SQL Server?

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.


2 Answers

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) 
like image 28
Stephen Wrighton Avatar answered Oct 21 '22 18:10

Stephen Wrighton


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.

like image 105
Josef Avatar answered Oct 21 '22 18:10

Josef