Using the SQL Command object, how can you check to see if the result set is empty?

Using the ExecuteScalar method in the SQL Command object, how can you check to see if the result set is empty? I am using ASP.net, C#, and MS SQL 2008. Right now when I run the following code the Response.Write returns a 0 when the resultset is empty. But I would like to differentiate between 0 and empty resultsets because there are actual 0 values in my database.

Here is the current code behind:

cmd = new SqlCommand("usp_test", cn);
cmd.CommandType = CommandType.StoredProcedure;

cn.Open();
TestOuput = Convert.ToInt32(cmd.ExecuteScalar());
cn.Close();

Response.Write(TestOutput);

Thank you.

Answers


Check out the definition of ExecuteScalar. It returns an Object, which will have a null reference if the result set is empty.

The reason you are seeing zero is that Convert.ToInt32 returns a zero when given null. You need to check the return value from ExecuteScalar before you convert it to an int.


DbCommand.ExecuteScalar() returns the first column of the first row, or null if the result is empty. Your problem is caused by Convert.ToInt32() because it returns 0 for null.

You have to check the value returned by ExecuteScalar() for null and only call Convert.ToInt32() if it is not null.

Object result = command.ExecuteScalar();

if (result != null)
{
   Int32 value = Convert.ToInt32(result);
}
else
{
   // Handle the empty result set case
}

As you can see in here you can check if the result is null :

Return Value Type: System.Object The first column of the first row in the result set, or a null reference (Nothing in Visual Basic) if the result set is empty.


Execute scalar will return the first column of the first row in the result set. If there are no results it should return null.

My guess is that your stored procedure is returning a count and not the dataset, which is why you are seeing a 0.


ExecuteScalar returns null if the result set is empty (as @fallen888, et al. have said). The reason you are seeing zero is that Convert.ToInt32 returns a zero when given null. You need to check the return value from ExecuteScalar before you convert it to an int.


cmd = new SqlCommand("usp_test", cn);
cmd.CommandType = CommandType.StoredProcedure;
cn.Open();
Object outPut=cmd.ExecuteScalar();
if(outPut!=null)
TestOuput = Convert.ToInt32(outPut);
else
//Return Empty Set
cn.Close();

Response.Write(TestOutput);

Need Your Help

Watch for CD in background

c# .net

I have found this code to watch for a CD to be inserted/ejected using C#. I'm curious if this can be efficiently tuned into a background process/timer function without any significant loss of