Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 从字符串而不是表使用SQL Server合并_Php_Sql Server_Merge_Upsert - Fatal编程技术网

Php 从字符串而不是表使用SQL Server合并

Php 从字符串而不是表使用SQL Server合并,php,sql-server,merge,upsert,Php,Sql Server,Merge,Upsert,通过php发送查询时,如何为具有复合键的表创建Upsert功能 我有一个order_items表,它的键是订单号和项目号。然后,我有一个api到一个存储,它返回一个order元素的xml文档(然后将其解析为数组)。我想用这个字符串更新已经存在的字符串,并插入不存在的字符串。由于可能有数百个订单(可能还有数千个行项目),我不想运行查询来检查每个行项目是否存在该项目 我认为Merge可能是答案,但我的数据不存在于表中(它是一个数组,我将写入表中)。有没有办法将数据字符串与现有表合并?例如,相当于:

通过php发送查询时,如何为具有复合键的表创建Upsert功能

我有一个order_items表,它的键是订单号和项目号。然后,我有一个api到一个存储,它返回一个order元素的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);

感谢您的帮助。

如果其他人遇到这样的问题,以下是满足我所有要求的解决方案:

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);
与(HOLDLOCK)合并为目标
使用(值('00001111','385480486071',10',10.00','3.00','0.00'))
作为来源(订单id、项目代码、项目数量、项目价格、发货价格、折扣)
在target.order\u id=source.order\u id和target.item\u code=source.item\u code上
当匹配时
更新
设置
物料数量=来源。物料数量,目标。物料价格=来源。物料价格,目标。发货价格=来源。发货价格,折扣=来源。折扣
当不匹配时
插入(订单id、项目代码、项目数量、项目价格、发货价格、折扣)
值(source.order\u id、source.item\u代码、source.item\u数量、source.item\u价格、source.shipping\u价格、source.折扣);

警告您的代码可能容易受到sql注入攻击!这不是实际的代码,它只是我正在寻找的功能的一个示例-