0

基本上我在约束中想要的逻辑是这样的......

IF([AssetTypeId] = 1) 
THEN
    [FileId] IS NOT NULL AND [Url] IS NULL 
END

IF([AssetTypeId] = 0) 
THEN
   [FileId] IS NULL AND [Url] IS NOT NULL)
END

AssetTypeId 是当前表的 FK 引用/约束。我得到的错误表明语法错误,无论我如何用一个例外来表达这个,当我这样做时......

([AssetTypeId] = 1) AND [FileId] IS NOT NULL AND [Url] IS NULL 
OR
([AssetTypeId] = 0)  AND [FileId] IS NULL AND [Url] IS NOT NULL

它给了我这个错误:

'Asset (dbo)' table
- Unable to add constraint 'CK_Asset_FileIdOrUrlRequiredNotBoth'.  
The ALTER TABLE statement conflicted with the CHECK constraint "CK_Asset_FileIdOrUrlRequiredNotBoth". The conflict occurred in database "MyDb", table

“dbo.资产”。

我似乎无法弄清楚为什么 SQL 不允许我这样做。有什么想法吗?

4

1 回答 1

2

当消息在创建约束期间指示违反了相同的约束时:

'Asset (dbo)' table
- Unable to add constraint 'CK_Asset_FileIdOrUrlRequiredNotBoth'.  
The ALTER TABLE statement conflicted with the CHECK constraint "CK_Asset_FileIdOrUrlRequiredNotBoth". The conflict occurred in database "MyDb", table

这意味着该表中存在不符合您所需约束的现有数据。约束在语法上是有效的,否则不会走到这一步。

在实施约束之前,您需要找到错误数据并进行更正。

例如

SELECT * from Asset where
([AssetTypeId] = 1) AND ([FileId] IS NULL OR [Url] IS NOT NULL )
OR
([AssetTypeId] = 0)  AND ([FileId] IS NOT NULL OR [Url] IS NULL)

应该找到坏数据

于 2012-08-09T14:52:29.950 回答