As stated in other answers here, for a table that has just been created and has never had a row in it, performing DBCC CHECKIDENT
seems to have strange effects.
Furthermore, it shouldn't really be necessary, because the first row that is inserted will nicely adhere to its identity(a, b)
specification.
Only when it has had rows in it (that have been deleted) you should reseed it, with the seed value being one less than the identity value you want to insert next.
That is, to have the first inserted row get an identity value of 1, use:
DBCC CHECKIDENT ('MyTable', RESEED, 0);
Now, to tell these 2 situations apart, the following query will return null
if MyTable never has any rows in it (and DBCC CHECKIDENT should not be used), or will return the last issued identity value otherwise (which should then be reset with DBCC CHECKIDENT):
select idc.last_value
from [sys].[objects] as obj
inner join [sys].[identity_columns] as idc on (obj.object_id = idc.object_id)
where obj.type = 'U' and obj.name = 'MyTable'
Combining these 2:
if (select idc.last_value
from [sys].[objects] as obj
inner join [sys].[identity_columns] as idc on (obj.object_id = idc.object_id)
where obj.type = 'U' and obj.name = 'MyTable') is not null
begin
-- Table has had at least one identity value generated, table needs to be reseeded.
dbcc checkident ('MyTable', reseed, 0);
end