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
 Incorrect syntax near the keyword 'order '

Author  Topic 

kirank
Yak Posting Veteran

58 Posts

Posted - 2011-05-14 : 14:38:56
how to assign order by

Declare @SortExp as varchar(50)
if @mSortBy = 'New'
begin
set @SortExp = 'addon desc'
end
order by @SortExp

if i run like this it gives me error as
Incorrect syntax near the keyword 'order'.

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2011-05-14 : 17:02:15
Well you can't dynamically set the ordering that way. You have to use dynamic SQL instead.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page

GilaMonster
Master Smack Fu Yak Hacker

4507 Posts

Posted - 2011-05-14 : 17:41:29
Untested, but I know the case in Order By does work

ORDER BY
CASE
WHEN @mSortBy = 'New' THEN addon
ELSE SomeOtherColumn
END DESC



--
Gail Shaw
SQL Server MVP
Go to Top of Page

kirank
Yak Posting Veteran

58 Posts

Posted - 2011-05-15 : 12:32:51
thx for the help help

actually here desc is also not fix it may change asc also

senario is

CASE
WHEN @mSortBy = 'New' THEN addedon DESC
WHEN @mSortBy = 'Old' THEN Old ASc
WHEN @mSortBy = 'Prev' THEN Prev Asc

ELSE SomeOtherColumn
END
so plz help me here i cant specify this asc or desc
Go to Top of Page

GilaMonster
Master Smack Fu Yak Hacker

4507 Posts

Posted - 2011-05-15 : 12:38:02
See Tara's reply in that case.

--
Gail Shaw
SQL Server MVP
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2011-05-15 : 23:29:53
You can use a dual order by case.

order by
case when @msortby = 'new' then addedon else null end desc,
case when @msortby = 'old' then old when @msortby = 'prev' then prev else null end asc



N 56°04'39.26"
E 12°55'05.63"
Go to Top of Page

kirank
Yak Posting Veteran

58 Posts

Posted - 2011-05-16 : 13:43:13
thx for reply. here i have change like this way.

case when @msortby = 'new' then addedon else null end desc,
case when @msortby = 'descpop' then b.rating end desc,
case when @msortby = 'descrating' then b.rating else null end asc

http://webdevlopementhelp.blogspot.com
Go to Top of Page

tkizer
Almighty SQL Goddess

38200 Posts

Posted - 2011-05-16 : 13:52:22
I had completely forgotten about the dynamic order by using case rather than dynamic SQL. Here's an article that goes over this topic: http://www.sqlteam.com/article/dynamic-order-by

Be sure to check out the article's comments as it goes into solutions for several problems with the technique, such as data type issues.

Tara Kizer
Microsoft MVP for Windows Server System - SQL Server
http://weblogs.sqlteam.com/tarad/

Subscribe to my blog
Go to Top of Page
   

- Advertisement -