在php脚本中存储db2 merge语句中的主键

时间:2019-01-24 01:59:38

标签: php db2

我有一个php脚本,其中设置了要在db2的2个合并语句中使用的参数。

问题是,在我的第一个合并语句上,我需要获取并使用受影响行的主键(如果合并进行了更新,请获取更新行的ID。如果执行插入,则要获取新创建的行) ID),因为我需要在第二次合并中使用ID /主键(插入或更新已具有它的行)

我的两个合并语句:

/*products table*/
MERGE INTO products AS P
    USING(VALUES(

        :GROUP,
        :DTL12,
        :DTL13,
        :CUSTNM,
        :SELLINGN,
        :COUNT_PLMN_1,
        :LAST_DATE

        )
    )

AS S(GROUP,DTL12,DTL13,CUSTNM,SELLINGN,COUNT_PLMN_1,LAST_DATE)
ON s.GROUP = p.GROUP and s.DTL12 = p.DTL12 and s.DTL13 = p.DTL13 and s.CUSTNM = p.CUSTNM 

WHEN MATCHED
    THEN UPDATE SET LAST_DATE = s.LAST_DATE

WHEN NOT MATCHED
    THEN INSERT VALUES (s.GROUP,s.DTL12,s.DTL13,s.CUSTNM,s.SELLINGN,s.COUNT_PLMN_1,s.LAST_DATE)



/*ORDERS Table*/
MERGE INTO ORDERS AS PO
    USING(VALUES(

        /*need foreign key, which is id from products table*/
        :QUANTITY,
        :LAST_DATE,
        :INVOICE_NUMBER
    ))

AS S(PRODUCT_ID,quantity_ordered,LAST_DATE,invoice_number)
ON s.PRODUCT_ID = po.id

WHEN MATCHED
    THEN UPDATE SET LAST_DATE = s.LAST_DATE, quantity_ordered = s.quantity_ordered, invoice_number = s.invoice_number

WHEN NOT MATCHED
    THEN INSERT VALUES (s.PRODUCT_ID, s.quantity_ordered, s.LAST_DATE, s.invoice_number)

如何在php脚本中正确处理此问题?

1 个答案:

答案 0 :(得分:2)

您无法从db2中的select中进行merge的诱惑。要在Product中获得受影响的ID(插入或更新),您可以使用以下查询:

with s (GROUP, DTL12, DTL13, CUSTNM, SELLINGN, COUNT_PLMN_1, LAST_DATE) as (VALUES
  (:GROUP, :DTL12, :DTL13, :CUSTNM, :SELLINGN, :COUNT_PLMN_1, :LAST_DATE)
) 
, u as (
select id 
from new table (
update products p
set (last_date)=(
select s.last_date 
from s
where s.GROUP = p.GROUP and s.DTL12 = p.DTL12 and s.DTL13 = p.DTL13 and s.CUSTNM = p.CUSTNM
)
where exists (
select s.last_date 
from s
where s.GROUP = p.GROUP and s.DTL12 = p.DTL12 and s.DTL13 = p.DTL13 and s.CUSTNM = p.CUSTNM
)
)
)
, i as (
select id
from new table(
insert into products (GROUP, DTL12, DTL13, CUSTNM, SELLINGN, COUNT_PLMN_1, LAST_DATE)
select GROUP, DTL12, DTL13, CUSTNM, SELLINGN, COUNT_PLMN_1, LAST_DATE
from s
where not exists (
select 1
from products p
where s.GROUP = p.GROUP and s.DTL12 = p.DTL12 and s.DTL13 = p.DTL13 and s.CUSTNM = p.CUSTNM
)
)
)
select id 
from table (values coalesce((select id from u), (select id from i))) t(id);

这里有2条针对Products-Update(如果存在对应行)和Insert(如果对应行不存在)的数据更改语句。从两个数据更改语句中的Select检索受ID影响(在Insert生成或更新)的#[message.inboundProperties.'http.query.params'],并返回其中之一。