Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to use order by clause with for xml path properly(Sql server)

I have the below situation (say tblRecord)

ID RowNum  Data
1 1  and seventy nine
1 2  five hundred
1 3  two thousand

I need the output to be

ID   Data
 1   two thousand five hundred and seventy nine

I have the below query

select ID , Data = 
  ( Select ' ' + cast(Data as varchar(max)) from tblRecord t2
                  where t2.RowNum= t1.RowNum
                  and t2.ID =t1.ID
                  order by t1.RowNum
                  for xml path(''))
from tblRecord t1
group by t1.ID

But the output is

ID  Data
1 five hundred two thousand and seventy nine

Help needed for this.

Thanks

like image 684
eshweeer Avatar asked Dec 08 '10 12:12

eshweeer


People also ask

Which is the correct mode that can be used along with FOR XML clause?

A SELECT query returns results as a rowset. You can optionally retrieve formal results of a SQL query as XML by specifying the FOR XML clause in the query. The FOR XML clause can be used in top-level queries and in subqueries. The top-level FOR XML clause can be used only in the SELECT statement.

How do you use order by with in SQL?

The ORDER BY statement in SQL is used to sort the fetched data in either ascending or descending according to one or more columns. By default ORDER BY sorts the data in ascending order. We can use the keyword DESC to sort the data in descending order and the keyword ASC to sort in ascending order.

When should I use XML Path?

We can use FOR XML PATH to prepare a comma-separated string from the existing data. Let's create an Authors table and insert a few records into it. In the data, we can see we have an ID column and the AuthorName column. If we just select the records, it gives the output in the following format.

What is XML RAW in SQL Server?

RAW mode transforms each row in the query result set into an XML element that has the generic identifier <row>, or the optionally provided element name. By default, each column value in the rowset that is not NULL is mapped to an attribute of the <row> element.


1 Answers

Try this:

SELECT DISTINCT
    ID, Data = (SELECT ' ' + Data 
                FROM dbo.tblRecord t2
                WHERE t2.ID = t1.ID
                ORDER BY t2.RowNum DESC
                FOR XML PATH('')
               )
FROM dbo.tblRecrd t1

Your first problem was the ORDER BY t1.RowNum in the inner select - needs to be ORDER BY t2.RowNum instead. Secondly: this join condition where t2.RowNum= t1.RowNum is not necessary and causes problems. And thirdly: the GROUP BY is again neither needed nor helpful - just use the SELECT DISTINCT to achieve what you're looking for.

Also - not sure why you're casting Data as VARCHAR(MAX) ???

like image 92
marc_s Avatar answered Sep 28 '22 13:09

marc_s