如何通过php发送查询时,为具有复合键的表创建Upsert功能?
我有一个order_items表,其键是订单号和商品号。然后我有一个api到一个商店,它返回一个订单元素的xml文档(我然后解析成数组)。我想取这个字符串并更新已经存在的字符串并插入那些不存在的字符串。由于可能有数百个订单(可能还有数千个订单项),因此我不想运行查询来检查每个订单项的项目是否都存在。
我认为Merge可能就是答案,但我的数据不存在于表中(它是一个我要写入表的数组)。有没有办法将一串数据与现有表合并?例如,等同于:
$query = "IF a.order_id and a.item_id --already exist
update db.dbo.order_items
SET a.quantity = $qty, a.status = $status ....
ELSE
INSERT (order_id, item_id, quantity, status)
VALUES
($order_id, $item_id, $qty, $status)";
run_query($query);
感谢您的帮助。
答案 0 :(得分:1)
如果有其他人遇到这样的问题,那么这个解决方案符合我的所有要求:
merge <table> WITH (HOLDLOCK) as target
USING (VALUES('00001111','385480486071',10, '10.00','3.00','0.00'))
AS source (order_id, item_code, item_quantity, item_price, shipping_price, discount)
ON target.order_id = source.order_id AND target.item_code = source.item_code
WHEN MATCHED THEN
update
SET
item_quantity = source.item_quantity, target.item_price = source.item_price, target.shipping_price = source.shipping_price, discount = source.discount
WHEN NOT MATCHED THEN
INSERT (order_id, item_code, item_quantity, item_price, shipping_price, discount)
values(source.order_id, source.item_code, source.item_quantity, source.item_price, source.shipping_price, source.discount);