views:

173

answers:

4

For example, I have a table, and there is a column named 'Tags'. I want to know if value 'programming' exists in this column. How can I do this in ADO.NET?

I did this:

OleDbCommand cmd = new OleDbCommand("SELECT * FROM table1 WHERE Tags='programming'", conn);
OleDbDataReader = cmd.ExecuteReader();
What should I do next?

+3  A: 

use SELECT COUNT(*) and check the results. (and use ExecuteScalar)

(assuming you know how to set the connection and use it)

Dani
+3  A: 
SELECT  TOP 1 1
FROM    table1
WHERE   Tags='programming'
Quassnoi
This solution is better to your's or Dani's because the server will stop processing as soon as it encounters one row with the right tag. If coloumn is not indexed , this will prevent a table scan.
Marcel Gosselin
+1  A: 

better version, it is a good practice to use parameters instead of string concatenation, see sql injection

OleDbCommand cmd = new OleDbCommand("SELECT TOP 1 1
 FROM table1 WHERE Tags=?", conn);
cmd.Parameters.Add("@p1", OleDbType.VarChar).Value = "Programming";
OleDbDataReader rdr = cmd.ExecuteReader();
if(rdr.Read())
    // record exists
else
   //Not exists
ArsenMkrt
+1  A: 

You should do two things:

If you are just checking the presence of a tag called Programming, you should change your query to return a COUNT instead of returning all rows.

SELECT TOP 1 Column1 FROM Table1 WHERE Tags = 'Programming'

You should check the returned set in the reader to see if there are any rows. If there are, then it means that the tag exists.

Raj More