简体   繁体   English

带有外键/主键的SQL表2表插入

[英]SQL table 2 table insert with foreign/primary keys

i have 2 tables. 我有2张桌子。 One is Order header the other one is order lines. 一个是Order标题,另一个是订单行。 Order header: 订单标题:

OrderID Customer IntegrationID(Identity auto Incremental)

Order lines : 订单行:

OrderID Itemid IntegrationID

The thing i want to do: i run a stored procedure which populates these 2 tables with data and i want the order line to have the same IntegrationID as the order header. 我想做的事情:我运行一个存储过程,用数据填充这两个表,我希望订单行具有与订单头相同的IntegrationID。 For example when i insert to order header: 例如,当我插入订单标题时:

OrderID Customer IntegrationID(Identity auto Incremental)
500       5          1
501       4          2

And in the order lines i want to have the data like this: 在订单行中我想要这样的数据:

OrderID Itemid IntegrationID
 500     101         1
 500     102         1
 501     102         2

Any ideas how can i achieve that? 任何想法我怎样才能实现这一目标? Orderheader and orderlines are linked via ORDERID field. Orderheader和订单行通过ORDERID字段链接。

Its Simple, 这很简单,
For Example In Your Stored Procedure you insert record in table "Order Header" 例如在您的存储过程中,您在“订单标题”表中插入记录

Insert into (col1,col2) values ("val1","val2")

then you should use the following query to insert into table "Order Line" 那么你应该使用以下查询插入表“订单行”

SELECT @new_identity = SCOPE_IDENTITY()

Then insert this @new_identity in the query 然后在查询中插入此@new_identity

Insert into Order Line (OrderID Itemid IntegrationID) values 
("value1","value2",@new_identity)

but make sure these both query executes in same stored procdure if you have individual SP for both then you should have return from the first SP 但要确保这两个查询都在相同的存储过程中执行,如果你有两个SP,那么你应该从第一个SP返回

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

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