selecting individual xml node using SQL

后端 未结 1 1793
礼貌的吻别
礼貌的吻别 2021-02-05 12:19

I have a large XML note with many nodes.

is there a way that I can select only a single node and all of its contents from the larger XML?

i am using sql 2005<

1条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-05 12:42

    You should use the query() Method if you want to get a part of your XML.

    declare @XML xml
    
    set @XML = 
    '
    
      
        1
      
      
        2
      
    
    '
    
    select @XML.query('/root/row2')
    

    Result:

    
      2
    
    

    If you want the value from a specific node you should use value() Method.

    select @XML.value('(/root/row2/value)[1]', 'int')
    

    Result:

    2
    

    Update:

    If you want to shred your XML to multiple rows you use nodes() Method.

    To get values:

    declare @XML xml
    
    set @XML = 
    '
    
      
        1
      
      
        2
      
    
    '
    
    select T.N.value('value[1]', 'int')
    from @XML.nodes('/root/row') as T(N)
    

    Result:

    (No column name)
    1
    2
    

    To get the entire XML:

    select T.N.query('.')
    from @XML.nodes('/root/row') as T(N)
    

    Result:

    (No column name)
    1
    2
    

    0 讨论(0)
提交回复
热议问题