用SCOPE_IDENTITY()制作程序

时间:2017-03-27 17:22:41

标签: asp.net sql-server webforms

我得到了这三张桌子

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(),但我得到这样的错误:"必须声明标量变量&#34 ; @ FirstTableId&#34 ;?我怎样才能解决这个问题并让它发挥作用?

2 个答案:

答案 0 :(得分:1)

您需要在正文中声明变量,而不是存储过程定义。在定义中声明它时,这意味着您将在调用存储过程时传递该值。

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)

答案 1 :(得分:1)

您的实际代码中是否有拼写错误?因为在您的问题中,您说过程参数是@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 |
+--------------+---------------+

返回

    GraphClientHelper graphClientHelper = new GraphClientHelper(tenantId);
        GraphServiceClient graphServiceClient = graphClientHelper.GetGraphServiceClient();
        IGraphServiceUsersCollectionPage user = await graphServiceClient.Users.Request().GetAsync();

rextester 演示http://rextester.com/VPS78362