Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Order By" using a parameter for the column name

We would like to use a parameter in the "Order By" clause of a query or stored procedure created with the Visual Studio DataSet Designer.

Example:

  FROM TableName  WHERE (Forename LIKE '%' + @SearchValue + '%') OR        (Surname LIKE '%' + @SearchValue + '%') OR        (@SearchValue = 'ALL') ORDER BY @OrderByColumn 

This error is displayed:

Variables are only allowed when ordering by an expression referencing  a column name. 
like image 969
Emad-ud-deen Avatar asked Dec 12 '12 16:12

Emad-ud-deen


People also ask

How do you ORDER BY a column?

Select a cell in the column you want to sort. On the Data tab, in the Sort & Filter group, click Sort. In the Sort dialog box, under Column, in the Sort by or Then by box, select the column that you want to sort by a custom list.

How do I sort a column name in SQL?

The ORDER BY statement in SQL is used to sort the fetched data in either ascending or descending according to one or more columns. By default ORDER BY sorts the data in ascending order. We can use the keyword DESC to sort the data in descending order and the keyword ASC to sort in ascending order.

Can we use ORDER BY for 2 columns?

After the ORDER BY keyword, add the name of the column by which you'd like to sort records first (in our example, salary). Then, after a comma, add the second column (in our example, last_name ). You can modify the sorting order (ascending or descending) separately for each column.


1 Answers

You should be able to do something like this:

SELECT * FROM     TableName WHERE     (Forename LIKE '%' + @SearchValue + '%') OR     (Surname LIKE '%' + @SearchValue + '%') OR     (@SearchValue = 'ALL') ORDER BY      CASE @OrderByColumn     WHEN 1 THEN Forename     WHEN 2 THEN Surname     END; 
  • Assign 1 to @OrderByColumn to sort on Forename.
  • Assign 2 to sort on Surname.
  • Etc... you can expand this scheme to arbitrary number of columns.

Be careful about performance though. These kinds of constructs may interfere with query optimizer's ability to find an optimal execution plan. For example, even if Forename is covered by index, query may still require the full sort instead of just traversing the index in order.

If that is the case, and you can't live with the performance implications, it may be necessary to have a separate version of the query for each possible sort order, complicating things considerably client-side.

like image 56
Branko Dimitrijevic Avatar answered Sep 18 '22 15:09

Branko Dimitrijevic