Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering SQL Server results by IN clause

I have a stored procedure which uses the IN clause. In my ASP.NET application, I have a multiline textbox that supplies values to the stored procedure. I want to be able to order by the values as they were entered in the textbox. I found out how to do this easily in mySQL (using FIELD function), but not a SQL Server equivalent.

So my query looks like:

Select * from myTable where item in @item

So I would be passing in values from my application like '113113','112112','114114' (in an arbitrary order). I want to order the results by that list.

Would a CASE statement be feasible? I wouldn't know how many items are coming in the textbox data.

like image 516
Andrew Avatar asked Jan 20 '12 20:01

Andrew


People also ask

How do you sort data by ORDER BY clause in SQL Server?

If you want to sort some of the data in ascending order and other data in descending order, then you would have to use the ASC and DESC keywords. SELECT * FROM table ORDER BY column1 ASC, column2 DESC; That is how to use the ORDER BY clause in SQL to sort data in ascending order.

Does order matter in ORDER BY clause?

The order of columns/expressions showing up does matter. It orders by the first one as specified, then orders that set by the next one, then by the next. The result is different than if you were to reverse the order in which the columns are ordered.

Can you use a subquery in an ORDER BY?

ORDER BY command cannot be used in a Subquery.


1 Answers

How are you parameterising the IN clause?

As you are on SQL Server 2008 I would pass in a Table Valued Parameter with two columns item and sort_order and join on that instead. Then you can just add an ORDER BY sort_order onto the end.

like image 59
Martin Smith Avatar answered Sep 28 '22 07:09

Martin Smith