2011-08-24 43 views
1
select * 
from tablename 
where CONVERT(xml, Sections).value('(/sections/section/@value)[1]', 'varchar(1)') = 'f' 

将正确检索与在第列以下值的记录:SQL Server中的XML类型选择其中属性= X从任何标记

<sections><section value="f" priority="4" /><section value="a" priority="4" /></sections> 

但是错过这样的:

<sections><section value="w" priority="4" /><section value="f" priority="4" /></sections> 

显然这是“/sections/section/@value)[1]”的问题,但我不明白这个语法,Google也没有太大的帮助。我发现一些代码让我走得这么远,但我不知道如何修改它,以便它可以查看所有标记而不是第一个标记。我试图丢弃[1]但给出了以下错误:

XQuery [value()]: 'value()' requires a singleton (or empty sequence), found operand of type 'xdt:untypedAtomic *' 

回答

2

您可以使用exist()

select * 
from tablename 
where CONVERT(xml, Sections).exist('/sections/section[@value = "f"]') = 1 

如果你想使用一些动态值,而不是硬查询编码f可以使用sql:variable()

declare @Value varchar(10) = 'f' 

select * 
from tablename 
where CONVERT(xml, Sections).exist('/sections/section[@value = sql:variable("@Value")]') = 1 
+0

感谢您的链接也做文档。我的Google Fu今天很弱,但这正是我所期待的。 – Dzejms

1

如果你有一个XML标签的多个条目,你需要使用.nodes() XQuery的方法:

select 
    *, 
    Sections(Section).value('(@value)[1]', 'varchar(1)') 
from tablename 
cross apply CONVERT(xml, Sections).nodes('/sections/section') AS Sections(Section) 

有了这个,你创造称为Sections(Section)的“伪表”,其中包含与您的XPath匹配的每个元素的一个XML行(对于<sections>下的每个<section>)。然后,您可以访问此伪表并使用hte从这些XML“行”中提取各个信息位。方法.value()方法