如何从SQL Server中的XML列获取所有数据

时间:2016-01-22 10:21:34

标签: sql-server xml

我正在尝试从XML列中获取数据。这是查询,下面是xml列数据

SELECT 
    [PQDAdvice].value('(/Advice//DORowData/PrimaryValue/node())[1]', 'nvarchar(max)') as PrimaryValue,
    [PQDAdvice].value('(/Advice//DORowData/ListValue1/node())[1]', 'nvarchar(max)') as ListValue1
FROM 
    PatQD 
WHERE
    PQDPatID = '4c983bd8-da00-4395-80bb-a383b21313d5' 

XML内容:

<Advice>
    <DORowData>
        <PrimaryValue>Diet and Nutrition</PrimaryValue>
        <ListValue1>Advice</ListValue1>
    </DORowData>
    <DORowData>
        <PrimaryValue>Salt Restriction</PrimaryValue>
        <ListValue1>Advice</ListValue1>
    </DORowData>
    <DORowData>
        <PrimaryValue>Water Consumption</PrimaryValue>
        <ListValue1>Advice</ListValue1>
    </DORowData>
</Advice>

我得到的问题是我只收到一列而不是所有列

Primary            |ListValue1
Diet and Nutrition |Advice

而不是

Primary            |ListValue1
Diet and Nutrition |Advice
Salt Restriction   |Advice
Water Consumption  |Advice

2 个答案:

答案 0 :(得分:1)

DECLARE @xml XML = '
<Advice>
    <DORowData>
        <PrimaryValue>Diet and Nutrition</PrimaryValue>
        <ListValue1>Advice</ListValue1>
    </DORowData>
    <DORowData>
        <PrimaryValue>Salt Restriction</PrimaryValue>
        <ListValue1>Advice</ListValue1>
    </DORowData>
    <DORowData>
        <PrimaryValue>Water Consumption</PrimaryValue>
        <ListValue1>Advice</ListValue1>
    </DORowData>
</Advice>'

SELECT 
    t.c.value('PrimaryValue[1]', 'nvarchar(max)') as PrimaryValue,
    t.c.value('ListValue1[1]', 'nvarchar(max)') as ListValue1
FROM @xml.nodes('Advice/DORowData') t(c)

输出 -

PrimaryValue            ListValue1
----------------------- ------------
Diet and Nutrition      Advice
Salt Restriction        Advice
Water Consumption       Advice

您的查询 -

SELECT
    PrimaryValue = t.c.value('PrimaryValue[1]', 'NVARCHAR(1000)'),
    ListValue1 = t.c.value('ListValue1[1]', 'NVARCHAR(1000)')
FROM PatQD
CROSS APPLY PQDAdvice.nodes('Advice/DORowData') t(c)
where PQDPatID = '4c983bd8-da00-4395-80bb-a383b21313d5' 

答案 1 :(得分:1)

尝试这样

DECLARE @x XML=
'<Advice>
    <DORowData>
        <PrimaryValue>Diet and Nutrition</PrimaryValue>
        <ListValue1>Advice</ListValue1>
    </DORowData>
    <DORowData>
        <PrimaryValue>Salt Restriction</PrimaryValue>
        <ListValue1>Advice</ListValue1>
    </DORowData>
    <DORowData>
        <PrimaryValue>Water Consumption</PrimaryValue>
        <ListValue1>Advice</ListValue1>
    </DORowData>
</Advice>';

SELECT DoRowData.value('PrimaryValue[1]','varchar(max)') AS PrimaryValue
      ,DoRowData.value('ListValue1[1]','varchar(max)') AS ListValue1
FROM @x.nodes('/Advice/DORowData') AS One(DORowData)