June 03, 2010

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, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

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?