I am converting an old application to Web API and noticed a strange behaviour. I'm executing a simple select statement to fetch records.
select top 10
name, weight, id
from
tblA TA
inner join
tblB TB on TA.id = TB.id
where
id = @id
ORDER BY
weight desc
Unlike a similar question asked on SO, I am using ORDER BY clause in my query and this is working absolutely fine in old application. The data type for column weight is int.
My C# code in the application is:
List<People> people = new List<People>();
SqlCommand cmd = new SqlCommand();
cmd.Connection = _conn;
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = strSQLText;
// add parameters
cmd.Parameters.AddWithValue("@id", ID);
SqlDataReader sdrPerson;
sdrPerson= cmd.ExecuteReader();
using (sdrPerson)
{
while (sdrPerson.Read())
{
Person _person = new Person();
_person.name = sdrPerson["name"].ToString().Trim();
_person.id = Convert.ToInt32(sdrPerson["id"].ToString().Trim());
//add person to people list
people.Add(_person);
}
}
The issue: Query is doing order by but the SqlDataReader reads in different order. The query returns 10 rows and out of them one has weight value of 5 and others have value of 7. When ordered DESC, the top 9 rows just come randomly while the last one is always at the bottom or the output. And strangely it only happens if I order DESC and works fine with ASC. Query runs all good in sql server management studio.
The code is absolutely simple and I expected it to work right away. Why is this happening? Is there an issue with Web API or am I doing something wrong here? Or if the more than 1 row have same value for the order by column, does SqlDataReader do random ordering? I've never come across this before.
Sample output:
<people>
<person>
<id>1234</id>
<name>Mike</name>
</person>
<person>
<id>4545</id>
<name>Sally</name>
</person>
<person>
<id>576565</id>
<name>Ben</name>
</person>
<person>
<id>66107</id>
<name>Spyro</name>
</person>
<person>
<id>54879</id>
<name>Pat</name>
</person>
<person>
<id>54876</id>
<name>Kate</name>
</person>
<person>
<id>40584</id>
<name>Larry</name>
</person>
<person>
<id>35742</id>
<name>John</name>
</person>
<person>
<id>26432</id>
<name>George</name>
</person>