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?
[StateId] = NULLthen you won't get any results - check it for yourself in SSMS (or your SQL client of choice). You need to includeAND [StateId] = @StateIdonly ifstateIdis not null (or check the answer below if you are explicitly interested in it beingnull). - mjwills