Abhishek Pradhan
Abhishek Pradhan

Reputation: 25

How to check whether a column has a particular value

I am have a MS SQL database where there are field like:

With same businessid there can be many rows and with same refno there can be many rows. But with same refno and businessid there can be only one row. Now there can be many rows with same businessid, but I want to check whether a particular refno exist in those businessid or not. I know how to check whether a businessid exist in a table or not. But I am confused how to check that businessid with same name have a particular refno or not.

string g = Session["businessid"].ToString();
string h = Session["referenceno"].ToString();
con.Open();
SqlCommand check = new SqlCommand("select * from quoted_price where businessid=@businessid", con);
check.Parameters.AddWithValue("@businessid", g);
SqlDataReader dr = check.ExecuteReader();        
if (dr.HasRows)
{
    con.Close();
}

Upvotes: 0

Views: 93

Answers (1)

mason
mason

Reputation: 32693

You've one major problem with your code. You aren't properly handling objects that implement IDisposable. You need to either use a using block or the try/catch/finally pattern, where you handle cleanup in the finally block. Failure to do so can lead to connections that get left open, and you can run into strange hard to diagnose errors later on. For any class you use (particularly when storage or network access is required), always check if it implements IDisposable.

You also should think about when you create your SqlConnection vs when you open your connection. Why open the connection prior to being ready to use it?

Also, variables should adequately describe the information they contain. Avoid using unhelpful names like g and h.

And lastly, you can use two parameters to check the condition you wish to check.

string businessId = Session["businessid"].ToString();
string referenceNo = Session["referenceno"].ToString();    
bool hasRows = false;    

using(SqlConnection connection = new SqlConnection(parameters))
{
    using(SqlCommand checkCommand = new SqlCommand("select * from quoted_price where businessid=@businessid AND refno=@refno", connection))
    {
        checkCommand.Parameters.AddWithValue("@businessid", businessId);
        checkCommand.Parameters.AddWithValue("@refno", referenceNo);
        connection.Open();
        using(SqlDataReader dataReader = check.ExecuteReader())
        {
             hasRows = dataReader.HasRows;
        }                   
    }
}

Notice how instead of attempting to do a lot of logic with the dataReader that I just get what I want from it and store the value I care about. This is because I don't want to leave the connection open any longer than necessary.

Upvotes: 1

Related Questions