Find the Next Identity Value of Each Table of your SQL Server Database

Here’s a quick (and dirty) way of finding out the next identity value of each table of your SQL Server Database. We will use the undocumented stored procedure sp_MSforeachtable for this purpose

USE Northwind
GO
EXEC
sp_MSforeachtable
'IF OBJECTPROPERTY(object_id(''?''), ''TableHasIdentity'') = 1
BEGIN
Print ''?'' DBCC CHECKIDENT (''?'', RESEED)
END'

OUTPUT

image

Observe how I have used an IF condition to only check those tables which have an Identity. Usually when developers do not add this step, they get error messages for those table that do not contain an identity column as shown below

image

As I said, it is a quick and dirty way! Although the undocumented stored procedures are helpful, use them sparingly as they may be deprecated and removed from future SQL Server versions.

If you liked this post, you can also read my other post 8 Common Uses of the undocumented Stored Procedure sp_MSforeachtable for similar tips


About The Author

Suprotim Agarwal, MCSD, MCAD, MCDBA, MCSE, is the founder of DotNetCurry, DNC Magazine for Developers, SQLServerCurry and DevCurry. He has also authored a couple of books 51 Recipes using jQuery with ASP.NET Controls and a new one recently at The Absolutely Awesome jQuery CookBook.

Suprotim has received the prestigous Microsoft MVP award for nine times in a row now. In a professional capacity, he is the CEO of A2Z Knowledge Visuals Pvt Ltd, a digital group that represents premium web sites and digital publications comprising of Professional web, windows, mobile and cloud developers, technical managers, and architects.

Get in touch with him on Twitter @suprotimagarwal, LinkedIn or befriend him on Facebook

2 comments:

Madhivanan said...

If you dont want to use undocumented procedure and if the version is later than 2000, you can use

select object_name(object_id) as table_name,name as column_name,last_value as current_value from sys.identity_columns
order by table_name

Khushboo said...

How to do it if I am using sql 2000?