select 全部来自 XML sql

select all from XML in sql

如何 select 来自 sql 中 XML 的所有节点?

XML:

<value>
    <TradeId>5555</TradeId>
    <Account>SomeAccount</Account>
    <Book>1</Book>
    <LocalCcy>XXXX</LocalCcy>
    <ValuationCcy>XXXX</ValuationCcy>
    <PVLocal>44444444</PVLocal>
    <PresentValue>44444444</PresentValue>
    <InstrumentCode>XXXXXXXXX</InstrumentCode>
</value>

我的SQL(不起作用):

SELECT   tradeRef.value('.','varchar(50)') AS strValue
    FROM @xmlData.nodes('data/value') AS trades(tradeRef)
    CROSS APPLY tradeRef.nodes('.') AS legColumns(nameRef)

这给了我所有的值,但在一行中...我想要每个值一行..

你能帮帮我吗?

编辑:

请求的输出(这里只有前两个节点...):

你可以试试这个方法:

declare @xmlData xml
select @xmlData = '<data><value>
    <TradeId>5555</TradeId>
    <Account>SomeAccount</Account>
    <Book>1</Book>
    <LocalCcy>XXXX</LocalCcy>
    <ValuationCcy>XXXX</ValuationCcy>
    <PVLocal>44444444</PVLocal>
    <PresentValue>44444444</PresentValue>
    <InstrumentCode>XXXXXXXXX</InstrumentCode>
</value></data>'

select
    t.c.value('./text()[1]', 'nvarchar(100)') as strValue
from  @xmlData.nodes('//value/child::node()') as t(c)

使用 CROSS APPLY 获得该输出的可能方法:

declare @xmlData XML

set @xmlData = '<value>
    <TradeId>5555</TradeId>
    <Account>SomeAccount</Account>
    <Book>1</Book>
    <LocalCcy>XXXX</LocalCcy>
    <ValuationCcy>XXXX</ValuationCcy>
    <PVLocal>44444444</PVLocal>
    <PresentValue>44444444</PresentValue>
    <InstrumentCode>XXXXXXXXX</InstrumentCode>
</value>'

select
    P.X.value('.', 'int') as TradeId
    ,T.X.value('local-name(.)', 'nvarchar(100)') as NodeName
    ,T.X.value('.', 'nvarchar(100)') as NodeValue
from  @xmlData.nodes('//value/*[not(local-name()="TradeId")]') as T(X)
      cross apply T.X.nodes('../TradeId') as P(X)

SQL Fiddle

如果您想将 TradeId 视为一列而不想将其视为一行:

select
    t.c.value('(TradeId/text())[1]', 'nvarchar(100)') as TradeId,
    r.c.value('local-name(.)', 'nvarchar(128)') as nodeName,
    r.c.value('text()[1]', 'nvarchar(100)') as strValue
from  @data.nodes('data/value') as t(c)
    cross apply t.c.nodes('*[local-name(.) != "TradeId"]') as r(c)

或者你可以使用父轴..(虽然它通常表现更差):

select
    t.c.value('(../TradeId/text())[1]', 'nvarchar(128)') as TradeId,
    t.c.value('local-name(.)', 'nvarchar(128)') as nodeName,
    t.c.value('text()[1]', 'nvarchar(128)') as nodeValue
from  @data.nodes('data/value/*[local-name(.) != "TradeId"]') as t(c)