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

时间:2017-06-16 18:50:07

标签: sql-server function tsql

alter table historicfirstnames with nocheck
add constraint numberoffirstnames check(dbo.countoffn() < 2) 
go
alter function countoffn()
returns int
as 

begin
return 
(select max(w.cf) from (select count(firstname) as cf from historicfirstnames group by firstname) as w)

end

create table simpleversionofsqlproject
(firstname varchar(5),
lastname varchar(5)
)
go

create table historicfirstnames
(
firstname varchar(5)
)

这是我执行它的程序:

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

这是结果:

(0 row(s) affected)
tata

1 个答案:

答案 0 :(得分:0)

只要没有重复的现有firstname,您的检查约束就可以添加新行。

重复第一个名称后,不能再添加任何行 - 因为您正在查看所有名字,而不仅仅是正在插入的名字。您已使用no check选项,因此我假设表中有重复项。

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

alter table historicfirstnames with nocheck
    add constraint unq_numberoffirstnames unique(firstname);
相关问题