Can anyone explain why the third insert (labeled Query Data) in the below code is allowed by SQL Server?
As far as I can tell, the check constraint should only allow:
Codeis null andSystemis null.Codeis not null andSystemis1.
My first thought was ANSI NULLS, but setting them on or off made no difference.
This is a simplified example of a larger problem we found in our application (System was checked against a list of numbers – IN(1, 2, etc.)). We replaced this check with a foreign key (instead of IN)and a new check constraint that allowed either, both null or both not null; doing that prevented the third insert.
IF EXISTS (SELECT * FROM sys.check_constraints WHERE object_id = OBJECT_ID(N'[dbo].[CK_TestCheck]') AND parent_object_id = OBJECT_ID(N'[dbo].[TestCheck]'))
ALTER TABLE [dbo].[TestCheck] DROP CONSTRAINT [CK_TestCheck]
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[TestCheck]') AND type in (N'U'))
DROP TABLE [dbo].[TestCheck]
GO
SET ANSI_NULLS ON
GO
CREATE TABLE TestCheck(
[Id] [int] IDENTITY(1,1) NOT NULL,
[Code] [varchar](50) NULL,
[System] [tinyint] NULL,
PRIMARY KEY CLUSTERED ([Id] ASC))
GO
ALTER TABLE [dbo].[TestCheck] WITH CHECK ADD CONSTRAINT [CK_TestCheck] CHECK
(
([Code] IS NULL AND [System] IS NULL) --Both null
OR
([Code] IS NOT NULL AND [System] = 1) --Both not null ????
)
GO
ALTER TABLE [dbo].[TestCheck] CHECK CONSTRAINT [CK_TestCheck]
GO
--Good Data
insert TestCheck (Code, [System]) Values(null, null);
insert TestCheck (Code, [System]) Values('123', 1);
--Query Data
insert TestCheck (Code, [System]) Values('123', null);
--Bad data stopped
insert TestCheck (Code, [System]) Values(null, 1);
insert TestCheck (Code, [System]) Values('123', 4);
select * from TestCheck
Where
case when
(
([Code] IS NULL AND [System] IS NULL) --Both null
OR
([Code] IS NOT NULL AND [System] in (1, 2, 3)) --Both not null ????
)
then 0 else 1 end
= 1
The result of evaluating the current constraint for the values
123, NULLis Undefined.([Code] IS NULL AND [System] IS NULL)evaluates toFalse([Code] IS NOT NULL AND [System] IN (1, 2, 3))evaluates toUndefinedResult is
UndefinedCheck Constraint
You should change your check for
[System] IN (1, 2, 3)toISNULL([System], 0) IN (1, 2, 3).Your check constraint then becomes