I've been writing a lot of web services with SQL inserts based on a stored procedure, and I haven't really worked with any SELECTS.
The one SELECT
I have in mind is very simple.
SELECT COUNT(AD_SID) As ReturnCount FROM AD_Authorization
WHERE AD_SID = @userSID
However, I can't figure out based on my current INSERT
code how to make that into a SELECT
and return the value of ReturnCount
... Can you help? Here is my INSERT
code:
string ConnString = "Data Source=Removed";
string SqlString = "spInsertProgress";
using (OleDbConnection conn = new OleDbConnection(ConnString))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("attachment_guid", smGuid.ToString());
cmd.Parameters.AddWithValue("attachment_percentcomplete", fileProgress);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
cmd.executescalar will return a single value, such as your count.
You would use cmd.executereader when you are returning a list of records
Here is where you are going wrong:
You are executing a query.
You need to
ExecuteReader
orExecuteScalar
instead.ExecuteReader
is used for a result set (several rows/columns),ExecuteScalar
when the query returns a single result (it returnsobject
, so the result needs to be cast to the correct type).The
results
variable will now hold aOledbDataReader
or a value with the results of theSELECT
. You can iterate over the results (for a reader), or the scalar value (for a scalar).You need to use
ExecuteScalar
instead ofExecuteNonQuery
:Since you are only after a single value, you can use cmd.ExecuteScalar();
A complete example is as follows:
If you wanted to return MULTIPLE rows, you can use the ExecuteReader() method. This returns an IDataReader via which you can enumerate the result set row by row.