0

Is "top 1" in sql skipping the where clause

Select top 1 afield from atable where secondfield = 3 I am telling you there is not record with secondfield = 3 If I run this the sql server it returns no record That was what I expected If I run this in the c# enviroment it returns the top most record regardless whether the where clause is true or not. Does "top" have precedence over the where clause ?

22nd Aug 2017, 8:51 PM
sneeze
sneeze - avatar
3 odpowiedzi
+ 2
@Sneeze, as I see it "TOP" only limits the number of records returned, it shouldn't interfere the "WHERE" clause.
22nd Aug 2017, 9:09 PM
Ipang
+ 1
Oeps I found my mistake. It was in the sql-statement "Select top 1 afield from atable where secondfield = secondfield" Not using the variable secondfield but just have plain text there. Still I do not understand why it did return a record. But when I use the variable it does not return any result anymore as it should.
22nd Aug 2017, 9:35 PM
sneeze
sneeze - avatar
0
@IPang thank you for answering. I starting to think it has something to do with the way I query the database. Becaus if I ran the same command in the sql server it gave me the correct results. This is the code I use to query the database. try { cnn.Open(); cmd = new SqlCommand(sql, cnn); reader = cmd.ExecuteReader(); while (reader.Read()) { MessageBox.Show(reader.GetValue(0) ); } reader.Close(); cmd.Dispose(); cnn.Close(); } catch (Exception ex) { MessageBox.Show("Can not open connection ! "); }
22nd Aug 2017, 9:17 PM
sneeze
sneeze - avatar