开发者

How to get an element tag in SQL Server

开发者 https://www.devze.com 2023-01-20 16:38 出处:网络
I have a stored procedure that receives some XML like this: <Root> <pickh attribute1=\"897\" attribute2=\"GGG\" ....>

I have a stored procedure that receives some XML like this:

<Root>
  <pickh attribute1="897" attribute2="GGG" ....>
      <pickd attribute1="123" attribute2="678" ..../>
  </pickh>
</Root>

or

<Root>
  <rcpth attribute1="ABC" attribute2 ="DEF" ....>
       <rcptd attribute1="012"  attribute2="345" ..../>
  </rcpth>
</Root>

what I need to do is something like:

select Nodetype = (here is the part that I need help),
       Attribute1 = nodes.c.value('@Attribute1','varchar(40)'),
       Attribute2 = nodes.c.value('@Attribute2','varchar(40)')
from   @Xml.nodes('/Root//*') as node(c)

This query should return as result this:

NodeType      Attribute1      Attribute2
pickh          897            GGG
pickd          123            678
rcpth          ABC            DEF
rpctd          012   开发者_如何学运维         345

Is there a way to do this?


declare @Xml xml

set @Xml = '<Root>
                <pickh attribute1="897" attribute2="GGG" >
                    <pickd attribute1="123" attribute2="678" />
                </pickh>
            </Root>'

select NodeType = node.c.value('local-name(.)', 'varchar(15)'),
       Attribute1 = node.c.value('@attribute1','varchar(40)'),
       Attribute2 = node.c.value('@attribute2','varchar(40)')
    from   @Xml.nodes('/Root//*') as node(c)


Yep, and it's incredibly easy:

select Nodetype = node.c.value('local-name(.)','varchar(40)'),
       Attribute1 = node.c.value('@attribute1','varchar(40)'),
       Attribute2 = node.c.value('@attribute2','varchar(40)')
from   @Xml.nodes('/Root//*') as node(c)
0

精彩评论

暂无评论...
验证码 换一张
取 消