Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
748 views
in Technique[技术] by (71.8m points)

tsql - Return the id of the just added row

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...