Skip to content

Automatically Reseeding Identity Values on SQL Server

The Problem

You have tables that have a lot of data inserted into them and deleted that use identity values and run out integers to use.  I have over 3000+ databases where this can occur so we have an alerts setup that checks the tables then checks a table to see if setup to be auto reseeded based on rather of database engineers have indicated it is safe to do so.  If it is that table is auto reseed either to one the maximum negative number for the datatype else we are alerted and we check with our database engineers on how to handle that table.  Keep in mind we are reseeding tables that have been deemed OK to reseed automatically.

The Solution

Step 1 – Setting up an SQL Agent Job to Alert You

The first step is to create a table that will hold the tables they we predefined as OK to reseed automatically for us.  At this stage, this table will be empty but it is needed for the procedure that checks to see if an alert needs to be generated for tables requiring your attention.  Our first step will be to create procedure that will check all our user database to check tables that are 90% near the identity the value.  This is parameter you can customize for the procedure.  The code for the procedure is below and you setup a job to run the procedure or add it your own monitoring tool.  Be sure to setup something that will alert if the job fails so you can take action.

STEP 2 – SETUP procedure to AUTOMATICALLY RESEED IDENTITY FIELDS

In the second step, we setup a table to record when auto seeding occurs because being the good DBAs we are will still need to know when our automated process actually run just in case.  Then we setup a job called “DBA – Identity Auto Reseed” to call procedure IdentityReseed_CheckandReseedValue that will reseed anything that we have inserted into our white list table.

STEP 3 – inserting values into white list table for automatic reseeding

Now that all the pieces are in place all you have to do is when the first job fails consult the developers who know whether it is safe to automatically reseed the table or not and you can insert data into your white list table.

To get the most negative number possible as your starting point you would run the following on your server subbing in your values for DatabaseName, SchemaName, and TableName:

To get the identity value to start with run the following subbing in your values:

Summary

You now have two tables, two stored procedures, and two SQL Agent jobs.  When the first job fails you check the messages for which table and database needs a reseed and consult your database engineer to see if can be adding to your white list.  Then use the insert statements in the last part of the post to place those tables in your white list and for now on you don’t have to worry about reseeding you those tables.

Leave a Comment