scope_identity vs ident_current

前端 未结 6 1558
深忆病人
深忆病人 2020-12-01 19:02

After much research I am a little confused by which identity tracker I should use in sql.

From what I understand scope_identity will give me the last id updated fro

6条回答
  •  日久生厌
    2020-12-01 19:37

    SELECT IDENT_CURRENT -- as you said will give you the table specific last inserted identity value. There are issues associated with this, one the user need to have permission to see the metadata otherwise it returns NULL and second you are hardcoding the name of the table , which will cause a problem in case the table name changes.

    The best practice is to use Scope_Identity together with a variable ...Look the following example

     DECLARE @myFirstTableID INT
    
      DECLARE @mySecondTableID INT
    
      INSERT INTO MYFirstTable (....) VALUES (.....)
    
       SELECT @myFirstTableID =SCOPE_IDENTITY()
    
    
      INSERT INTO MYSecondTable () VALUES (.....)
    
    
       SELECT @mySecondTableID=SCOPE_IDENTITY()
    

    Thus by making use of variable and scope_identity next to the insert statement of interest, you can make sure that you are getting the right identity from the right table. Enjoy

提交回复
热议问题