在SQL中使用XML时的Where子句

Flo*_*ind 9 xml sql sql-server sql-server-2012

我目前在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    |
Run Code Online (Sandbox Code Playgroud)

我的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>
Run Code Online (Sandbox Code Playgroud)

现在根据艺术家获取记录我正在使用查询

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

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

Jas*_*nko 12

试试这个:

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%'
Run Code Online (Sandbox Code Playgroud)

  • 不 :)。我最近学了一些xml,所以我才知道答案。 (2认同)

小智 8

您需要使用.value函数.

SELECT Id, Name, Surname, Title 
FROM DATA 
WHERE Artist.value('(/song/artist-main)[1]','varchar(max)') LIKE '%FatFinger%'
Run Code Online (Sandbox Code Playgroud)