如何使存储过程返回最后插入的id

时间:2010-04-26 02:52:32

标签: c# sql-server-2008

这里我有一个插入行的存储过程但是如何使它返回最后插入的id而不进行另一个查询

CREATE PROCEDURE [dbo].[spInsertCriteriaItem]
@GroupID int
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    insert into CriteriaItem (CriteriaGroupID) VALUES(@GroupID)
    --I don't want to make another query here
END

是否可以这样做

3 个答案:

答案 0 :(得分:5)

使用Sql Server,您可以使用OUTPUT子句。

这样的东西
DECLARE @CriteriaItem TABLE (
        ID INT IDENTITY (1,1),
        CriteriaGroupID INT
)
insert into @CriteriaItem (CriteriaGroupID)
OUTPUT INSERTED.ID
VALUES(1)

答案 1 :(得分:4)

如果没有额外的查询,你不需要处理什么,但是如果你想要数据库中的数据,你必须查询它。

CREATE PROCEDURE [dbo].[spInsertCriteriaItem]
@GroupID int
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    insert into CriteriaItem (CriteriaGroupID) VALUES(@GroupID);
    SELECT SCOPE_IDENTITY();
END

答案 2 :(得分:0)

为什么不想再提出查询?

CREATE PROCEDURE [dbo].[spInsertCriteriaItem]
@GroupID int
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    insert into CriteriaItem (CriteriaGroupID) VALUES(@GroupID);
    SELECT @@IDENTITY AS InsertedId;
END