首先,我首先要注意的是,我不应该选择在XML中使用nvp及其在修改过程中使用nvp。话虽这么说,我有一个包含XML列的表,该列包含以下xml:
<root>
<results>
<result name='First Result'>
<property name='Property1' value='Value1' />
<property name='Property2' value='Value2' />
</result>
</results>
</root>
我有以下查询来获取结果名称:
SELECT
T.N.value('@name', 'nvarchar(256)') AS resultName
FROM
results CROSS APPLY xmlField.nodes('/root/results/result') AS T(N)
但我不能肯定如何让财产显示出来。我尝试了以下方法:
SELECT
T.N.value('@name', 'nvarchar(256)') AS resultName,
T.N.value('/property[@name="Property1"]/@value', 'nvarchar(256)') AS Property
FROM
results CROSS APPLY xmlField.nodes('/root/results/result') AS T(N)
但是我收到了以下错误:
XQuery [results .xmlField.value()]:&#39; value()&#39;需要一个单例(或空序列),找到类型为&#39; xdt:untypedAtomic *&#39;
的操作数我知道我沿着正确的道路前进,但我不确定我到底应该做些什么。有人能指出我正确的方向吗?
答案 0 :(得分:3)
这就是你要追求的吗?
SELECT
T.N.value('../@name','varchar(255)') as resultName,
T.N.value('@name', 'nvarchar(256)') AS Propertyname ,
T.N.value('@value', 'nvarchar(256)') as Value
FROM
results
cross apply
xmlfield.nodes('/root/results/result/property') AS T(N)
where
T.N.value('@name', 'nvarchar(256)') ='property1'
OR
SELECT
T.N.value('@name', 'nvarchar(256)') AS resultName,
T.N.value('(./property[@name="Property1"]/@value)[1]', 'nvarchar(256)') AS Property
FROM
results CROSS APPLY xmlField.nodes('/root/results/result') AS T(N)
答案 1 :(得分:0)
尝试在xpath中查找第一个匹配的节点。
SELECT organizationDeviceId,
T.N.value('@name', 'nvarchar(256)') AS resultName,
T.N.value('(/property[@name="Property1"])[1]/@value', 'nvarchar(256)') AS Property
FROM results CROSS APPLY xmlField.nodes('/root/results/result') AS T(N)
我不是100%确定结果,但需要使用[1]
来查找第一个结果。