[英]Make Procedure with SCOPE_IDENTITY()
我得到了这三张桌子
CREATE TABLE
(
FirstTableId Int primary key identity,
Something nvarchar(20)
)
CREATE TABLE SecondTable
(
SecondTableId Int primary key identity,
Something nvarchar(20)
)
CREATE TABLE Relation
(
RelationId int primary key identity,
RelationSomething nvarchar(20),
FirstTableId Int,
SecondTableId Int,
FOREIGN KEY (FirstTableId) REFERENCES FirstTable(FirstTableId),
FOREIGN KEY (SecondTableId) REFERENCES SecondTable(SecondTableId),
)
我创建此过程以将数据插入FirstTable和Relation:
CREATE PROC InsertInto (@FirstTableId int)
AS
INSERT INTO FirstTable VALUES ('example')
SELECT @FirstTableId = SCOPE_IDENTITY()
INSERT INTO Relation (RelationSomething, FirstTableId, SecondTableId) VALUES ('example', @FirstTableId, 2)
我从下拉列表中传递示例数据的值,并且不传递@FirstTable的任何值,因为我希望它获取SCOPE_IDENTITY(),但是却出现如下错误:“必须声明标量变量“ @FirstTableId”?如何解决?这并使其起作用?
您需要在主体中声明变量,而不是在存储过程定义中声明。 在定义中声明它时,这意味着您将在调用存储过程时传递该值。
CREATE PROC InsertInto ()
AS
DECLARE @FirstTableId int;
INSERT INTO FirstTable VALUES ('example')
SET @FirstTableId = SCOPE_IDENTITY()
INSERT INTO Relation (RelationSomething, FirstTableId, SecondTableId) VALUES ('example', @FirstTableId, 2)
您的实际代码中有错字吗? 因为在您的问题中您说过程参数为@FirstTable
,然后再说该错误与@FirstTableId
有关,在示例过程中,参数的名称为@FirstTableId
。
如果不需要从参数输入或输出任何内容,请在过程中声明并使用变量。
如果尝试使用输出参数,则可以将参数声明为输出:
create proc InsertInto (@FirstTableId int output) as
begin;
set nocount, xact_abort on;
insert into FirstTable
values ('example');
select @FirstTableId = scope_identity();
insert into Relation (FirstTableId, SecondTableId) values
(@FirstTableId, 2);
end;
go
并像这样使用它:
declare @id int;
exec insertinto @id output;
select @id as IdOutput;
回报
+----------+
| IdOutput |
+----------+
| 1 |
+----------+
和关系表中的行:
select * from relation;
回报
+--------------+---------------+
| firsttableid | secondtableid |
+--------------+---------------+
| 1 | 2 |
+--------------+---------------+
rextester 演示 : http ://rextester.com/VPS78362
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.