MYSQL存储器的使用

使用存储器的场景:需要在数据新增前判断这条数据是否存在,如果存在,就不让新增了。 (为啥不用唯一索引呢? 因为y_vehicle_id这个字段是外键)

原理:写一个存储器,在新增前判断,如果存在,就抛出异常,不让他继续执行了
create trigger vehicle_judge before insert on hl_vehicle for each row
begin
    set @count = (select count(*) from hl_vehicle where y_vehicle_id = new.y_vehicle_id);
    if @count >0 then
        begin
            set @msg = '车辆已经存在';
            SIGNAL SQLSTATE '44444' SET MESSAGE_TEXT = @msg;
        end;

    end if;
end;
posted @ 2021-05-08 11:51  super_胡  阅读(154)  评论(0编辑  收藏  举报