2015-06-12 44 views
0

我正在写一个存储过程,在插入值之前需要检查一些约束。检查表中不同字段值的组合是否存在

的组合名称,性别和HQ_code应该不存在于表中。我正在使用select 1进行此约束检查。如果组合不存在,那么只执行插入语句,如果组合已经存在打印消息。请参阅代码中的注释部分。但不能进一步进行。

create proc_set_ref_staff 
    @name  varchar(50), 
    @sex  varchar(1), 
    @hq_code varchar(4), 
    @out_result varchar(500) output 

as 
begin 
    begin try 

     select 1 from tbl_ref_staff where name = @name and sex = @sex and hq_code = @hq_code; 
     --- if the combination exists set @out_result = 'already exists' 

     --- how can I write if the above combination not exists then only execute insert statement 
     --- insert into tbl_ref_staff values (@name, @sex, @hq_code) 

    end try 
    begin catch 
     set @out_result = error_message(); 
    end catch; 

end 

回答

2

也许你看起来像这样?

IF NOT EXISTS(SELECT 1 FROM tbl_ref_staff WHERE name = @name AND sex = @sex AND hq_code = @hq_code;) 
BEGIN 
INSERT INTO tbl_ref_staff VALUES (@name, @sex, @hq_code) 
END 
+0

感谢您的答复。如果该值已经存在,如何打印消息'@out_result ='已经存在'。请你可以相应地编辑你的代码。 – user4221591

1

您可以使用

if exists(select 1 from ...) 
begin 
... 
end 

,或者您可以使用语法

if (select count(1) from ..) > 0 
begin 
... 
end