如果表中不存在参数,如何抛出错误处理程序?

时间:2019-10-25 01:20:45

标签: mysql sql stored-procedures error-handling

所以我有这个存储过程:

delimiter //
create procedure sp_finish_campaign(in c_title varchar(30))
begin 
    update campaign set CAMPAIGNFINISHDATE = CURDATE()
    where TITLE = c_title;
end//
delimiter ;

我想知道如果活动表中不存在c_title参数,则如何在消息中引发错误处理程序。我尝试使用

DECLARE EXIT HANDLER FOR SQLSTATE '42000' SELECT 'Error!';

和一些if语句,但语法错误或字段列表中出现错误1054未知列标题。

1 个答案:

答案 0 :(得分:0)

使用此代码:

create procedure sp_finish_campaign(in c_title varchar(30))
begin 
    update campaign set CAMPAIGNFINISHDATE = CURDATE()
    where TITLE = c_title;

    if @@rowcount=0
    begin
      DECLARE @ErrorMessage  NVARCHAR(4000);
      DECLARE @V_ErrorCode   INT;
      DECLARE @ErrorState    INT;

      SELECT @V_ErrorCode   = 50000 ,
             @ErrorMessage  = c_title+ ' is not exists' ,
             @ErrorState    = 1
      THROW @V_ErrorCode,@ErrorMessage,@ErrorState

    end
end//