简体   繁体   中英

How to check for null values with Dapper

I'm having an SQL table Countries, with CountryId and StateId. StateId can be null, as not all countries have States. I'd like to check if the combination of country/state exists in the table. If I have the country "NL" and state NULL in the table, and I use the following query where countryId = "NL" and stateId = null:

return await conn.ExecuteScalarAsync<bool>(@"SELECT COUNT(*)
                                             FROM [dbo].[Countries]
                                             WHERE [CountryId] = @CountryId
                                             AND [StateId] = @StateId",
                                             new { countryId, stateId });

It will return false. I expected a true response. Could someone explain this behaviour and what is the best approach to solve this?

That is not a Dapper issue. Comparing anything to NULL with the = operator will usually return false. You will have to use "is null" for comparison, ie

AND [StateId] is null

(at least on SQL Server). That means of course that your query will have to look differently in case stateid is null.

Check this:

SELECT COUNT(*)
       FROM [dbo].[Countries]
       WHERE [CountryId] = @CountryId
       AND ([StateId] IS NULL OR ([StateId] IS NOT NULL AND [StateId] = @StateId))

It will check if StateId is null , then only the 'CountryId' will be checked for those countries with no state, if StateId is not null , then StateId would be checked too

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