SET TERM ^ ;

CREATE trigger ttbacesso_ip_usuario_b01d for tbacesso_ip_usuario
active before delete position 0
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
DECLARE VARIABLE USUARIO VARCHAR(100);
BEGIN

    HISTORICO = '';
    USUARIO = COALESCE((SELECT FIRST 1 IIF( CHAR_LENGTH(COALESCE(U.NOME,'')) > 0, U.NOME, U.USUARIO) AS DESCRICAO FROM TBUSUARIO U WHERE U.CODIGO = OLD.USUARIO_ID), '');

    IF ( OLD.ACESSO_IP_ID > 0 AND OLD.ID > 0 ) THEN
    BEGIN
        HISTORICO = HISTORICO||' USUARIO INCLUIDO: '||FN_LPAD(OLD.USUARIO_ID, 4, '0')||' - '||USUARIO;
    END

    IF (HISTORICO <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBACESSO_IP',OLD.ACESSO_IP_ID, HISTORICO);
    END
END
^

SET TERM ; ^

SET TERM ^ ;

CREATE OR ALTER trigger ttbacesso_ip_usuario_b02i for tbacesso_ip_usuario
active before insert position 1
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
DECLARE VARIABLE USUARIO VARCHAR(100);
BEGIN

    HISTORICO = '';
    USUARIO = COALESCE((SELECT FIRST 1 IIF( CHAR_LENGTH(COALESCE(U.NOME,'')) > 0, U.NOME, U.USUARIO) AS DESCRICAO FROM TBUSUARIO U WHERE U.CODIGO = NEW.USUARIO_ID), '');

    IF ( NEW.ACESSO_IP_ID > 0 AND NEW.ID > 0 ) THEN
    BEGIN
        HISTORICO = HISTORICO||' USUARIO INCLUIDO: '||FN_LPAD(NEW.USUARIO_ID, 4, '0')||' - '||USUARIO;
    END

    IF (HISTORICO <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBACESSO_IP',NEW.ACESSO_IP_ID, HISTORICO);
    END
END
^

SET TERM ; ^

