Getting autoincrement value in advance

JORGE MALDONADO BARRERA 211 Reputation points
2022-10-25T18:17:32.697+00:00

Hi,

I am new to SQL Server. I have a table with a primary key which is an auto increment field. Of course, it gets an automatic value when a new record is inserted.

Is it possible to know/get the next autoincrement value and assign it manually to the field that represents the primary key instead of letting SQL Server assign it automatically?

Respectfully,
Jorge Maldonado

SQL Server | Other
0 comments No comments
{count} votes

Accepted answer
  1. Viorel 122.6K Reputation points
    2022-10-25T18:22:41.357+00:00

    Consider the Sequence Numbers (https://learn.microsoft.com/en-us/sql/relational-databases/sequence-numbers/sequence-numbers) and use a simple column instead of auto-incremented.

    0 comments No comments

3 additional answers

Sort by: Most helpful
  1. Tom Phillips 17,771 Reputation points
    2022-10-25T19:59:42.7+00:00

    No. You should not attempt to do this. In a multi-user system, there is no guarantee you will calculate the same value as assigned.

    Please see:
    https://www.brentozar.com/archive/2020/11/how-to-insert-rows-and-get-their-identity-values-with-the-output-clause/

    0 comments No comments

  2. PandaPan-MSFT 1,931 Reputation points
    2022-10-26T03:08:03.6+00:00

    Hi @JORGE MALDONADO BARRERA ,
    I think your demand is that you wana the sequence be like 1 2 3 100 101? If so You just need to check this link: https://www.simplilearn.com/tutorials/sql-tutorial/auto-increment-in-sql
    And if you want to know the next autoincrement value, you can check the two links: https://stackoverflow.com/questions/18781701/how-do-i-get-the-next-auto-increment-value-for-a-sql-table-and-use-it https://www.folkstalk.com/2022/09/get-the-next-auto_increment-value-mysql-with-code-examples.html
    If I misunderstand your meaning , pls let me know.


    If the answer is helpful, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment"

    0 comments No comments

  3. Olaf Helper 47,436 Reputation points
    2022-10-26T04:54:58.78+00:00

    it manually to the field that represents the primary key instead of letting SQL Server assign it automatically?

    And what would that be good for; it contradict the concept of autoincrement

    I am new to SQL Server

    Then you should first start learning SQL.

    it manually to the field

    It's possible by using SET IDENTITY_INSERT

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.