2012-03-27 53 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