Getting the next ID without inserting a row

前端 未结 5 857
臣服心动
臣服心动 2021-02-05 10:50

Is it possible in SQL (SQL Server) to retrieve the next ID (integer) from an identity column in a table before, and without actually, inserting a row? This is not necessarily th

5条回答
  •  忘掉有多难
    2021-02-05 11:11

    This is a little bit strange but it will work:

    If you want to know the next value, start by getting the greatest value plus one:

    SELECT max(id) FROM yourtable
    

    To make this work, you'll need to reset the identity on insert:

    DECLARE @value INTEGER
    
    SELECT @value = max(id) + 1 FROM yourtable
    
    DBCC CHECKIDENT (yourtable, reseed, @value)
    
    INSERT INTO yourtable ...
    

    Not exactly an elegant solution but I haven't had my coffee yet ;-)

    (This also assumes that there is nothing done to the table by your process or any other process between the first and second blocks of code).

提交回复
热议问题