order by in sql

Hi Expert,

I used
order by StreetName + ' ' + @SortOrder in store procedure,
@SortOrder  passed

then i execute store procedure
ABC 'desc'

It doesn't work.

Thanks in advance
It doesn't work



LVL 1
dshi15Asked:
Who is Participating?
 
ralmadaConnect With a Mentor Commented:

you can do something like this:
order by CASE when @sortOrder = 'ASC' then StreetName ASC else StreetName DESC END
0
 
Nathan RileyFounderCommented:
can you show your code?
0
 
arnoldConnect With a Mentor Commented:
If you want to order based on several columns, you either need to use order by column1 asc, column2.
Alternatively, you might need to group the item in the select (column1 + ' ' + clomn2 ) as newColumn order by newColumn.
0
 
ralmadaCommented:
If not you will have to use dynamic SQL. so the logic you need in your sp should look like this

declare @strSQL varchar(2000)
 
set @strSQL = 'select field1, field2 from yourtable order by StreetName ' + @sortOrder
 
exec(@strSQL)

Open in new window

0
 
dportasConnect With a Mentor Commented:
ORDER BY
  CASE @SortOrder WHEN 'DESC' THEN StreetName END DESC,
  StreetName ASC
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.