SET TERM ^ ;

CREATE OR ALTER TRIGGER TTBCONTROLE_USUARIO_B0IUD FOR TBCONTROLE_USUARIO
ACTIVE BEFORE INSERT OR UPDATE OR DELETE POSITION 0
AS
BEGIN

    IF ( COALESCE(FN_GET_CONTEXT_TEMPORARY('ALTER_TBPARAMETRO'),0) <> 1 ) THEN
    BEGIN
        FN_SET_CONTEXT('ALTER_TBPARAMETRO',2);

        IF ( DELETING ) THEN
        BEGIN
        
            DELETE FROM TBPARAMETRO_DETALHE
             WHERE PARAMETRO_ID = COALESCE(FN_PARAMETRO('TBUSUARIO.'||OLD.ID,NULL,TRUE),0)
               AND TABELA_ID = OLD.USUARIO_ID;

            --DELETE FROM TBPARAMETRO WHERE TABELA = 'TBUSUARIO' AND CONTROLE = OLD.ID;
        END
        ELSE
        BEGIN

            UPDATE OR INSERT INTO TBPARAMETRO_DETALHE (
                PARAMETRO_ID,
                TABELA_ID,
                VALOR
            ) VALUES (
                COALESCE(FN_PARAMETRO('TBUSUARIO.'||NEW.ID,NULL,TRUE),0),
                NEW.USUARIO_ID,
                NEW.VALOR_EXT
            ) MATCHING ( PARAMETRO_ID, TABELA_ID );

        END
    END




END
^

SET TERM ; ^

