Question : Using a variable in the ORDER BY clause of an SQL stored procedure.

I am writing a stored procedure which will be used to run a SELECT query with multiple ORDER BY columns.  I will pass in the ORDER BY parameters -- @FIELD1, @FIELD2, for example.  Problem is, SQL won't let me use a variable in the ORDER BY clause.

I want the proc to look like this:

CREATE PROCEDURE udp_MULTI_SORT @FIELD1 VARCHAR(15), @FIELD2 VARCHAR(15)
AS

SELECT * FROM RM00101 ORDER BY @FIELD1, @FIELD2

The SQL error I get when I try this is:

The SELECT item identified by the ORDER BY number 1 contains a variable as part of the expression identifying a column position. Variables are only allowed when ordering by an expression referencing a column name.

Does anyone know a way around this?

Answer : Using a variable in the ORDER BY clause of an SQL stored procedure.

as the error message indicates: change the field names into field positions (data type int), OR you have to change to a "dynamic" sql at some point
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
CREATE PROCEDURE udp_MULTI_SORT @FIELD1 VARCHAR(15), @FIELD2 VARCHAR(15)
AS
SELECT * 
 FROM RM00101 
ORDER BY CASE 
   WHEN @FIELD1 = 'Col1' THEN Col1 
   WHEN @FIELD1 = 'Col2' THEN Col2
   --- etc ----
  END
,CASE 
   WHEN @FIELD2 = 'Col1' THEN Col1 
   WHEN @FIELD2 = 'Col2' THEN Col2
   --- etc ----
  END

// note: in above suggestion, you might need to add more "case statements" to accomodate for different data types
 



OR, the quick and dirty method


CREATE PROCEDURE udp_MULTI_SORT @FIELD1 VARCHAR(15), @FIELD2 VARCHAR(15)
AS
exec(SELECT * FROM RM00101 ORDER BY [' + @FIELD1 + '],[' + @FIELD2 +']')
Random Solutions  
 
programming4us programming4us