Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server Dynamic Order By

Tags:

sql

sql-server

I'm trying to use a dynamic order by in a stored procedure so I can pass the order I want the data returned into the stored procedure as a parameter. This works fine for VARCHAR fields however if I try to sort an int or datetime field it errors the code I have is as follows

DECLARE @ORDERBY INT
SET @ORDERBY = 1
SELECT TOP 10 * FROM TBL_LMS_USERS_RECORDs_LAST_ATTEMPT
ORDER BY 
CASE 
    WHEN @OrderBy = 1 THEN s10_record_dow
    --WHEN @OrderBy = 2 THEN pk_big_record_id
    else s10_record_dow
END

If I uncomment the second WHEN in the case statement it errors with

"Error converting data type varchar to bigint."

I can order by this field fine if I dont use the case statement.

Any ideas?

like image 308
Gavin Avatar asked Mar 06 '26 09:03

Gavin


1 Answers

Change it to this:

SELECT TOP 10 * FROM TBL_LMS_USERS_RECORDs_LAST_ATTEMPT
ORDER BY 
    CASE WHEN @OrderBy = 1 THEN s10_record_dow ELSE NUll END,  
    CASE WHEN @OrderBy = 2 THEN pk_big_record_id ELSE NULL END,
    CASE WHEN @OrderBy <> 1 AND  @OrderBy <> 2 THEN s10_record_dow 
         ELSE NULL 
    END
like image 126
Mitch Wheat Avatar answered Mar 09 '26 00:03

Mitch Wheat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!