I’m trying to return the result as a string and I keep erring out at the cmd.ExecuteScalar()
Any suggestions?
static public string GetScalar(string sql)
{
string result = "";
SqlConnection conn = new SqlConnection(ConnectionString);
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
try
{
result = cmd.ExecuteScalar().ToString();
}
catch (SqlException ex)
{
DBUtilExceptionHandler(ex, sql);
throw ex;
}
finally
{
conn.Close();
}
return result;
}
I’m passing the following sql statement into sql:
select count(LeadListID) from LeadLists WHERE SalesPersonID = 1
AND LeadListDateCreated BETWEEN '9/1/11' AND '10/1/11 23:59:59'
which works fine as a query in Server Management Studio.
EDIT:
The method works, I was building my statement with errors. Thanks for your help!
The SqlCommand.ExecuteScalar return an Object type. It executes the query, and returns the first column of the first row in the result set returned by the query.
If you return a
countyou may need to cast the return value into an IntegerWithout the exact exception is hard to tell you what you did wrong, but for sure, I won’t use the ToString().