将主键插入到另一个具有两个独立插入的表中

时间:2021-07-06 15:41:46

My code is probably very sloppy and that's probably why I can't get this to work. (Note: I'm using php.) I have 2 inserts on my page and I need to copy the primary key from the first insert and use it in my second insert. The primary key of CustBill_billing is 'bill_ID'. Is there a way to output the primary key of CustBill_billing after it queries so I can use it on my second insert?

我的代码可能非常草率,这可能就是为什么我不能让它工作的原因。(注:我使用php)。我的页面上有两个插入项,我需要从第一个插入项中复制主键并在第二个插入项中使用它。CustBill_billing的主键是“bill_ID”。是否有一种方法可以在查询之后输出CustBill_billing的主键,以便我可以在第二个插入中使用它?

First insert:

首先插入:

    $sql="
INSERT INTO CustBill_billing (C_ID, bolNum, type, le, waybill_date, bill_type, bol_date, con_name, con_city, con_state, ship_name, ship_city, ship_state, contract_num, weight, weight_cd, weight_auth, edc, fsac, ind, stcc, rr_from, rr_to, paymentMeth, unlDcd) 
VALUES ('1', '$pbolNum', '2', 'L', '$today', 'L', '$pbol_date', '$pcon_name', '$pcon_city', '$pcon_state', '$pship_name', '$pship_city', '$pship_state', '$pcontract_num', '$pweight', '$pweight_cd', 'A', 'RR', '1', '$pind', '$pstcc', '$prr_from', '$prr_to', '$ppaymentMeth', '$punlDcd')
";

Second insert:

第二个插入:

foreach($_POST['car_init'] as $key => $car_init)
{
$sql1 = "INSERT INTO CustBill_cars (C_ID, car_init, car_num, bolNum) VALUES ('1', '".$car_init."', '".$car_num[$key]."', '$pbolNum')
";

The reason I have them separate is because I have to loop the 2nd insert because of the auto-generated text boxes; it checks to see how many there are in an array and then inserts each new record into the CustBill_cars table. Each time it inserts, I need the primary key that was created from the first insert to insert into this second query in a field named 'carbill_ID'.

我将它们分开的原因是,由于自动生成的文本框,我必须循环第二个插入;它检查数组中有多少条记录,然后将每个新记录插入CustBill_cars表。每次插入时,我都需要从第一次插入中创建的主键,以便在名为“carbill_ID”的字段中插入第二个查询。

2 个解决方案

#1


0  

In SQL Server, if your Id field is an Identity then you can try SCOPE_IDENTITY(). For example:

在SQL Server中,如果Id字段是标识,那么可以尝试SCOPE_IDENTITY()。例如:

INSERT INTO dbo.MyTable(columns)
   VALUES(...)

SELECT SCOPE_IDENTITY()

#2


0  

I figured it out, I made it way more complicated than need be.

我想出来了,我让它变得比需要的复杂。

$sql1 = "INSERT INTO CustBill_cars (C_ID, car_init, car_num, bolNum, bill_ID)
SELECT 1, '".$car_init."', '".$car_num[$key]."', $pbolNum, CustBill_billing.bill_ID
FROM CustBill_billing
";

#1


0  

In SQL Server, if your Id field is an Identity then you can try SCOPE_IDENTITY(). For example:

在SQL Server中,如果Id字段是标识,那么可以尝试SCOPE_IDENTITY()。例如:

INSERT INTO dbo.MyTable(columns)
   VALUES(...)

SELECT SCOPE_IDENTITY()

#2


0  

I figured it out, I made it way more complicated than need be.

我想出来了,我让它变得比需要的复杂。

$sql1 = "INSERT INTO CustBill_cars (C_ID, car_init, car_num, bolNum, bill_ID)
SELECT 1, '".$car_init."', '".$car_num[$key]."', $pbolNum, CustBill_billing.bill_ID
FROM CustBill_billing
";