Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Dynamic Order By

Author  Topic 

godspeedba
Yak Posting Veteran

90 Posts

Posted - 2010-08-23 : 10:17:45
Hi friends

I'm back again, you would of thought I wouldn't be a novice by now but alas I still require help

I am after a way of doing a dynamic order by clause, so far I have:
ORDER BY
CASE WHEN @Order = 'low' THEN prop_price
WHEN @Order = 'high' THEN prop_price
END


I have a price field that needs to be ordered by ASC or DESC but can't implement this into the above code withouth creating an error message, and ideas?

Many thanks in advance

russell
Pyro-ma-ni-yak

5072 Posts

Posted - 2010-08-23 : 10:23:45
[code]Create Proc myProc
@sortby sysname = 'field1',
@sortDir varchar(4) = 'ASC'
AS

SET NOCOUNT ON

EXEC ('
SELECT field1, field2, field3
FROM yourTable
WHERE someCondition
ORDER BY ' + @sortby + ' ' + @sortDir
)[/code]
Go to Top of Page

Lamprey
Master Smack Fu Yak Hacker

4614 Posts

Posted - 2010-08-23 : 13:17:14
There a lots of ways to do dynamic sorting. Depending on what you are trying to do Dynamic SQL is one way to go. Antoher is to use CASE statements in conjuction with CASTing to the SQL_VARIANT datatype. Here is an article that describes that technique:
http://www.norimek.com/blog/post/2008/04/Dynamic-Sort-Parameters-in-MS-SQL-Server-2005.aspx
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2010-08-23 : 13:19:02
[code]ORDER BY
CASE WHEN @Order = 'low' THEN prop_price
WHEN @Order = 'high' THEN -1 * prop_price
END
[/code]

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -