Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Order by a Parameter

Status
Not open for further replies.

joebickley

Programmer
Aug 28, 2001
139
0
0
GB
Hi, im trying the following in a stored proc

Select * from tablex
order by coalesce(@sortfield, referencenumber)

I want it to sort by a field that i pass into it, if it is not provided i want to use the reference number but it doesnt work. I cant build up the SQL text and execute it as i have other stuff going on that makes that impracticle. If i remove the coalesce bit and just put the @sortfield again it doent work

Any ideas?

 
You would have to do it dynamically like this:

declare @sql1 varchar(500)

select @sql1 =
'Select * from tablex
order by coalesce(' + @sortfield + ', referencenumber)'

exec(@sql1)
 
I have taken this code from a reply given to a similar query on this forum. I am not claiming credit for it though!!!

Code:
SELECT T.Field1, T.Field2, T.Field3
  FROM Table T
  WHERE [condition]
  ORDER BY 
    CASE WHEN @SortOrder = 'Field1' THEN T.Field1
         WHEN @SortOrder = 'Field2' THEN T.Field2
         ELSE T.ReferenceNumber END
 
I know i can use the CASE method but with 50 fields its not very practicle.

And as for building the SQL string and executing it, like i said in the original post there are other things preventing that.

No matter i will look for another way

Thanks anyway

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top