这里我有一个插入行的存储过程但是如何使它返回最后插入的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
是否可以这样做
答案 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