ExecuteScalar Vs ExecuteNonQuery


ExecuteScalar Method

Namespace:
  System.Data.SqlClient

Return DataType
: System.Object (returns a single value)

Use : Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.

Example:
public int getSomeProdId()
{
        int count=0;
        SqlConnection conn = new SqlConnection(connString))
        String sqlQuery = "SELECT COUNT(*) FROM dbo.region";
        SqlCommand cmd = new SqlCommand(sqlQuery, conn);
        try
        {
            conn.Open();
            //Since return type is System.Object, a typecast is must
            count = (Int32)cmd.ExecuteScalar();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
         finally
         {
            conn.Close();
         }
         return count;
}

ExecuteNonQuery Method

Namespace:  System.Data.SqlClient

Return DataType
: System.Int32 (number of rows affected)

Use : You can use the ExecuteNonQuery to perform catalog operations by executing UPDATE, INSERT, or DELETE statements.
For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1.

Example:
public void UpdateEmployeeEmail()
{
        SqlConnection conn = new SqlConnection(connString))
        String sqlQuery = "UPDATE Employee SET empemail='[email protected]' WHERE empid=4;
        SqlCommand cmd = new SqlCommand(sqlQuery, conn);
        try
        {
            conn.Open();
            cmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
         finally
         {
            conn.Close();
         }
         return count;
}

--------------------------------------------------------------------------------
Thank You...