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
 SQL Server 2005 Forums
 Transact-SQL (2005)
 CTE and Order By, how can I make it dynamic ?

Author  Topic 

sql777
Constraint Violating Yak Guru

314 Posts

Posted - 2008-01-14 : 16:27:35
Hi,

I want to pass a parameter in my stored procedure so I can have my ORDER by clause use either ASC or DESC.

How can I do this when I am also using a CTE?

e.g.

WITH myCTE AS
(

)

SELECT *
FROM MyCTE
ORDER BY ASC/DESC **** <-- depending on my paramenter @SortOrder

TG
Master Smack Fu Yak Hacker

6065 Posts

Posted - 2008-01-14 : 17:08:30
whether you use a CTE or not, with 2005 you can dynamically order asc/desc using something like this:

declare @sortOrder varchar(4)
set @sortOrder = 'asc'

select top 20 id from sysobjects
order by
case
when @sortorder = 'asc' then rank() over (order by id)
else rank() over (order by id desc)
end


Be One with the Optimizer
TG
Go to Top of Page
   

- Advertisement -