3

ExecuteScalar() sometimes returns empty object -not null- although the record is exists. When I analyze this object with quickwatch, I see that object.GetType() is equal to DbNull. I can handle this empty object but I need to know why it is returns empty object sometimes although the record is exists.

string sql = @"SELECT SentDate 
               FROM dbo.EmailOut                                    
               WHERE ID = @ID";
SqlCommand cmd = new SqlCommand(sql, _cnn);
cmd.CommandType = System.Data.CommandType.Text;
cmd.Parameters.Add(new SqlParameter("@ID", ID));
object obj = cmd.ExecuteScalar();
if (obj == null)
    return false
sentDate = (DateTime)obj;
cmd.Dispose();

Most of the time my query runs perfectly. Can you please check my code?

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
cihadakt
  • 3,054
  • 11
  • 37
  • 59

1 Answers1

9

A return value of null means that no record was found.

A return value of DBNull means that a record was found, but the value of SentDate in that record is NULL.

Heinzi
  • 167,459
  • 57
  • 363
  • 519
  • but sentdate is not null – cihadakt Nov 08 '13 at 08:43
  • @cihata87: That's... surprising. Are you sure about that? Can you reproduce the problem? – Heinzi Nov 08 '13 at 08:45
  • 1
    @cihata87: Then we need to investigate further. Can you prepare a minimal sample (including the database data) that reliably reproduces the problem? – Heinzi Nov 08 '13 at 08:48
  • Finally I have found out that record is creating after 1 or 2 seconds later. But when I check sentdate is null because query runs so fast. So I did this System.Threading.Thread.Sleep(2000); I always get the full object. Thank you – cihadakt Nov 08 '13 at 09:22