CREATE TRIGGER TTBSAC_RESPONSAVEL_B01I FOR TBSAC_RESPONSAVEL
ACTIVE BEFORE INSERT POSITION 0
as
begin
  if (new.CODIGO is null) then
    new.CODIGO = gen_id(GTBSAC_RESPONSAVEL,1);
end;

CREATE TRIGGER TTBSAC_RESPONSAVEL_B02I FOR TBSAC_RESPONSAVEL
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN

    HISTORICO = '';

    IF ( NEW.CODIGO > 0) THEN
    BEGIN
        HISTORICO = HISTORICO||'Registro incluido';
    END

    IF (HISTORICO <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBSAC_RESPONSAVEL',NEW.CODIGO, HISTORICO);
    END
end;

CREATE TRIGGER TTBSAC_RESPONSAVEL_B01U FOR TBSAC_RESPONSAVEL
ACTIVE BEFORE UPDATE POSITION 0
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN

    HISTORICO = '';

    IF ( OLD.DESCRICAO <> NEW.DESCRICAO) THEN
    BEGIN
        HISTORICO = HISTORICO||'Codigo: '||OLD.CODIGO||', Descricao: '|| OLD.DESCRICAO||'->'||NEW.DESCRICAO;
    END

    IF ( OLD.SETOR <> NEW.SETOR) THEN
    BEGIN
        HISTORICO = HISTORICO||'Codigo: '||OLD.CODIGO||', Setor: '|| OLD.SETOR||'->'||NEW.SETOR;
    END

    IF ( OLD.USUARIO_CODIGO <> NEW.USUARIO_CODIGO) THEN
    BEGIN
        HISTORICO = HISTORICO||'Codigo: '||OLD.CODIGO||', Usuario Codigo: '|| OLD.USUARIO_CODIGO||'->'||NEW.USUARIO_CODIGO;
    END

    IF ( OLD.DATA <> NEW.DATA) THEN
    BEGIN
        HISTORICO = HISTORICO||'Codigo: '||OLD.CODIGO||', Data: '|| OLD.DATA||'->'||NEW.DATA;
    END

    IF ( OLD.STATUS <> NEW.STATUS) THEN
    BEGIN
        HISTORICO = HISTORICO||'Codigo: '||OLD.CODIGO||', Status: '|| OLD.STATUS||'->'||NEW.STATUS;
    END

    IF ( OLD.STATUS_EXCLUSAO <> NEW.STATUS_EXCLUSAO) THEN
    BEGIN
        HISTORICO = HISTORICO||'Codigo: '||OLD.CODIGO||', Status Exclusao: '|| OLD.STATUS_EXCLUSAO||'->'||NEW.STATUS_EXCLUSAO;
    END

    IF (HISTORICO <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBSAC_RESPONSAVEL',NEW.CODIGO, HISTORICO);
    END
end;

CREATE TRIGGER TTBSAC_RESPONSAVEL_B01D FOR TBSAC_RESPONSAVEL
ACTIVE BEFORE DELETE POSITION 0
AS
DECLARE VARIABLE HISTORICO VARCHAR(500);
BEGIN

    HISTORICO = '';

    IF ( OLD.CODIGO > 0) THEN
    BEGIN
        HISTORICO = HISTORICO||'Registro Excluido: '||old.CODIGO;
    END

    IF (HISTORICO <> '') THEN
    BEGIN
        EXECUTE PROCEDURE SPI_HISTORICO('TBSAC_RESPONSAVEL',old.CODIGO, HISTORICO);
    END
end;
