Writing a stored procedure in MS SQL Server 2008 R2, I want to avoid using DSQL...
I would like the sort method (ASC or DESC) to be conditional.
Now, with a numeric column I would simply use a case statement and negate the value to emulate ASC or DESC... That is:
... ORDER BY CASE @OrderAscOrDesc WHEN 0 THEN [NumericColumn] ELSE -[NumericColumn] END ASC
What is an appropriate method for doing this with an alpha column?
EDIT: I thought of a clever way but it seems terribly inefficient... I could insert my ordered alpha column into a temp table with an autonumber then sort by the autonumber using the method described above.
EDIT2:
What do you guys think of this approach?
ORDER BY CASE @OrderAscOrDesc WHEN 0 THEN [AlphaColumn] ELSE '' END ASC,
CASE @OrderAscOrDesc WHEN 0 THEN '' ELSE [AlphaColumn] END DESC
I don't know if forcing a sort on a uniform column is more efficient than deriving numbers from sorted strings though
If you want to sort some of the data in ascending order and other data in descending order, then you would have to use the ASC and DESC keywords. SELECT * FROM table ORDER BY column1 ASC, column2 DESC; That is how to use the ORDER BY clause in SQL to sort data in ascending order.
SELECT column-list FROM table_name [WHERE condition] [ORDER BY column1, column2, .. columnN] [ASC | DESC]; You can use more than one column in the ORDER BY clause. Make sure whatever column you are using to sort that column should be in the column-list.
The SQL ORDER BY Keyword The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.
CASE Syntax: CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 WHEN condition3 THEN result3 ELSE result END; ORDER BY: This keyword is used to sort the result-set in ascending or descending order. It sorts the records in ascending order by default.
One option
;WITH cQuery AS
(
SELECT
*,
ROW_NUMBER() OVER (ORDER BY SortColumn) AS RowNum
FROM
MyTable
)
SELECT
*
FROM
cQuery
ORDER BY
RowNum * @Direction --1 = ASC or -1 = DESC
Or CASE which IMHO is a bit uglier
ORDER BY
CASE WHEN 'ASC' THEN SortColumn ELSE '' END ASC,
CASE WHEN 'DESC' THEN SortColumn ELSE '' END DESC
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