CREATE trigger ttbformulario_b02i for tbformulario
active before insert position 1
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN
    HISTORICO = '';

    IF ( NEW.ID > 0) THEN
    BEGIN
        HISTORICO = HISTORICO||' REGISTRO INCLUIDO';
    END

    IF (HISTORICO <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBFORMULARIO',NEW.ID, HISTORICO);
    END
END;


CREATE OR ALTER trigger ttbformulario_b1u for tbformulario
active before update position 1
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN

    HISTORICO = '';

    IF (OLD.FORMULARIO_TIPO_ID <> NEW.FORMULARIO_TIPO_ID) THEN
    BEGIN
       HISTORICO = HISTORICO||' TIPO FORM:'||OLD.FORMULARIO_TIPO_ID||'->'||NEW.FORMULARIO_TIPO_ID;
    END

    IF (OLD.TITULO <> NEW.TITULO) THEN
    BEGIN
        HISTORICO = HISTORICO||' TITULO:'||OLD.TITULO||'->'||NEW.TITULO;
    END

    IF (OLD.DESCRICAO <> NEW.DESCRICAO) THEN
    BEGIN
       HISTORICO = HISTORICO||' DESC:'||OLD.DESCRICAO||'->'||NEW.DESCRICAO;
    END

    IF(OLD.PERIODO_INI <> NEW.PERIODO_INI) THEN
    BEGIN
       HISTORICO = HISTORICO||' PERIODO INI:'||OLD.PERIODO_INI||'->'||NEW.PERIODO_INI;
    END

    IF(OLD.PERIODO_FIM <> NEW.PERIODO_FIM) THEN
    BEGIN
       HISTORICO = HISTORICO||' PERIODO FIM:'||OLD.PERIODO_FIM||'->'||NEW.PERIODO_FIM;
    END

    IF (HISTORICO <> '') THEN
    BEGIN
		HISTORICO = ' REGISTRO ALTERADO: '||HISTORICO;
       INSERT INTO TBHISTORICO (
       TABELA, TABELA_ID, USUARIO, IP, HISTORICO) VALUES (
       'TBFORMULARIO', OLD.ID,
      (SELECT FIRST 1 MON$USER FROM MON$ATTACHMENTS WHERE MON$ATTACHMENT_ID = CURRENT_CONNECTION),
      (SELECT FIRST 1 MON$REMOTE_ADDRESS FROM MON$ATTACHMENTS WHERE MON$ATTACHMENT_ID = CURRENT_CONNECTION),
       :HISTORICO);
    END
END;


CREATE trigger ttbformulario_b01d for tbformulario
active before delete position 0
AS
BEGIN
   IF(OLD.ID > 0) THEN
   BEGIN
      DELETE FROM TBFORMULARIO_DESTINATARIO WHERE FORMULARIO_ID = OLD.ID;
      DELETE FROM TBFORMULARIO_PERGUNTA     WHERE FORMULARIO_ID = OLD.ID;
      DELETE FROM TBFORMULARIO_ALTERNATIVA  WHERE FORMULARIO_ID = OLD.ID;
   END
END;


CREATE trigger ttbformulario_b02d for tbformulario
active before delete position 1
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN
    HISTORICO = '';

    IF ( OLD.ID > 0) THEN
    BEGIN
        HISTORICO = HISTORICO||' REGISTRO EXCLUIDO';
    END

    IF (HISTORICO <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBFORMULARIO',OLD.ID, HISTORICO);
    END
END;








