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
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With