snippetMinor
CASE ORDER BY with multiple columns, and different sort options
Viewed 0 times
caseordercolumnswithoptionsdifferentmultipleandsort
Problem
I am attempting to use a T-SQL
My question is: How can I get the date column to sort desc when I am passed a 2 for that parameter, and have the a string column sort asc in the same CASE ORDER BY statement?
This is what I have now for the
This codes parses and returns a result set without error, but the 2nd CASE ORDER BY is all in DESC sort order, when I would prefer to have ccd.CertEndDate DESC , tp.LastName ASC , tp.FirstName ASC
Thanks in advance.
CASE ORDER BY in a stored procedure where I am passed @OrderBy parameter as a TINYINT. @Orderby = 1 Then Date column should be ASC
@Orderby = 2 Then Date column should be DESC
My question is: How can I get the date column to sort desc when I am passed a 2 for that parameter, and have the a string column sort asc in the same CASE ORDER BY statement?
This is what I have now for the
CASE ORDER BYORDER BY
CASE WHEN @OrderBy = 1 THEN CONVERT(NVARCHAR(30) , ccd.CertEndDate) + tp.LastName + tp.FirstName END ,
CASE WHEN @OrderBy = 2 THEN CONVERT(NVARCHAR(30) , ccd.CertEndDate) + tp.LastName + tp.FirstName END DESCThis codes parses and returns a result set without error, but the 2nd CASE ORDER BY is all in DESC sort order, when I would prefer to have ccd.CertEndDate DESC , tp.LastName ASC , tp.FirstName ASC
Thanks in advance.
Solution
Break it out a little more:
You only need the sort order to change on the first field, so don't enclose the others in the
It should be noted that we don't include an
ORDER BY CASE WHEN @orderby = 1 THEN CONVERT(NVARCHAR(30) , ccd.CertEndDate) END ASC,
CASE WHEN @orderby = 2 THEN CONVERT(NVARCHAR(30) , ccd.CertEndDate) END DESC,
tp.lastname ASC,
tp.firstname ASCYou only need the sort order to change on the first field, so don't enclose the others in the
CASE.It should be noted that we don't include an
ELSE for each CASE, which means any other value will return NULL and be discarded from the ORDER BY.Code Snippets
ORDER BY CASE WHEN @orderby = 1 THEN CONVERT(NVARCHAR(30) , ccd.CertEndDate) END ASC,
CASE WHEN @orderby = 2 THEN CONVERT(NVARCHAR(30) , ccd.CertEndDate) END DESC,
tp.lastname ASC,
tp.firstname ASCContext
StackExchange Database Administrators Q#9109, answer score: 6
Revisions (0)
No revisions yet.