如何根据数据库中xml列的兄弟内容获取节点内容?

时间:2015-10-23 20:54:28

标签: sql-server-2005 xquery-sql

<book>
 <author>a1</author>
 <title>t1</title>
</book>
<book>
 <author>a1</author>
 <title>t2</title>
</book>
<book>
 <author>a2</author>
 <title>t3</title>
</book>
<book>
 <author>a3</author>
 <title>t4</title>
</book>

我希望获得作者的所有头衔和书籍标题。书信息作为xml数据存储在db列中。每个都在不同的行。我尝试了各种价值调用,但根本不起作用。我得到的最接近的是:

select parameters.query('//book[author="a1"]/title/text()') from tablename

但是这会返回4行

"t1"
"t2"
""
""

请帮忙

2 个答案:

答案 0 :(得分:1)

试试这个

DECLARE @t TABLE (
    Data XML
)
INSERT INTO @t (Data)
SELECT '<book>
 <author>a1</author>
 <title>t1</title>
</book>
<book>
 <author>a1</author>
 <title>t2</title>
</book>
<book>
 <author>a2</author>
 <title>t3</title>
</book>
<book>
 <author>a3</author>
 <title>t4</title>
</book>'

SELECT
    x.value('author[1]', 'VARCHAR(20)') AS Author
    ,x.value('title[1]', 'VARCHAR(20)') AS Title
FROM @t t
CROSS APPLY Data.nodes('/book') a(x)
WHERE x.value('author[1]', 'VARCHAR(20)') = 'a1'

/*
Author  Title
------  -------
a1         t1
a1         t2
*/

答案 1 :(得分:1)

看起来我误解了value()函数。我一直把[1]放在单引号之外,它一直没能通过。以下内容产生了我想要的东西:

DECLARE @t TABLE (
Book XML
)
INSERT INTO @t (Book) values ( '<book><author>a1</author><title>t1</title></book>')
INSERT INTO @t (Book) values ( '<book><author>a1</author><title>t2</title></book>')
INSERT INTO @t (Book) values ( '<book><author>a2</author><title>t3</title></book>')
INSERT INTO @t (Book) values ( '<book><author>a3</author><title>t4</title></book>')
select Book.value('(/book/title)[1]', 'VARCHAR(20)') as title from @t t
where Book.value('(/book/author)[1]', 'VARCHAR(20)') = 'a1'

感谢RNA Team提供@t示例,我不知道您可以将表声明为变量。节省了我很多时间,因为它允许我在没有真实数据的情况下进行实验