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.
| Author |
Topic |
|
jeffj
Starting Member
5 Posts |
Posted - 2004-07-29 : 13:16:59
|
| I am having trouble figuring out how to create a truly dynamic Order By clause.I know I can use the case statements to build my dynamic columns but how do you specify ASC or DESC dynamically?select contactIDfrom contactactsORDER BY case when ( @orderBy = 'email' ) then email when ( @orderBy = 'lastName' ) then lastName else NULL end ascHow can I make the "asc" in the above dynamic so I can specify ASC or DESC?Thanks in advance for your help |
|
|
tkizer
Almighty SQL Goddess
38200 Posts |
Posted - 2004-07-29 : 13:23:14
|
| http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=5942Tara |
 |
|
|
jeffj
Starting Member
5 Posts |
Posted - 2004-07-29 : 13:54:57
|
| Ah of course... Celko's answer makes perfect sense.He did of course leave off one important tid bit though, the desc keyword on sort_2 in the order by clause.SELECT ..CASE WHEN @sort_col = 'A' AND @sort_order = 'ASC' THEN A WHEN @sort_col = 'B'AND @sort_order = 'ASC' THEN BELSE NULL END AS sort_1,CASE WHEN @sort_col = 'A' AND @sort_order = 'DESC' THEN A WHEN @sort_col = 'B'AND @sort_order = 'DESC'THEN BELSE NULL END AS sort_2FROM FoobarWHERE ..ORDER BY sort_1 asc, sort_2 desc |
 |
|
|
|
|
|