[英]SQL Server: Use output from first insert to insert into second table
I have a basic stored procedure that adds a new record to a table with a structure like the following.我有一个基本的存储过程,它将新记录添加到具有如下结构的表中。 The table also has a column "itemID" that is set to auto-incrementing to create a unique id for each record.
该表还有一列“itemID”,该列设置为自动递增,以便为每条记录创建唯一 ID。
I would like to use Output to get this id from the new record I inserted and then use this to add a new record to another table ( Table2 with columns colD, colE, colF ).我想使用输出从我插入的新记录中获取此 ID,然后使用它向另一个表(带有 colD、colE、colF 列的 Table2)添加新记录。 colF in Table2 should be the Output from the below as this is the id that links both tables.
表 2 中的 colF 应该是下面的输出,因为这是链接两个表的 ID。
Can someone here tell me how this would work as I am pretty new to SQL and have never done this before ?这里有人可以告诉我这是如何工作的,因为我对 SQL 还很陌生并且以前从未这样做过吗?
My stored procedure (example):我的存储过程(示例):
ALTER PROCEDURE [dbo].[CreateStuff]
@colA datetime,
@colB varchar(50),
@colC nvarchar(20)
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO Table1
(
colA,
colB,
colC
)
SELECT @colA,
@colB,
@colC
END
Many thanks for any help with this, Tim.非常感谢您对此的任何帮助,蒂姆。
BEGIN
SET NOCOUNT ON;
/* Here declare a Table Variable */
DECLARE @Table_Var TABLE(itemID INT)
INSERT INTO Table1(colA,colB,colC)
OUTPUT inserted.itemID INTO @Table_Var(itemID)
SELECT @colA,@colB,@colC
/* Now do the insert into Table 2*/
INSERT INTO TABLE2
SELECT itemID FROM @Table_Var
END
SCOPE_IDENTITY()
is only good when you are doing a single Insert, and it is an IDENTITY column whos value you want to capture. SCOPE_IDENTITY()
仅在您执行单个 Insert 时SCOPE_IDENTITY()
,并且它是您要捕获其值的 IDENTITY 列。 It will only return the last Generated Identity value.它只会返回最后一个 Generated Identity 值。
Other then that if you are doing multiple insert or it isn't an identity column then you should use OUTPUT
clause along with a table variable/temp table to capture the inserted values.除此之外,如果您正在执行多个插入或者它不是标识列,那么您应该使用
OUTPUT
子句以及表变量/临时表来捕获插入的值。 and then do whatever you want to do with them values later on (insert in another table/logging whatever).然后在以后对它们的值做任何你想做的事情(插入另一个表/记录任何东西)。
To learn more about OUTPUT Clause
have a look at this link.要了解有关
OUTPUT Clause
更多信息,请查看此链接。
Try with SCOPE_IDENTITY()
:尝试使用
SCOPE_IDENTITY()
:
ALTER PROCEDURE [dbo].[CreateStuff]
@colA datetime,
@colB varchar(50),
@colC nvarchar(20),
@Valueout int output
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO Table1
(
colA,
colB,
colC
)
SELECT @colA,
@colB,
@colC
SET @Valueout = SCOPE_IDENTITY()
END
You can create a Trigger on the table as follows:您可以按如下方式在表上创建触发器:
CREATE TRIGGER Trigger_Name
ON Table_Name
AFTER INSERT,UPDATE
AS
BEGIN
SET NOCOUNT ON;
INSERT INTO Table1 ( colA, colB, colC )
SELECT colA, colB, colC FROM Inserted
END
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.