Hello,
Basically I am trying to do an order by statement using variables.
I have the SQL:
IF
@SortOrder = 'ASC' BEGIN SELECT DISTINCT D.Code as 'T1', D.CompanyName as 'T2',S
.SpendAmount as 'T3', E.SpendAmount as 'T4',E
.SpendAmount - S.SpendAmount as 'T5', Case When S.SpendAmount > 0 Then ((E.SpendAmount - S.SpendAmount)/S.SpendAmount) * 100 When S.SpendAmount = 0 Then ((E.SpendAmount - S.SpendAmount)/1) When E.SpendAmount > 0 Then ((E.SpendAmount - S.SpendAmount)/E.SpendAmount) * 100 When E.SpendAmount = 0 Then ((E.SpendAmount - S.SpendAmount)/1) END as 'T6' FROM DivisionData D, (SELECT Code, SpendAmount FROM DivisionData WHERE Year = @StartYear and Month = @StartMonth and Division = @Division) S, (SELECT Code, SpendAmount FROM DivisionData WHERE Year = @EndYear and Month = @EndMonth and Division = @Division) E WHERE D.Division = @Division AND S.Code = D.Code AND E.Code = D.Code ENDI have the params @Crit1 @Crit2 .... to @Crit6. These parameters come from a web form and can have the values 'T1' 'T2'... to 'T6' They correspond to the field names I have put in my select statement.
What I want to do is use these params in an Order By statement, enabling the user to select how the fields are ordered.
I have tried using something along the lines of:
ORDER
BYCASE
WHEN @Crit1 = 'T1' THEN 'T1' END
This works as long as I dont use the word DISTINCT in my select statement, otherwise I get the error:
Msg 145, Level 15, State 1, Line 4
ORDER BY items must appear in the select list if SELECT DISTINCT is specified.
I do need the distinct... I was wondering if there is a simple way to get round this, or if anyone can point me in the right direction or a article/example of this
Many thanks
Andrew Rayner