我在下面有一个简单的例子
begin tran
CREATE TABLE [dbo].[Filters]
(
[Id] INT NOT NULL IDENTITY,
[FCode] varchar(30) null,
[FVersion] varbinary(892) null,
CONSTRAINT [PK_Filter] PRIMARY KEY CLUSTERED ([Id]),
CONSTRAINT [CK_Filters_FCode_FVersion]
CHECK (([FCode] IS NULL AND [FVersion] IS NULL)
OR (LEN([FCode]) > 0 AND DATALENGTH([FVersion]) > 0)),
)
INSERT INTO [dbo].[Filters] (FCode, FVersion)
VALUES (NULL, NULL),
(NULL, 0x6BE348),
('ASD', NULL),
('ASD', 0x6BE348)
SELECT
IIF(([FCode] IS NULL AND [FVersion] IS NULL)
OR (LEN([FCode]) > 0 AND DATALENGTH([FVersion]) > 0) , 1, 0) AS [check], *
FROM
[dbo].[filters]
rollback
我希望第2和第3个插入语句会导致约束违规。但服务器允许它们。
使用select语句查看第2行和第3行是否违反了约束检查的值。查看结果
check Id FCode FVersion
------------------------------
1 1 NULL NULL
0 2 NULL 0x6BE348
0 3 ASD NULL
1 4 ASD 0x6BE348
有什么想法吗?
答案 0 :(得分:5)
检查约束仅在值明确为false
时失败。
您希望违反约束的表达式评估为UNKNOWN
。
你可以用
看到这个SELECT CASE
WHEN( ( [FCode] IS NULL
AND [FVersion] IS NULL )
OR ( LEN([FCode]) > 0
AND DATALENGTH([FVersion]) > 0 ) ) THEN 'True'
WHEN NOT ( ( [FCode] IS NULL
AND [FVersion] IS NULL )
OR ( LEN([FCode]) > 0
AND DATALENGTH([FVersion]) > 0 ) ) THEN 'False'
ELSE 'Unknown'
END AS [check],
LEN([FCode]) AS LenFCode,
DATALENGTH([FVersion]) AS DataLengthFVersion,
*
FROM [dbo].[filters]
返回
+---------+----------+--------------------+----+-------+----------+
| check | LenFCode | DataLengthFVersion | Id | FCode | FVersion |
+---------+----------+--------------------+----+-------+----------+
| True | NULL | NULL | 1 | NULL | NULL |
| Unknown | NULL | 3 | 2 | NULL | 0x6BE348 |
| Unknown | 3 | NULL | 3 | ASD | NULL |
| True | 3 | 3 | 4 | ASD | 0x6BE348 |
+---------+----------+--------------------+----+-------+----------+
他们UNKNOWN
的原因是因为LEN
和DATALENGTH
在传递NULL
时都返回NULL
答案 1 :(得分:0)
Martin Smith的答案已经包含了SQL服务器在不违反检查约束的情况下允许指定值的原因。
您可以将检查约束修改为以下以使其正常工作。 Demo
CONSTRAINT [CK_Filters_FCode_FVersion]
CHECK (([FCode] IS NULL AND [FVersion] IS NULL)
OR (LEN(ISNULL([FCode],'')) > 0
AND ISNULL(DATALENGTH([FVersion]),-1) > 0))