karan k
karan k

Reputation: 967

Should I check for null or dbnull in the query

I have a query which checks how many records of a certain type are there using count().

select count(*) from abc where date="some value"

Here, is it possible that my query returns null or DBNull? Should I check for them?

Upvotes: 0

Views: 1345

Answers (6)

Eren Ersönmez
Eren Ersönmez

Reputation: 39085

Just try it:

SELECT COUNT(*) WHERE 1=2
--Returns 0

Per MSDN:

COUNT always returns an int data type value.

Upvotes: 1

e4rthdog
e4rthdog

Reputation: 5223

This is what i do:

if (rdr.HasRows)
        {
          rdr.Read();
          if (rdr["MyField"] != DBNull.Value)
                {
                   bla bla....
                }

So yes check for DBNull.

Upvotes: 0

charles
charles

Reputation: 55

You should check DbNull as it is database oriented.

See this answer

Upvotes: 0

Serge Bollaerts
Serge Bollaerts

Reputation: 324

If you are using ExecuteScalar, I think the call will retrieve null instead of a DbNull object.

What I use to do in order to always receive a value is encapsulating my request: SELECT ISNULL((SELECT COUNT(date) FROM abc WHERE date = "some value"), 0)

Serge

Upvotes: 0

juergen d
juergen d

Reputation: 204756

No, it will always return a number greater or equal to 0.

Upvotes: 3

Matías Fidemraizer
Matías Fidemraizer

Reputation: 64923

I don't think so: it can return zero or greater, since you're counting.

NULL would be a wrong result, since no results is there're zero results.

Upvotes: 5

Related Questions