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 2000 Forums
 Transact-SQL (2000)
 Dynamic Order By + multiple columns

Author  Topic 

AskSQLTeam
Ask SQLTeam Question

0 Posts

Posted - 2003-09-08 : 07:18:58
wladi writes "I found a great example in the FAQ, but could you help me with the last step?!?!?!
I would like to order (dynamic) on more than 1 column....
So in case of @SortOrder = 1 I would like to order by CompanyName and also on ContactTitle as the second order column

ORDER BY CASE WHEN @SortOrder = 1 THEN CompanyName, ContactTitle
gives an error...


CREATE PROCEDURE ps_Customers_SELECT_DynamicOrderBy
@SortOrder tinyint = NULL
AS
SELECT CompanyName,
ContactName,
ContactTitle
FROM Customers
ORDER BY CASE WHEN @SortOrder = 1 THEN CompanyName
WHEN @SortOrder = 2 THEN ContactName
ELSE ContactTitle
END"

mohdowais
Sheikh of Yak Knowledge

1456 Posts

Posted - 2003-09-08 : 08:11:22
You will need a second CASE Statement:

CREATE PROCEDURE ps_Customers_SELECT_DynamicOrderBy
@SortOrder tinyint = NULL
AS
SELECT CompanyName,
ContactName,
ContactTitle
FROM Customers
ORDER BY
CASE
WHEN @SortOrder = 1 THEN CompanyName
WHEN @SortOrder = 2 THEN ContactName
ELSE ContactTitle
END,
CASE
WHEN @SortOrder = 1 THEN ContactName
WHEN @SortOrder = 2 THEN CompanyName
ELSE ContactTitle
END


Owais


Make it idiot proof and someone will make a better idiot
Go to Top of Page
   

- Advertisement -