我对 sql 中的约束方法有疑问。
这是我的桌子
CREATE TABLE [relations].[CompoundKey_Contacts](
[compoundId] [varchar](32) NOT NULL,
[companyId] [varchar](32) NULL,
[personId] [varchar](32) NULL,
[contactInfoId] [varchar](32) NOT NULL)
当您向此表中添加一行时,它应该检查此人员和公司的组合是否已存在于表中。为此,我使用约束函数
约束
ALTER TABLE [relations].[CompoundKey_Contacts] WITH NOCHECK ADD CONSTRAINT [CK_CompoundKey_Contacts] CHECK (([relations].[doesThisCompoundKeyExist]([personId],[companyId])='NO'))
GO
ALTER TABLE [relations].[CompoundKey_Contacts] CHECK CONSTRAINT [CK_CompoundKey_Contacts]
GO
功能
CREATE function [relations].[doesThisCompoundKeyExist](
@personId varchar(32),
@companyId varchar(32)
)
returns varchar(3)
as
begin
declare @exists varchar(32)
if(@companyId is null and @personId is null)
set @exists = 'YES'
else if(@personId is null)
if exists(select compoundId from relations.CompoundKey_Contacts where personId is null AND companyId = @companyId)
set @exists = 'YES' 'This is where to code enters, but it should come to the else and return 'NO'
else
set @exists = 'NO'
else if(@companyId is null)
if exists(select compoundId from relations.CompoundKey_Contacts where personId = @personId AND companyId is null)
set @exists = 'YES'
else
set @exists = 'NO'
else if exists(
select compoundId from relations.CompoundKey_Contacts where personId = @personId AND companyId = @companyId
)
set @exists = 'YES'
else
set @exists = 'NO'
return @exists
end;
我的插入语句失败
insert into relations.CompoundKey_Contacts (companyId, contactInfoId, personId, compoundId) values ('COM-000015945', 'INF-000144406', null, 'CPK-000000067');
问题是这样的。当我在具有唯一插入的表上运行插入时,它仍然失败。我当然检查过它是否依赖于 select 语句是唯一的。有趣的部分来了。当我调试它并检查它失败的地方并分解该代码部分并在不处于函数中的情况下自由运行它时,它的行为应该如此,因此如果以下代码不在函数中运行,则它可以工作
if exists(select compoundId from relations.CompoundKey_Contacts where personId is null AND companyId = 'COM-000015945')
print 'YES'
else
print 'NO' 'Returns NO as it should.
这是我得到的错误消息
The INSERT statement conflicted with the CHECK constraint "CK_CompoundKey_Contacts". The conflict occurred in database "domas", table "relations.CompoundKey_Contacts".
The statement has been terminated.
我在 Sql Server 2012 和 Sql Server 'DENALI' CTP3 上运行它