Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset Identity column to zero in SQL Server?

How can I reset the Identity column of a table to zero in SQL Server?

Edit:

How can we do it with LINQ to SQL ?

like image 743
Mohammad Dayyan Avatar asked Dec 19 '10 19:12

Mohammad Dayyan


People also ask

How do you set the identity column to zero in SQL Server?

Reset the Identity Value Using the DBCC CHECKIDENT Method : 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.

Does truncating a table reset the identity?

Truncate command reset the identity to its seed value. It requires more transaction log space than the truncate command. It requires less transaction log space than the truncate command. You require Alter table permissions to truncate a table.

How do you change the seed value of an identity column?

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.


3 Answers

DBCC CHECKIDENT (MyTable, RESEED, NewValue)

You can also do a Truncate Table, but, of course, that will remove all rows from the table as well.

To do this via L2S:

db.ExecuteCommand("DBCC CHECKIDENT('MyTable', RESEED, NewValue);");

Or, you can call a stored procedure, from L2S, to do it

like image 100
Randy Minder Avatar answered Oct 16 '22 21:10

Randy Minder


DBCC CHECKIDENT ( ‘databasename.dbo.yourtable’,RESEED, 0)

More info : http://msdn.microsoft.com/en-us/library/ms176057.aspx

like image 39
Andrew Avatar answered Oct 16 '22 22:10

Andrew


Use the LINQ to SQL ExecuteCommand to run the required SQL.

db.ExecuteCommand("DBCC CHECKIDENT('table', RESEED, 0);");

LINQ is a data-source agnostic query language and has no built-in facilities for this kind of data-source specific functionality. LINQ to SQL doesn't provide a specific function to do this either AFAIK.

like image 24
Blake Taylor Avatar answered Oct 16 '22 22:10

Blake Taylor