[英]Using declared variable in another sql query
I want to use my insert query's Id in another query by declaring variable like below. 我想通过声明如下变量在另一个查询中使用我的插入查询的ID。 However second query does not see declared variable.
但是第二个查询看不到声明的变量。 How can I use my first insert's Id in second insert query
如何在第二个插入查询中使用第一个插入的ID
DECLARE @myVariable table (PKProductVariantId INT)
INSERT INTO STProductVariant
(FKProductId,FKProductDetailValueId_,ProductVariantCode,IsActive,StockQuantity)
OUTPUT inserted.PKProductVariantId into @myVariable
values(1,1,'test',1,1)
Then 然后
insert into STBranchProductVariantRelation(FKProductVariant,FKBranch,IsActive)
values (@myVariable,1,1)
You want to use the pk from the inserted row in STProductVariant? 您要使用STProductVariant中插入行的pk吗? Try this:
尝试这个:
INSERT INTO STProductVariant (...) VALUES (...);
SET @lastId := LAST_INSERT_ID();
INSERT INTO STBranchProductVariantRelation (FKProductVariant, FKBranch, IsActive)
VALUES (@lastId, 1, 1);
You need to use insert . . . select
您需要使用
insert . . . select
insert . . . select
insert . . . select
: insert . . . select
:
insert into STBranchProductVariantRelation(FKProductVariant, FKBranch, IsActive)
select t.PKProductVariantId, 1, 1
from @myVariable t;
I think you are confusing your self by naming a table variable a "variable". 我认为您通过将表变量命名为“变量”来混淆自己。 You are then thinking it is a scalar variable.
然后,您认为它是一个标量变量。
I would write this code as: 我将这段代码写为:
DECLARE @ids table (PKProductVariantId INT);
INSERT INTO STProductVariant
(FKProductId, FKProductDetailValueId_, ProductVariantCode, IsActive, StockQuantity)
OUTPUT inserted.PKProductVariantId into @ids
VALUES(1, 1, 'test', 1, 1);
insert into STBranchProductVariantRelation(FKProductVariant, FKBranch, IsActive)
select i.PKProductVariantId, 1, 1
from @ids i;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.