9

我对此有点困难,因为我不确定如何在 SQL Server 中执行此操作。

基本上,我想在数据库中插入一个新行,获取刚刚插入的 PK 值(相同的查询)并将其输出回称为存储过程的任何内容:

CREATE PROCEDURE Users_Insert
    -- Add the parameters for the stored procedure here
    @userid int output,
    @name varchar(50),
    @surname varchar(50),
    @email varchar(200),
    @password varchar(50),
    @location varchar(50)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    insert into Users(FirstName, LastName, Email, Password, Location)
    values(@name, @surname, @email, @password, @location);
    GO
    @userid = @@IDENTITY;
END

我在 MySQL 中这样做如下:

CREATE PROCEDURE Users_Insert(@userid int output, @name varchar(50), @surname varchar(50), @email varchar(200), @password varchar(50), @location varchar(50)
BEGIN

    insert into Users(FirstName, LastName, Email, Password, Location)
    values(@name, @surname, @email, @password, @location);

    set @userid = last_insert_id();
END

SQL Server 给我一个错误:

消息 102,级别 15,状态 1,过程 Users_Insert,第 18 行
“@userid”附近的语法不正确。

坦率地说,我不确定我是否正确声明了输出参数,有人可以提供建议吗?

4

1 回答 1

14

您需要将值分配@userid给! 另外,我建议使用SCOPE_IDENTITY()而不是@@IDENTITY

CREATE PROCEDURE Users_Insert
    -- Add the parameters for the stored procedure here
    @userid int output,
    @name varchar(50),
    @surname varchar(50),
    @email varchar(200),
    @password varchar(50),
    @location varchar(50)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    -- Insert statements for procedure here
    insert into Users(FirstName, LastName, Email, Password, Location)
    values(@name, @surname, @email, @password, @location);

    -- make an actual **assignment** here...
    SELECT @userid = SCOPE_IDENTITY();
END

请参阅此博客文章,了解为什么应该使用SCOPE_IDENTITYover@@IDENTITY

于 2013-05-10T12:11:41.933 回答