How Do You Tell What Next Identity Column Will Be?

前端 未结 6 1648
遥遥无期
遥遥无期 2020-12-06 19:12

Is there a tsql query to tell what SQL server identity column value it expects to use for the next row insert?

Edited to add:

I deleted and

6条回答
  •  不知归路
    2020-12-06 19:46

    This piece of sql will give you the next identity column value (there are probably many reasons not to repeat this snippet in production code)

    declare @nextid int;
    declare @previousid int;
    
    begin tran
    
     insert into dbo.TestTable (Col1) values ('11');
     select @nextid = SCOPE_IDENTITY(); 
    
    rollback tran
    
     select @previousid = @nextid -1
     DBCC CHECKIDENT('dbo.TestTable', RESEED, @previousid);
     select @nextid
    

    this stackoverflow question gives some extra information - sql-identity-autonumber-is-incremented-even-with-a-transaction-rollback

提交回复
热议问题