I need to have an order by functionality inside a stored procedure. A value is posted to a webservice and based on that value I have to order the results in a certain way i.e.
When ColName is posted order by ColName When ColName2 is posted order by ColName2
I was looking into using Case but I am getting an error:
Incorrect syntax near '@version'
ORDER BY CASE
WHEN @OrderBy ='Seller (code)' THEN A_SNO
WHEN @OrderBy ='Lot' THEN A_LOTNO
WHEN @OrderBy ='Ring Type' THEN RN_NUM
WHEN @OrderBy ='Aim Error Code' THEN AimRejectionCode
ELSE A_SNO END
DECLARE @version varchar(50)
SET @version = (SELECT DBVERSION FROM MSYSCFG)
PRINT 'New Version = ' + @version
Sorry I'm new to this and using sql server 2008. Any help appreciated UPDATE: Provided additional code. When I leave out the last 3 lines I get an error of
Incorrect synatx near END
UPDATE2: I've changed the ORDER BY TO the following:
ORDER BY
CASE @OrderBy
WHEN @OrderBy = 'Seller (code)' THEN A_SNO
WHEN @OrderBy = 'Lot' THEN A_LOTNO
WHEN @OrderBy = 'Aim Error Code' THEN AimRejectionCode
END
, CASE @OrderBy WHEN 'Ring Type' THEN RingTypeFlag
END
, A_SNO
The first three are varchar and the other is of type int.
This is giving me red lines under all three '=' with an error description of:
'incorrect syntax near '='
and a red line under ORDER BY which gives an error description of:
'A constant expression was encountered in the ORDER BY list, position 3'
Note when I remove the final , A_SNO
The Order By error is gone but I am still receiving the = syntax error