Best way to get identity of inserted row?

后端 未结 14 2454
醉梦人生
醉梦人生 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:52

    I can't speak to other versions of SQL Server, but in 2012, outputting directly works just fine. You don't need to bother with a temporary table.

    INSERT INTO MyTable
    OUTPUT INSERTED.ID
    VALUES (...)
    

    By the way, this technique also works when inserting multiple rows.

    INSERT INTO MyTable
    OUTPUT INSERTED.ID
    VALUES
        (...),
        (...),
        (...)
    

    Output

    ID
    2
    3
    4
    

提交回复
热议问题