Let’s say you have a Select Statement with a List of IDs in it’s “IN()” Part and want to get the Results in the same Order as the List of IDs.
You now could use the same “ORDER BY” you used when you got the List of IDs but why reordering if you already got the order?
Or you could reorder the result in your application.
But there’s another solution to order it in SQL. Using the “CASE-WHEN-THEN” Statement. It may not be very efficient if you have many IDs but that’s the best I found.
Example:
SELECT * FROM MyTable WHERE ID IN (60898,306386,316781,345240,183559,106853,63373,57124,10260,328451) ORDER BY (CASE WHEN ID = 60898 THEN 1 WHEN ID = 306386 THEN 2 WHEN ID = 316781 THEN 3 WHEN ID = 345240 THEN 4 WHEN ID = 183559 THEN 5 WHEN ID = 106853 THEN 6 WHEN ID = 63373 THEN 7 WHEN ID = 57124 THEN 8 WHEN ID = 10260 THEN 9 WHEN ID = 328451 THEN 10 END)
To automate that in CSharp, it could look like:
private string GenerateOrder(IList<int> idList) { StringBuilder sb = new StringBuilder(); sb.Append(" ORDER BY (CASE"); for (int i=0; i<idList.Count; i++) { int headerId = idList[i]; sb.AppendFormat(" WHEN header_id = {0} THEN {1}", headerId, (i+1)); } sb.Append(" END)"); return sb.ToString(); }