Return the id of the just added row

2019-01-28 20:53发布

问题:

In a similar vein to my previous question I again ask the SO guys for your collective wisdom and help.

In a stored procedure and after passing some checks I need to insert a new row and return the newly created id for it. The check if a row exists works so it is the bit after that which I am undecided upon.

The table has two important columns: The LocationID and the CaseID. The CaseID is autoincrementing, so when you add insert a new locationid it will automatically rachet up.

I currently have this:

-- previous checks for existance of CaseID

IF @CaseID IS NULL
BEGIN
    INSERT INTO
        Cases(LocationID)
    VALUES
        (@LocationID)

    -- what now?
END

I was thinking of performing a @CaseID = (SELECT blah) statement immeadiately after but I was wondering if there is a better way?

Is there a better way? How would you do this?

回答1:

SELECT @CaseID = SCOPE_IDENTITY()

In fact, you can just do (if that's the end of the stored proc.):

SELECT SCOPE_IDENTITY()

(The OUTPUT clause is only available in SQL Server 2005 onwards...)

Ref: SCOPE_IDENTITY



回答2:

scope_identity()



回答3:

SELECT SCOPE_IDENTITY()



回答4:

As others mentioned, SCOPE_IDENTITY() is the way to go, though some ORM tools provide this functionality as well.

The only thing you need to remember is SCOPE_IDENTITY() will return the last identity key value generated during the current session only. This is useful in filtering out new keys which may have been created by other clients simultaneously. SELECT @@IDENTITY will return the last key generated by any client/session.



回答5:

You need to use the OUTPUT clause

http://blog.jemm.net/articles/databases/how-to-using-sql-server-2005s-output-to-return-generated-identity/

...which, as pointed out, is only available in sqlserver 2005. Plz disregard.