10

我目前在 SQL 表中使用 XML 数据类型

我的数据表看起来像这样

Id | Name | Surname | Title  | Location | Artist |
-------------------------------------------------------
1  | xxx  | abc     | def    | London   | XML    |
2  | xxx  | abc     | def    | Oslo     | XML    |
3  | xxx  | abc     | def    | New York | XML    |

我的 XML 文件看起来像这样

<song category="gaming">
<title>Valentine's Day</title>
<artist-main>Fatfinger</artist-main>
<artist-featured>Slimthumb</artist-featured>
<year>2013</year>
<price>29.99</price>
<album>Gamestain</album>
<albumimg>http://download.gamezone.com/uploads/image/data/875338/halo-4.jpg</albumimg>
<songurl>http://www.youtube.com/watch?v=-J0ABq9TnCw</songurl>

现在要根据我正在使用的查询的艺术家来获取记录,该查询是

SELECT 
Id, Name, Surname, Title 
FROM 
DATA 
WHERE 
Artist Like '%Fatfinger%' -- (this is user input)

这是在 SQL 中查询 XML 数据的正确方法,还是 SQL 中有任何内置函数可以处理 XML。我是 SQL 新手。

4

2 回答 2

13

试试这个:

declare @table table (
Id int, Name varchar(50), Surname varchar(50), 
Title  varchar(50), Location varchar(50), Artist xml)

insert into @table (Id, Name, Surname, Title, Location , Artist )
values(1, 'xxx', 'abc', 'def', 'London', '<song category="gaming"></song>
<title>Valentines Day</title>
<artist-main>Fatfinger</artist-main>
<artist-featured>Slimthumb</artist-featured>
<year>2013</year>
<price>29.99</price>
<album>Gamestain</album>
<albumimg>http://download.gamezone.com/uploads/image/data/875338/halo-4.jpg</albumimg>
<songurl>http://www.youtube.com/watch?v=-J0ABq9TnCw</songurl>')

SELECT Id, Name, Surname, Title 
FROM @table 
WHERE Artist.value('(/artist-main)[1]','varchar(max)') LIKE '%FatFinger%'
于 2013-05-10T17:51:31.943 回答
8

您需要使用 .value 函数。

SELECT Id, Name, Surname, Title 
FROM DATA 
WHERE Artist.value('(/song/artist-main)[1]','varchar(max)') LIKE '%FatFinger%'
于 2013-05-10T14:43:53.077 回答