Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IF statement in ORDER BY Clause of a SELECT Statement in a SQL Server Stored Procedure

I am trying to create a stored procedure that takes a bit parameter which if true orders by one column and if false orders by another column. How would I implement this?

Here is what I have so far

CREATE PROCEDURE [dbo].[CLICK10_GetCP]
    @switch AS BIT
AS
    BEGIN
        SELECT
            acct_nbr,
            acct_name
        FROM
            acct
        ORDER BY 

    END
GO
like image 405
Malachi Avatar asked Aug 07 '09 11:08

Malachi


2 Answers

ORDER BY
   CASE WHEN @switch = 0 THEN Field1 END,
   CASE WHEN @Switch = 1 THEN Field2 END
like image 181
Mr. Smith Avatar answered Sep 25 '22 12:09

Mr. Smith


A crude way:

IF @switch = 1
  BEGIN
    SELECT
            acct_nbr,
            acct_name
    FROM
            acct
    ORDER BY acct_nbr
  END
ELSE
  BEGIN
    SELECT
            acct_nbr,
            acct_name
    FROM
            acct
    ORDER BY acct_name
  END

You should also be able to use CASE..WHEN I think:

SELECT
  acct_nbr,
  acct_name
FROM
  acct
ORDER BY
  CASE @switch
    WHEN 1 THEN acct_nbr
    WHEN 0 THEN acct_name
  END
like image 31
Lloyd Avatar answered Sep 25 '22 12:09

Lloyd