查询sql server中的xml数据类型

时间:2017-09-22 09:46:33

标签: sql-server xml

我的sql server中有这个结构:

<?xml version="1.0" encoding="utf-16"?>
<HydroResultTestParameterView xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <ReceptionId>11</ReceptionId>
  <CapsuleCompany>BR</CapsuleCompany>
  <CapsuleSerialNumber>228154</CapsuleSerialNumber>
  <CapsuleType>1</CapsuleType>
  <CapsuleBuiltDate>1389</CapsuleBuiltDate>
  <CapsuleExpireDate>1405</CapsuleExpireDate>
  <GasSystemGeneration>1</GasSystemGeneration>
  <Remark>ok</Remark>
</HydroResultTestParameterView>

我的列的数据类型为nvarchar(max)。所以我想获得ReceptionId的{​​{1}}结果。我怎样才能找到这些结果?

2 个答案:

答案 0 :(得分:0)

这明确地使用XPath表达式选择所有节点,将所有HydroResultTestParameterView带有子元素CapsuleCompany,文本=&#34; BR&#34;:/HydroResultTestParameterView[CapsuleCompany="BR"]/ReceptionId

DECLARE @t TABLE(x XML);
INSERT INTO @t(x)VALUES(N'<HydroResultTestParameterView xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <ReceptionId>11</ReceptionId>
  <CapsuleCompany>BR</CapsuleCompany>
  <CapsuleSerialNumber>228154</CapsuleSerialNumber>
  <CapsuleType>1</CapsuleType>
  <CapsuleBuiltDate>1389</CapsuleBuiltDate>
  <CapsuleExpireDate>1405</CapsuleExpireDate>
  <GasSystemGeneration>1</GasSystemGeneration>
  <Remark>ok</Remark>
</HydroResultTestParameterView>');

SELECT
    n.v.value('.[1]','NVARCHAR(MAX)')
FROM
    @t
    CROSS APPLY x.nodes('/HydroResultTestParameterView[CapsuleCompany="BR"]/ReceptionId') AS n(v)

答案 1 :(得分:0)

SELECT
 convert(xml,ResultTest).query('/HydroResultTestParameterView/CapsuleSerialNumber')

FROM
  [S].[dbo].[HydrostaticTests]
WHERE
   convert(xml,ResultTest).exist('/HydroResultTestParameterView[CapsuleSerialNumber="47274"]') = 1;


//-----------------

SELECT
 convert(xml,ResultTest).value('(/HydroResultTestParameterView/CapsuleSerialNumber)[1]', 'int')

FROM
  [S].[dbo].[HydrostaticTests]
WHERE
   convert(xml,ResultTest).exist('/HydroResultTestParameterView[CapsuleSerialNumber="47274"]') = 1;