在存储过程中插入后如何获取自动生成的主键?

时间:2019-03-20 19:12:50

标签: sql sql-server database

我的SQL Server表:

[dbo].[Rep] (
[rep_ID]        INT          IDENTITY (300, 1) NOT NULL,
[Restaurant_ID] INT          NULL,
[Fname]         VARCHAR (50) NOT NULL,
[Lname]         VARCHAR (50) NOT NULL,
CONSTRAINT [PK_Rep_ID] PRIMARY KEY CLUSTERED ([rep_ID] ASC),
CONSTRAINT [FK_Restaurant_ID] FOREIGN KEY ([Restaurant_ID]) REFERENCES [dbo].[Restaurants] ([ID])

);

我想创建一个存储过程,该过程返回插入记录的自动生成的密钥。

我当前的存储过程:

CREATE PROCEDURE [dbo].[createRepAcc]
    @first varchar(50),
    @last varchar(50)
AS
    INSERT INTO Rep([Fname], [Lname])
    OUTPUT inserted.rep_ID
    VALUES (@first, @last);

它可以插入表中,但仅返回1而不是生成的主键。

我在做什么错了?

1 个答案:

答案 0 :(得分:2)

您可以使用 scope_identity()获取最后生成的ID。对于您的情况,这是一个详细的工作表

/* creating a simple table with identity column */
CREATE TABLE dbo.a(identity_column INT IDENTITY(300,1), x CHAR(1));

/* Procedure that inserts values and returns generated output*/
CREATE PROCEDURE [dbo].[ap]
    @x char(1),
    @id int output
AS
    INSERT INTO a(x) VALUES (@x);
    select @id = SCOPE_IDENTITY();

/* This is how the procedure could be called */
declare @ident int -- declare a variable to receive output
execute dbo.ap @x='b', @id=@ident output -- execute or call the procedure
select @ident -- select or print the genereated id