简体   繁体   中英

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?

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 .

不,它将始终返回一个大于或等于0

Just try it:

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

Per MSDN :

COUNT always returns an int data type value.

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

You should check DbNull as it is database oriented.

See this answer

This is what i do:

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

So yes check for DBNull.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM