execute scaler and execute non querry

ExecuteNonQuery expects to run a command, or a stored procedure, that affects the state of the specified table. This means anything but a query command. You normally use this method to issue an INSERT, UPDATE, DELETE, CREATE, and SET statement.
ExecuteNonQuery returns only the number of rows affected by the command execution, or –1 should this information be unavailable. It doesn’t give you a chance to access any result set generated by the statement or the stored procedure. Actually, there’s really nothing to prevent you from using this method for a query command, but in this case you get neither the resultset nor the number of the affected rows.
cmd.Connection.Open();
nRecsAffected = cmd.ExecuteNonQuery();
cmd.Connection.Close();
// check the record(s) affected here

The number of affected rows is also made available through the RecordsAffected property of the SqlCommand object. This property equals –1 in case of errors or if a query command is executed.
ExecuteScalar expects to run a query command, or more likely a stored procedure, that returns data. However, this method is different from ExecuteReader in that it just makes available, as a scalar value, the first column on the first row of the selected resultset.
cmd.Connection.Open();
Object o = cmd.ExecuteScalar(); cmd.Connection.Close();
// work on the scalar here

The method returns the value as a boxed object. It’s then up to you to unbox or cast that value to the proper, expected type.
ExecuteScalar turns out to be particularly useful when you have statistical or aggregate operations to accomplish on a certain amount of data. In these and similar circumstances, there is just one value that you might want to return back to the caller. Because of its use cases, you normally use this method on more or less complex stored procedures rather than on single SQL statements.


0 comments: