带有XML字段的UPDATE SELECT语句

时间:2018-08-29 14:44:13

标签: sql xml xpath

我正在尝试执行UPDATE语句,该语句需要从我加入的表中选择一个值。我需要获取的值是XML节点的一部分,但是我很难获取它。我想从下面提到的XML中获取LocationID。我编辑了代码和表名/字段,但前提保持不变。

我当前的SQL查询:

select order_id from orders where status !=Received and order_id in 
(select order_id from orders where status==delivered)

我一直得到返回的NULL值,但是我可以看到LocationID确实有一个值。

编辑:我的解决方案

UPDATE table1

SET LocationId = CAST(t2.CustomProperties AS xml).value('(/ArrayOfCustomProperty/CustomProperty/@LocationId)[1]', 'varchar(36)')

FROM table1 as t1
INNER JOIN table2 as t2
ON t1.x = t2.x

<?xml version="1.0" encoding="utf-16"?>  <ArrayOfCustomProperty xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">    <CustomProperty>      <DeveloperId>X</DeveloperId>      <Key>ShipToId</Key>      <Value>X</Value>    </CustomProperty>    <CustomProperty>      <DeveloperId>X</DeveloperId>      <Key>CustomerId</Key>      <Value>X</Value>    </CustomProperty>    <CustomProperty>      <DeveloperId>X</DeveloperId>      <Key>CorporateId</Key>      <Value>X</Value>    </CustomProperty>    <CustomProperty>      <DeveloperId>X</DeveloperId>      <Key>NeedsApproval</Key>      <Value>0</Value>    </CustomProperty>    <CustomProperty>      <DeveloperId>X</DeveloperId>      <Key>LocationId</Key>      <Value>X</Value>    </CustomProperty>  </ArrayOfCustomProperty>

2 个答案:

答案 0 :(得分:1)

您的XML似乎是键-值对的典型列表。

如果这在您的控制之下,那么您真的应该将其存储为本机XML ...将XML存储在字符串中既麻烦又缓慢...

您可以使用类似这样的查询来过滤所需的值:

DECLARE @DeveloperId VARCHAR(10)='X';
DECLARE @Key VARCHAR(50)='LocationId';

SELECT CAST(t2.CustomProperties AS xml)
          .value('(/ArrayOfCustomProperty
                   /CustomProperty[(DeveloperId/text())[1]=sql:variable("@DeveloperId")
                                   and (Key/text())[1]=sql:variable("@Key")]
                   /Value
                   /text())[1]','nvarchar(max)');

路径将寻找合适的<CustomProperty>并采用其<Values>的{​​{1}}

答案 1 :(得分:0)

您可以这样尝试:

SET LocationId = (SELECT TOP 1 x.value('/LocationId[1]') AS [LocationId]
FROM CAST(t2.CustomProperties AS xml).nodes('/ArrayOfCustomProperty/CustomProperty') AS a(x)
WHERE x.value('/LocationId[1]') IS NOT NULL)
相关问题