Wednesday, 5 February 2014

What is the difference between ExecuteNonQuery and ExecuteScalar in SQL

ExecuteNonQuery 
  1. Used mainly for action queries(insert,delete,update,create,alter). 
  2. Returns an int value indicating the number of affected rows.
  3. Return value is optional and can be assigned to an integer variable.
Example :
public void updateEmail()
{
        SqlConnection con = new SqlConnection(connString);
        String sqlQuery = "UPDATE Employee SET email='a@b.com' WHERE id=1;
        SqlCommand cmd = new SqlCommand(sqlQuery, con);
        try
        {
            con.Open();
            cmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
         finally
         {
            con.Close();
         }
}
 
ExecuteScalar 
  1. Used in queries where we have to read a single value.
  2. Returns an object.
  3. Return value is compulsory and should be assigned to a variable of required type.
Example:
public int getSomeNumber()
{
        int count=0;
        SqlConnection con = new SqlConnection(connString);
        String sqlQuery = "SELECT COUNT(*) FROM dbo.myTable";
        SqlCommand cmd = new SqlCommand(sqlQuery, con);
        try
        {
            con.Open();
            //return type is System.Object, a typecast is must
            count = (Int32)cmd.ExecuteScalar();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
         finally
         {
            con.Close();
         }
         return count;
}


That’s it!!…..Happy Programming...

No comments:

Post a Comment