返回刚刚添加的行的id [英] Return the id of the just added row

查看:24
本文介绍了返回刚刚添加的行的id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与我的上一个问题类似,我再次向 SO 人员寻求您的集体智慧和帮助.

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

在存储过程中并通过一些检查后,我需要插入一个新行并为其返回新创建的 ID.检查一行是否存在有效,所以它是我未决定的后面的位.

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.

该表有两个重要的列:LocationID 和 CaseID.CaseID 是自动递增的,所以当你添加插入一个新的 locationid 时,它会自动增加.

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.

我目前有这个:

-- previous checks for existance of CaseID

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

    -- what now?
END

我想在之后立即执行 @CaseID = (SELECT blah) 语句,但我想知道是否有更好的方法?

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?

推荐答案

SELECT @CaseID = SCOPE_IDENTITY()

事实上,你可以这样做(如果这是存储过程的结尾.):

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

SELECT SCOPE_IDENTITY()

(OUTPUT 子句仅在 SQL Server 2005 及更高版本中可用...)

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

参考:SCOPE_IDENTITY

这篇关于返回刚刚添加的行的id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆