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.
これは、SQLServer2012とSQLServer'DENALI'CTP3の両方で実行します。