Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where clause when using XML in SQL [duplicate]

I am currently using a XML data type in a SQL table

My datatable looks like this

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    |

My XML file looks like this

<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>

Now to get the record depending upon the artist I am using a query which is

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

Is this is the right approach in querying XML data in SQL or are there any built in functions in SQL that can handle XML. I am new to SQL.

like image 298
Flood Gravemind Avatar asked May 10 '13 14:05

Flood Gravemind


People also ask

Can you use WHERE clause twice in SQL?

But yes, you can use two WHERE.

How do you use duplicate value in SQL?

To select duplicate values, you need to create groups of rows with the same values and then select the groups with counts greater than one. You can achieve that by using GROUP BY and a HAVING clause.

How do you not duplicate in SQL?

If you want the query to return only unique rows, use the keyword DISTINCT after SELECT . DISTINCT can be used to fetch unique rows from one or more columns.


2 Answers

Try this:

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%'
like image 68
Jasmina Shevchenko Avatar answered Sep 30 '22 06:09

Jasmina Shevchenko


You need to use the .value function.

SELECT Id, Name, Surname, Title 
FROM DATA 
WHERE Artist.value('(/song/artist-main)[1]','varchar(max)') LIKE '%FatFinger%'
like image 29
Jeff B Avatar answered Sep 30 '22 05:09

Jeff B