将主键插入到另一个表中,并进行两次单独的插入


Insert primary key into another table with 2 separate inserts

我的代码可能很潦草,这可能就是为什么我不能让这个工作。(注意:我使用php。)我有2个插入在我的页面上,我需要从第一次插入复制主键,并在我的第二次插入使用它。CustBill_billing的主键是'bill_ID'。是否有一种方法可以在CustBill_billing查询后输出主键,以便我可以在第二次插入时使用它?

第一次插入:

    $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')
";

第二插入:

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')
";

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

在SQL Server中,如果你的Id字段是一个Identity,那么你可以尝试SCOPE_IDENTITY()。例如:

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

我想明白了,我把它弄得比需要的更复杂了。

$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
";