如何在MySQL存储过程中设置动态错误消息

时间:2014-12-08 22:26:40

标签: mysql stored-procedures error-handling

您好我正在尝试创建一个存储过程来将数据int插入到数据库中,但首先我验证了一些参数

如果未满足一个或多个验证,我想引发异常并停止存储过程。

到目前为止,我可以通过在检测到第一次错误时立即退出执行来执行此操作:

    -- si existe el correo
            if exists(select 1 from tbl_users u where u.`e-mail` = p_email limit 1) then
               SIGNAL SQLSTATE '45000'
               SET MESSAGE_TEXT ='Error: el correo ingreasdo ya existe';
            end if;
            -- convinacion de nombre y apellido ya existen
            IF EXISTS(SELECT 1 FROM tbl_users u WHERE u.`Nombre` = p_Nombre and u.`Apellido`=p_Apellido limit 1  ) THEN
               SIGNAL SQLSTATE '45000'
               SET MESSAGE_TEXT ='El nombre y apellido ya fueron ingreasados anteriormente';
            END IF;
            -- si el pasword es valido y el tipo (p_fk_user_type_id) es:1 (supervisor)
            IF (SELECT CHAR_LENGTH(p_Password)<4) and (p_fk_user_type_id <>1 ) THEN
               SIGNAL SQLSTATE '45000'
               SET MESSAGE_TEXT ='El pasword es muy corto, debe tener al menos 4 caracteres';
            END IF;

我需要做的是获取所有错误并将其返回到单个错误消息中 像这样的东西:

 DECLARE mensaje VARCHAR(100);
        SET mensaje = '';
        IF EXISTS(SELECT 1 FROM tbl_users u WHERE u.`e-mail` = p_email LIMIT 1) THEN
           SET mensaje = 'el correo ingreasdo ya existe');
        END IF;
        -- convinacion de nombre y apellido ya existen
        IF EXISTS(SELECT 1 FROM tbl_users u WHERE u.`Nombre` = p_Nombre AND u.`Apellido`=p_Apellido LIMIT 1  ) THEN
           SET mensaje = CONCAT(mensaje,' ','El nombre y apellido ya fueron ingreasados anteriormente');
        END IF;
        -- si el pasword es valido y el tipo (p_fk_user_type_id) es:1 (supervisor)
        IF (SELECT CHAR_LENGTH(p_Password)<4) AND (p_fk_user_type_id <>1 ) THEN
           SET mensaje = CONCAT(mensaje, ' ' ,'El pasword es muy corto, debe tener al menos 4 caracteres');
        END IF;

        IF (mensaje <>"")THEN
        SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT = mensaje;
         ELSEIF 
           -- insert to database
        END IF;

0 个答案:

没有答案
相关问题