Sql server 为什么我的检查约束不允许我向表中添加更多的值?

Sql server 为什么我的检查约束不允许我向表中添加更多的值?,sql-server,function,tsql,Sql Server,Function,Tsql,结果是: decision 'ron','haller','insert' alter procedure decision (@gt varchar(max) = null, @gg varchar(max) = null , @decision varchar(max)) as begin if @decision = 'select' begin try select * from simpleversionofsqlproject where firstname = isnull

结果是:

decision  'ron','haller','insert'


alter procedure decision (@gt varchar(max) = null, @gg varchar(max) = null , @decision varchar(max))
as
begin

if @decision = 'select'
begin try
select *
from simpleversionofsqlproject
where firstname = isnull(@gt, firstname)
or lastname = isnull(@gg, lastname)
end try
begin catch
raiserror ('not here',16,1)
end catch



if @decision = 'update'
begin
begin try
update simpleversionofsqlproject 
set firstname = @gt, lastname =@gg 
where @gg = lastname or @gt =firstname
end try
begin catch
begin
throw
print 'you have made a mistake'

end
end catch

end

if @decision = 'insert'
begin
begin try
begin transaction
insert into simpleversionofsqlproject(firstname,lastname)
values( @gt, @gg)

insert into historicfirstnames
values (@gt)
commit transaction
end try
begin catch
rollback
print 'tata'
end catch
end

if @decision = 'delete'
begin
delete from simpleversionofsqlproject
where firstname = @gt
end

if @decision not in ('update','delete','insert','select')
begin
raiserror('wrong action',16,1)
end


end

您的检查约束允许您添加新行,只要没有重复的现有
firstname

一旦复制了一个名字,就不能再添加行了——因为您要查看的是所有的名字,而不仅仅是插入的名字。您使用了
no check
选项,因此我假设表中有重复项

您需要将
firstname
传递给函数,并将其用于“唯一”约束。但是,为什么不创建一个唯一的约束呢

(0 row(s) affected)
tata

无论如何,您应该使用唯一约束而不是检查约束。如果它是3而不是2呢?@witchieleaks。我不知道你的数据是什么样子的。但是,如果要强制唯一性,为什么不使用
unique
约束呢?我猜这就是您真正想要做的。创建表simpleversionofsqlproject(firstname varchar(5),lastname varchar(5))去创建表historicfirstnames(firstname varchar(5))
(0 row(s) affected)
tata
alter table historicfirstnames with nocheck
    add constraint unq_numberoffirstnames unique(firstname);