How to validate a record in a trigger?

1

To avoid doing code validation, I would like mysql to insert a detail of a loan to create a trigger to validate if cantidad de artículos in tabla artículos is greater than zero , let me update the table articles otherwise not update.
This is what I have done for the moment in phpmyadmin.

DROP TRIGGER IF EXISTS ACTUALIZAP_BI;
DELIMITER $$
    CREATE TRIGGER ACTUALIZAP_BI BEFORE INSERT ON detalleprestamo FOR EACH ROW
    BEGIN
        DECLARE V = @SELECT cant_articulo FROM articulos WHERE id_articulo = new.idarticulo;
        IF V > 0 THEN
            DECLARE T = UPDATE articulos SET
            cant_articulo = (cant_articulo - new.unidades) WHERE id_articulo = new.idarticulo;
        ELSE 
            DECLARE T = FALSE;
        END IF;
        SELECT T;
END;
DELIMITER $$;
    
asked by JDavid 10.05.2018 в 23:47
source

1 answer

1

There is an incorrect mix of delimiters in the code. Also, you try to do a SELECT that is not valid in the trigger (you will not return the result)

DROP TRIGGER IF EXISTS ACTUALIZAP_BI;
DELIMITER $$
CREATE TRIGGER ACTUALIZAP_BI BEFORE INSERT ON detalleprestamo FOR EACH ROW
BEGIN
    DECLARE v_cant_articulos int(11);

    SELECT cant_articulo INTO v_cant_articulos FROM articulos WHERE id_articulo = new.idarticulo;
    IF v_cant_articulos > 0 THEN
       UPDATE articulos SET cant_articulo = (cant_articulo - new.unidades) WHERE id_articulo = new.idarticulo;
    END IF;
    -- SELECT T; //No puedes hacer SELECT en el trigger esperando que lo retorne
END $$ -- Cambiaste el delimitador, úsalo!
DELIMITER ;  -- Y así es que se regresa al delimitador habitual
    
answered by 11.05.2018 в 00:01