Is there a way I can do something like
@sortType
SELECT
*
FROM
table
ORDER BY
-- if sortType == id
table.Id
-- else if sortType == date
table.Date
How would that syntax look? Thanks.
You can use the WHERE clause with or without the ORDER BY statement. You can filter records by finite values, comparison values or with sub-SELECT statements.
An ORDER BY command cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY command can be used to perform the same function as the ORDER BY in a subquery. Subqueries that return more than one row can only be used with multiple value operators such as the IN operator.
Yes, PL/SQL allows us to nest if statements within if-then statements. i.e, we can place an if then statement inside another if then statement. if (condition1) then -- Executes when condition1 is true if (condition2) then -- Executes when condition2 is true end if; end if; SQL.
The ORDER BY clause must come after the WHERE, GROUP BY, and HAVING clause if present in the query. Use ASC or DESC to specify the sorting order after the column name.
There's a gotcha here... you can't mix data types in your case statement, so you need to create different groups of case statements for the different data types.
SELECT
*
FROM
table
ORDER BY
CASE WHEN @SortType = id THEN table.Id END ASC,
CASE WHEN @SortType != id THEN table.Date END ASC
Related blog post:
http://dirk.net/2006/11/14/dynamic-order-by-with-case-statement-in-sql-server-data-type-issues/
Try
ORDER BY
case when @sortType = 'id' then
table.Id
else
table.Date end
Caution: That said, for performance reason it is probably better to split it up or use dynamic sql with sp_executesql
Don't ever do something like that. The resulted query plan will have to satisfy both conditions, since the plan is generic and not tied to a specific runtime value of the @variables. Such plan will miss a lot of possible optimizations. You should explicitly separate the queries:
@sortType
if @sortType == id
SELECT
*
FROM
table
ORDER BY
table.Id
else if @sortType == date
SELECT
*
FROM
table
ORDER BY
table.Date
This is the very same issue as trying to implement dynamic search conditions. The syntactic sugar of using a CASE in the ORDER BY is actually a query optimization blocker.
or just cast the date to an integer...
... ORDER BY case
When @sortType = 'id' Then table.Id
Else cast(table.Date As Integer) end
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