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

2 comments:

  1. 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

    ReplyDelete
  2. How to do it if I am using sql 2000?

    ReplyDelete