简体   繁体   English

获取标识值并将其插入其他表

[英]Getting the Identity value and Inserting into Other table

I am having an Identity element for Table 1 (ID Column). 我有一个用于表1(标识列)的标识元素。

I make a SP where I insert into Table1 and then I want that identity value to be inserted into other table. 我在插入Table1的位置制作了一个SP,然后希望将该标识值插入其他表。

Insert into Table 1 values (Name, RollNo) -- Get the Id of the identity element and insert into other table
Insert into Table 2 values (ID, Standard)

I tried making a temp table 我试图做一个临时表

DECLARE @OutputTbl TABLE (ID INT)

Insert into Table 1 values (Name, RollNo)
OUTPUT INSERTED.ID INTO @OutputTbl(ID)

//But now how should I insert into Table2. //但是现在我应该如何插入Table2。

Or is there any other good way ? 还是还有其他好的方法?

Use SCOPE_IDENTITY() to get the identity last generated in your stored procedure. 使用SCOPE_IDENTITY()获取在存储过程中最后生成的身份。

From MSDN: 从MSDN:

Returns the last identity value inserted into an identity column in the same scope. 返回插入到同一作用域的标识列中的最后一个标识值。 A scope is a module: a stored procedure, trigger, function, or batch. 范围是一个模块:存储过程,触发器,函数或批处理。 Therefore, two statements are in the same scope if they are in the same stored procedure, function, or batch. 因此,如果两个语句位于相同的存储过程,函数或批处理中,则它们属于同一范围。

You can use the following tsql: 您可以使用以下tsql:

DECLARE @ScopeIdentity int

INSERT INTO Table1 VALUES (Name, RollNo)
SELECT @ScopeIdentity = SCOPE_IDENTITY()
INSERT INTO Table2 VALUES (@ScopeIdentity, Standard)

For more information you can read this article by Pinal Dave 有关更多信息,您可以阅读Pinal Dave的这篇文章

update 更新

To enable Rollback as per your question in the comments, you can use a transaction and Try...catch : 要根据评论中的问题启用回滚,可以使用事务Try ... catch

DECLARE @ScopeIdentity int
BEGIN TRY
BEGIN TRANSACTION

INSERT INTO Table1 VALUES (Name, RollNo)
SELECT @ScopeIdentity = SCOPE_IDENTITY()
INSERT INTO Table2 VALUES (@ScopeIdentity, Standard)

COMMIT TRANSACTION
END TRY
BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION
END CATCH

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM