检查表中不同字段的值组合是否存在

时间:2015-06-12 11:25:37

标签: sql sql-server-2008

我正在编写一个存储过程,我需要在插入值之前检查一些约束。

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

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 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

您可以使用

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

或者您可以使用语法

if (select count(1) from ..) > 0 
begin 
...
end    
相关问题