我有以下情况,我有一个带有主键的表和一个约束,我不能有具有特定要求的行。出于演示目的,这里我有一个不允许在 N 列中插入重复值的约束。在实际情况下,它使用其他表的外键和附加过滤器检查多个列,因此我不能放置简单的唯一约束。所以这里是例子
create table dbo.T1 (
Id int not null identity (1,1),
N int not null
)
alter table dbo.T1
add primary key (Id);
go
create function [dbo].[fn_CheckN](@id int, @n int)
returns int
as
begin
if exists (select * from dbo.T1 t where t.n = @n and t.Id != @id)
return 0
return 1
end
go
alter table [dbo].T1 with nocheck add constraint [CK_T1_Valid] check (([dbo].[fn_CheckN]([Id],[N]) = 1))
go
alter table [dbo].T1 check constraint [CK_T1_Valid]
go
Run Code Online (Sandbox Code Playgroud)
当我同时运行时
insert into …Run Code Online (Sandbox Code Playgroud)