Thursday, November 11, 2010

Small Script for resetting the identity column value in MS SQL Server


Normally on Microsoft Technologies we use Access or MS- Sql Server as a database. In a Software development scenario we use

Development Server ->Testing Server -> Production Server -> Client Server .

Now in this given scenario if people use Idendity Column in SQL Server Database then they come accross the problem of reseting it's value atleast i faced it and come to a solution as a script which can solve my problem at any stag as i need to reset all my identity columns on every stag. see it below


use <db_name>

DECLARE @reset_id varchar(200)




DECLARE reset_cursor CURSOR FOR

select Table_schema+'.'+Table_Name as tname from information_schema.tables

where Table_Type='BASE TABLE'

OPEN reset_cursor;




FETCH NEXT FROM reset_cursor

INTO @reset_id;




WHILE @@FETCH_STATUS = 0

BEGIN




DBCC CHECKIDENT(@reset_id,RESEED,0)

print @reset_id;

FETCH NEXT FROM reset_cursor INTO @reset_id;

END;




CLOSE reset_cursor;

DEALLOCATE reset_cursor;





No comments: