Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

select an xml type column in select query with group by SQL Server 2008

I am writing a select query in which I am fetching several columns (by joining 3-4 tables). I use group by clause to group my results.

Query -

    select ci.Candidate_Id, ci.FirstName, ci.DetailXML
from Candidate_Instance ci 
where ci.Candidate_Instance_Id=2
group by 
ci.Candidate_Id, ci.FirstName, ci.DetailXML

One of the tables have a column which is of XML data type. When I add the column in the select list, I get this error -

Column 'table.myXML' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

and when I add the column in the group by clause, I get this error -

The XML data type cannot be compared or sorted, except when using the IS NULL operator.

I am quite confused as to how to come out of this. I want to get the XML data from the column.

Thanks

like image 772
saarthak Avatar asked Mar 07 '11 16:03

saarthak


People also ask

How do I query an XML column in SQL?

SQL Server provides the XQuery feature to querying XML data type or querying with the XML column with the XPATH. Using XQuery, users can Insert, Update and Delete with the XML nodes and node values in an XML column.

How do I SELECT a specific XML node in SQL Server?

You should use the query() Method if you want to get a part of your XML. If you want the value from a specific node you should use value() Method. Update: If you want to shred your XML to multiple rows you use nodes() Method.

Can we use SELECT * with GROUP BY?

When issuing a query with SELECT , you can end it with GROUP BY to group the selected columns by a particular column value. This is typically used in combination with aggregate functions, so that the results show the result of some aggregation function for rows with particular column values.

How do I get data from XML format in SQL Server?

To retrieve data in XML format from SQL Server database, we can use FOR XML <options> clause. Notice the last three words in the above query. We have a normal SELECT statement and in the last of the statement, we are suffixing FOR XML RAW that will return the data from PersonalDetails table in Raw xml format.


1 Answers

You cannot group by XML or TEXT columns, you would first need to convert to varchar(max)

select ci.Candidate_Id, ci.FirstName, convert(xml,convert(varchar(max),ci.DetailXML)) DetailXML
from Candidate_Instance ci 
where ci.Candidate_Instance_Id=2
group by 
ci.Candidate_Id, ci.FirstName, convert(varchar(max),ci.DetailXML)

On the first line, it is converted to varchar(max) to match the GROUP BY clause, and later it is re-cast back to XML.

like image 172
RichardTheKiwi Avatar answered Oct 10 '22 07:10

RichardTheKiwi