How we get auto incremented ID before Insertion in following code?? RRS feed

  • Question

  • insert into [MedicalCenters].[Med_Service](ServiceID,SPUsername,ImagePath,Charges)values(@ID,@Usernme,@Imag,@Charges);
    Monday, March 26, 2018 1:53 PM

All replies

  • Hello,

    Generally speaking this is a bad idea unless only one person will be adding records as it return the incorrect value or create a race condition.

    Here is how to get the last auto-increment id

    SELECT MAX(TheId) FROM TheTableName


    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Monday, March 26, 2018 2:01 PM
  • Well Here I would recommend to use IDENT_CURRENT to get very next ID without inserting the record as following:

    Select IDENT_CURRENT('yourtablename')

    Monday, March 26, 2018 5:38 PM
  • In modern SQL, in order to deal with unique numbers in safer manner, you can also consider the Sequence Numbers: It depends on things.

    Monday, March 26, 2018 8:06 PM