2012-03-27 60 views
4
<book> 
<author>Bob Villa</author> 
<author>Tom Whatever</author> 
<author>Sarah kajdl</author> 
</book> 

我该如何查询任何有Tom作者的记录?我见过的大多数查询示例都引用了值[x],但我想搜索所有作者。查询多个XML值

DECLARE @author as varchar(100) 
SET @author = 'Tom Whatever' 
SELECT xmlfield.value('/book/author') 
WHERE xmlfield.value('/book/author') = @author 

回答

4

下面是答案

DECLARE @x XML 
SET @x = '<book> 
<author>Bob Villa</author> 
<author>Tom Whatever</author> 
<author>Sarah kajdl</author> 
</book>' 

DECLARE @author AS VARCHAR(100) 
SET @author = 'Tom Whatever' 
SELECT c.value('.' ,'VARCHAR(100)') 
FROM @x.nodes('book/author') AS t(c) 
WHERE c.value('.' ,'VARCHAR(8000)') = @author 
+0

如果我想在这种情况下查询标签“作者”的所有外观? http://stackoverflow.com/questions/26426412/how-to-ensure-the-sql-is-able-to-read-all-xml-tag-data – SearchForKnowledge 2014-10-17 13:51:21

3

如果你只是想从一个XML变量的值,你可以直接使用value方法,在你的XPath表达式中使用sql:variable

SELECT @XML.value('(/book/author[.=sql:variable("@author")])[1]', 'nvarchar(50)') 

如果你的XML在一个表中,并且需要有作者的行,你可以使用exist

select * 
from YourTable 
where XMLCol.exist('/book/author[.=sql:variable("@author")]') = 1 

然后,你当然可以结合起来。

select XMLCol.value('(/book/author[.=sql:variable("@author")])[1]', 'nvarchar(50)') 
from YourTable 
where XMLCol.exist('/book/author[.=sql:variable("@author")]') = 1