It seems ridiculous that you can't set/reset an identity column with a single command to cover both cases of whether or not the table has had records inserted. I couldn't understand the behavior I was experiencing until I stumbled across this question on SO!
My solution (ugly but works) is to explicitly check the sys.identity_columns.last_value
table (which tells you whether or not the table has had records inserted) and call the appropriate DBCC CHECKIDENT
command in each case. It is as follows:
DECLARE @last_value INT = CONVERT(INT, (SELECT last_value FROM sys.identity_columns WHERE OBJECT_NAME(OBJECT_ID) = 'MyTable'));
IF @last_value IS NULL
BEGIN
-- Table newly created and no rows inserted yet; start the IDs off from 1
DBCC CHECKIDENT ('MyTable', RESEED, 1);
END
ELSE
BEGIN
-- Table has rows; ensure the IDs continue from the last ID used
DECLARE @lastValUsed INT = (SELECT ISNULL(MAX(ID),0) FROM MyTable);
DBCC CHECKIDENT ('MyTable', RESEED, @lastValUsed);
END