My INSERT fails with Cannot insert the value NULL into column 'CustomerId', table 'dbo.Orders'; column does not allow nulls. The app is sure it sends a value. What can I check?
The column is defined NOT NULL and the statement supplies NULL. Check three places.
1. The data. Run the SELECT part of an INSERT ... SELECT and look for NULL values, using WHERE CustomerId IS NULL. A left join that finds no match is a very common source.
2. The mapping. In an ORM or import tool a column may not be mapped, so it is sent as NULL. Check the generated SQL in a profiler or Extended Events.
3. Defaults. A default constraint only applies when the column is left out of the insert. If the statement lists the column and passes NULL, the default is not used.
Fix the data or the mapping first. Making the column nullable only hides the problem, so do that only when NULL is a valid business value.
A left join was returning NULL for unmatched customers. Added a filter. Thanks.