I have the following query in sql:
SELECT a1 FROM dbo.myProductNames WHERE keycode = 40 OR keycode = 28 OR keycode = 32 OR keycode = 50
a1 = the name
I need the information in the table to output the names its queried in the order ive asked, so I need 40 to be first then 28 so on on.
The reason for this is my code reads the results and stores in an array that then is used to display on a form.
The table that the SQL query comes from has the information stored in num order, so 28 will be read first etc etc.
As I have said I need to get the information in the order I entered in the where clause.
I’m thinking something to do with nested Select statements although ive never tried nested selects.
Or, is there an easy way?
Any help would be great!
Many thanks in advance!
Update:
ok here is the solution thanks to you guys!
SqlCommand pgNameFill = new SqlCommand("SELECT a1, CASE keycode WHEN @pg1 THEN 1 WHEN @pg2 THEN 2 WHEN @pg3 THEN 3 WHEN @pg4 THEN 4 END AS SortOrder FROM dbo.myProductNames WHERE keycode IN (@pg1, @pg2, @pg3, @pg4) ORDER BY SortOrder ASC", conny1); pgNameFill.Parameters.AddWithValue("@pg1", pg1); pgNameFill.Parameters.AddWithValue("@pg2", pg2); pgNameFill.Parameters.AddWithValue("@pg3", pg3); pgNameFill.Parameters.AddWithValue("@pg4", pg4); SqlDataReader readpg = pgNameFill.ExecuteReader();
Many thanks for all the posts! I wish I could flag more answers than just one, oh well upvotes all around!
Advertisement
Answer
Add the following ORDER BY clause:
ORDER BY CASE keycode when 40 then 1 when 28 then 2 when 32 then 3 when 50 then 4 END