我已经打了一段时间,似乎我很接近,但不是那里.我在数据库中有一个列如下所示:
<document>
<items>
<item name="one">one is the first number</item>
<item name="two">two is the second number</item>
</items>
</document>
在这个例子中,我需要查询并返回'two is the second number'.我也想在不创建临时表的情况下这样做.目前我有:
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而无需转换为临时表?
我也想在不创建临时表的情况下这样做
您可以使用数据类型为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.