All the documentation I read about reseeding suggests something along the lines of:
SET @maxIdentityValue = (SELECT MAX(id) FROM tablename)
- run
DBCC CHECKIDENT('tablename', RESEED, @maxIdentityValue)
And yet it appears to me that a simple DBCC CHECKIDENT('tablename', RESEED)
is all that's needed, and it will automatically determine the correct identity value from the table without supplying a max value.
Is there a reason (performance or otherwise) that extracting the value using MAX
first is preferred?
Piggyback question: the reason I need to reseed is because I'm using replication and identities keep getting set to Null each time the database replication runs. What am I doing wrong? How can I maintain the correct identity seed for each table?
Update (Current solution)
For now I'm not using the max value. This is the stored procedure I'm using (I generate it using a query on sys.columns
and then just cutting and pasting each into a new query window. Messier, slower, less elegant, but I'm not very familiar with stored procedures and don't want to use dynamic SQL queries):
declare @seedval integer
declare @maxval integer
declare @newval integer
set @seedval = (select ident_current('mytable'));
set @maxval = (select MAX(id) from mytable);
if @maxval > @seedval or @seedval is NULL
BEGIN
print 'Need to reseed: max is ' + cast(@maxval as varchar) + ' and seed is ' + cast(@seedval as varchar)
dbcc checkident('mytable', RESEED);
set @newval = (select ident_current('mytable'));
print 'Max is ' + cast(@maxval as varchar) + ' and seed is ' + cast(@newval as varchar)
END
ELSE
print 'No need to reseed';
DBCC CHECKIDENT ('CARD.Alias') – Leonardo Marques de Souza Sep 21 '16 at 15:16