【问题标题】:Parse / query XML using TSQL使用 TSQL 解析/查询 XML
【发布时间】:2012-01-12 23:10:43
【问题描述】:

我已经为此奋斗了一段时间,似乎我已经很接近了,但并不完全在那里。我在数据库中有一个如下所示的列:

<document>
<items>
<item name="one">one is the first number</item>
<item name="two">two is the second number</item>
</items>
</document>

在本例中,我需要查询并返回“二是第二个数字”。我也想在不创建临时表的情况下执行此操作。目前我有:

create table #test (item1 xml)
insert into #test (item1) 
values ('<document> <items> <item name="one">one is the first number</item> <item name="two">two is the second number</item> </items> </document>')

select item1.value('(/document/items/item)[2]', 'nvarchar(max)') from #test
select item1.query('/document/items/item[@name="two"]') from #test

第一个选择返回正确的值,但我需要知道它是第二个“索引” 第二个返回我想要的,但它返回整个节点两个..

我错过了什么?而且,有没有一种简单的方法可以在不转换为临时表的情况下使用 XML?

【问题讨论】:

    标签: sql xml tsql


    【解决方案1】:

    我也想在不创建临时表的情况下这样做

    您可以使用数据类型为 XML 的变量。

    declare @xml xml
    
    set @xml = 
    '<document>
      <items>
        <item name="one">one is the first number</item>
        <item name="two">two is the second number</item>
      </items>
    </document>'
    
    select @xml.value('(/document/items/item[@name="two"])[1]', 'nvarchar(max)')
    

    或者您可以在查询中将字符串转换为 XML。

    select cast(
                '<document>
                  <items>
                    <item name="one">one is the first number</item>
                    <item name="two">two is the second number</item>
                  </items>
                </document>' as xml
               ).value('(/document/items/item[@name="two"])[1]', 'nvarchar(max)')
    

    您的第一个查询使用正确的.value(),而您的第二个查询具有正确的 XQuery 表达式。使用.value() 时,您需要使用返回单个值的XQuery 表达式。这将为您提供@name 是两个/document/items/item[@name="two"]) 的所有项目节点。在末尾添加 [1] 可确保您只会在 XML 中第一次出现 @name 是两个。

    【讨论】:

      【解决方案2】:

      (首先,您可以使用xml 类型的变量,而不是临时表,就像我在下面所做的那样。这些变量可以直接从字符串文字分配)

      所以我认为你的意思是你想要item 节点的文本值与name two,在这种情况下,你只需要在你在value() 调用中使用的xpath 中包含适当的条件:

      DECLARE @x xml
      
      SET @x = '<document> <items> <item name="one">one is the first number</item> 
           <item name="two">two is the second number</item> </items> </document>'
      
      SELECT @x.value('(/document/items/item[@name="two"])[1]', 'nvarchar(max)')
      

      给予

      --------------------------------------------------------------
      two is the second number
      
      (1 row(s) affected)
      

      【讨论】:

        猜你喜欢
        • 2023-04-07
        • 1970-01-01
        • 2014-05-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-02
        • 1970-01-01
        相关资源
        最近更新 更多