How to reset the primary key value in SQL Server

Usually when testing a database I fill it with loads of dummy data. This helps both me and the client see what their site will look like once real data is in their system. Just before the site goes live it's always a good idea to remove the test data, especially if you have user accounts with test as the username and password!

However, if you delete the contents of a table then you will notice that the primary ID values will continue to auto increment from the last number that was in your table. So if you had 100 rows of temp data and removed them then the next entry to the system will be 101. This should not be an issue for your database or code but sometimes it's nice to reset these values too. In SQL you can do this by running the following command:

DBCC CHECKIDENT (tablename, reseed, 0)

Tablename should obviously be the name of your table that you want to reset the primary key value in. It should be pointed out that this code isn't just for resetting to zero. You could put 350 as the number in place of 0 and SQL would start the next entry in your table to 351.

As you can see setting the value of a primary key is quite an easy thing to do within SQL.

blog comments powered by Disqus

Get In Touch

Follow me online at TwitterFacebook or Flickr.

Latest Tweets