Best way to get identity of inserted row?

后端 未结 14 2742
醉梦人生
醉梦人生 2020-11-21 07:06

What is the best way to get IDENTITY of inserted row?

I know about @@IDENTITY and IDENT_CURRENT and SCOPE_IDENTITY

14条回答
  •  春和景丽
    2020-11-21 07:40

    One other way to guarantee the identity of the rows you insert is to specify the identity values and use the SET IDENTITY_INSERT ON and then OFF. This guarantees you know exactly what the identity values are! As long as the values are not in use then you can insert these values into the identity column.

    CREATE TABLE #foo 
      ( 
         fooid   INT IDENTITY NOT NULL, 
         fooname VARCHAR(20) 
      ) 
    
    SELECT @@Identity            AS [@@Identity], 
           Scope_identity()      AS [SCOPE_IDENTITY()], 
           Ident_current('#Foo') AS [IDENT_CURRENT] 
    
    SET IDENTITY_INSERT #foo ON 
    
    INSERT INTO #foo 
                (fooid, 
                 fooname) 
    VALUES      (1, 
                 'one'), 
                (2, 
                 'Two') 
    
    SET IDENTITY_INSERT #foo OFF 
    
    SELECT @@Identity            AS [@@Identity], 
           Scope_identity()      AS [SCOPE_IDENTITY()], 
           Ident_current('#Foo') AS [IDENT_CURRENT] 
    
    INSERT INTO #foo 
                (fooname) 
    VALUES      ('Three') 
    
    SELECT @@Identity            AS [@@Identity], 
           Scope_identity()      AS [SCOPE_IDENTITY()], 
           Ident_current('#Foo') AS [IDENT_CURRENT] 
    
    -- YOU CAN INSERT  
    SET IDENTITY_INSERT #foo ON 
    
    INSERT INTO #foo 
                (fooid, 
                 fooname) 
    VALUES      (10, 
                 'Ten'), 
                (11, 
                 'Eleven') 
    
    SET IDENTITY_INSERT #foo OFF 
    
    SELECT @@Identity            AS [@@Identity], 
           Scope_identity()      AS [SCOPE_IDENTITY()], 
           Ident_current('#Foo') AS [IDENT_CURRENT] 
    
    SELECT * 
    FROM   #foo 
    

    This can be a very useful technique if you are loading data from another source or merging data from two databases etc.

提交回复
热议问题