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)
 Variable ORDER BY

Author  Topic 

AskSQLTeam
Ask SQLTeam Question

0 Posts

Posted - 2004-12-17 : 13:24:16
David writes "Hi

I am attempting to use a variable ORDER BY clause but am being defeated because of the use of DISTINCT in the select line. This is a simplified version:

DECLARE @FirstSortOrder nvarchar(50)
SET @FirstSortOrder = 'CSurname'

SELECT DISTINCT ContactNumber, CSurname FROM Delegate
ORDER BY CASE WHEN @FirstSortOrder = 'CSurname' THEN CSurname END

This gives an error:

ORDER BY items must appear in the select list if SELECT DISTINCT is specified.

The same query without the DISTINCT works fine as descrived in a Forum on this site. The real query links 4 tables together and the DISTINCT is neccessary, and the ORDER BY has a two level order based on CASE statements. All of which works fine until the DISTINCT is introduced.

ANy help would be appreciated.

David"

X002548
Not Just a Number

15586 Posts

Posted - 2004-12-17 : 13:33:55
SELECT * FROM (
SELECT DISTINCT ContactNumber, CSurname FROM Delegate) AS XXX
ORDER BY CASE WHEN @FirstSortOrder = 'CSurname' THEN CSurname END



Brett

8-)
Go to Top of Page
   

- Advertisement -