tags:

views:

83

answers:

4
...@Sort bit) 
AS                
     SELECT
..............

and I want to Order only if Sort = true

How can I realize it ?

Thank you.

+1  A: 

You test the value of the @sort parameter and execute different queries accordingly.

Using IF:

IF (@sort = 0)
  SELECT...
ELSE
  SELECT... 
  ORDER BY ....

Using CASE:

SELECT ...
ORDER BY
  CASE
    WHEN @sort = 1 THEN xxx
    ELSE 1
  END
Oded
That's a maintenance nightmare, unless you comment it really really well. Someone will invariably change one branch and not the other.
Eric H.
+7  A: 

I didn't expect this to work I must admit, but it does. In this example, we sort by town if @sort is set to true, otherwise, we use some other default sort (that must be the same type as the sort column).

DECLARE @sort bit SET @sort = 0

SELECT [addressId]
      ,[customerId]
      ,[addressTypeId]
      ,[address1]
      ,[address2]
      ,[address3]
      ,[town]
      ,[county]
      ,[postcode]
      ,[countryCode]
FROM
    [dbo].[tblAddress]
ORDER BY
    CASE
        WHEN @sort = 1 THEN town
        ELSE 'A'
    END ASC

Edited as per comment suggestion.

Sohnee
Rather than sorting by primary key in your ELSE clause, just sort on some fixed value, like 0 or ''.
Rory MacLeod
Great suggestion. I've updated the answer to reflect that idea.
Sohnee
A: 

Assuming you are using SQL Server (a big assumption) - This post nicely describes a method to so this using dynamic sql (which you almost certainly shouldn't be doing b/c sql server will be unable to optimize the procedur.

But regardless of a method to do this, why would you want to? The added complexity of conditionally sorting is almost surely less optimal the writing a good stored procedure (with proper indexes) that always returns sorted data. Why would you ever specifically need unsorted data (and even if you do need it unsorted, there is no guarantee that SQL won't sort it for you anyway since the returned rows are in a non-deterministic order if a sort isn't specified)?

Chris Clark
+5  A: 
...
ORDER BY
    CASE
        WHEN @sort = 1 THEN sortcolumn
        ELSE 1 --constant value with same type of "sortcolumn" eg '19000101' or 'a'
    END
gbn