Sql receiving information, but in the wrong order

Hi guys, 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 = name I need information in the table to display the names that he requested in the query I set, so I need 40 to be first, then 28 onwards.

The reason for this is my code, which reads the results and stores in an array, which is then used to display on the form.

The table from which the SQL query arrives contains information stored in num order, so 28 will be read first, etc. etc.

As I said, I need to get the information in the order in which I entered the where clause.

I think there is something to do with nested Select statements, although I have never tried nested selects.

Or is there an easy way?

Any help would be great!

!

!!!!! UPDATE!!!!!

ok , , !

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();

! , , , !

+5
5

ORDER BY:

ORDER BY
CASE keycode 
    when 40 then 1
    when 28 then 2
    when 32 then 3
    when 50 then 4
END
+5

( mssql );

;with myRank(rank, keycode) as (
    select 1, 40 union
    select 2, 28 union
    select 3, 32 union
    select 4, 50
)
select 
    a1
from 
    myProductNames 
    inner join myRank on (myProductNames.keycode = myRank.keycode)
order by
    myRank.rank asc
+5

ORDER BY. , , . .

, , SortOrder , .

+4
source

Adding an answer to Simon. I would change the request to something like:

SELECT  
a1,
CASE keycode WHEN 40 THEN 1
WHEN 28 THEN 2
WHEN 32 THEN 3
WHEN 50 THEN 4 END AS SortOrder
FROM  dbo.myProductNames  
WHERE keycode IN (40, 28, 32, 50)
ORDER BY SortOrder ASC
+2
source
SELECT a1
 FROM myProductNames
 ORDER BY CASE WHEN keycode =40 THEN 1
               WHEN keycode =28 THEN 2
               WHEN keycode =32 THEN 3
               WHEN keycode =50 THEN 4
               ELSE 5
               END;
+1
source

All Articles