2015-06-12 45 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