ALTER TABLE TBPDV_CONFERENCIA
    ADD VERSAO_ALTERACAO INTEGER DEFAULT 1 NOT NULL;


CREATE INDEX ITBPDV_CONFERENCIA_20
ON TBPDV_CONFERENCIA (VERSAO_ALTERACAO);

SET TERM ^ ;

CREATE trigger ttbpdv_conferencia_b02u for tbpdv_conferencia
active before update position 2
AS
BEGIN   
    IF(OLD.ESTABELECIMENTO_ID IS DISTINCT FROM NEW.ESTABELECIMENTO_ID
    OR OLD.PDV_ID IS DISTINCT FROM NEW.PDV_ID
    OR OLD.CLIENTE_ID IS DISTINCT FROM NEW.CLIENTE_ID
    OR OLD.TABELA_PRECO_ID IS DISTINCT FROM NEW.TABELA_PRECO_ID
    OR OLD.LOCALIZACAO_ID IS DISTINCT FROM NEW.LOCALIZACAO_ID
    OR OLD.REPRESENTANTE_ID IS DISTINCT FROM NEW.REPRESENTANTE_ID
    OR OLD.CORRETOR_ID IS DISTINCT FROM NEW.CORRETOR_ID
    OR OLD.VENDEDOR_ID IS DISTINCT FROM NEW.VENDEDOR_ID
    OR OLD.COLABORADOR_ID IS DISTINCT FROM NEW.COLABORADOR_ID
    ) THEN
    BEGIN
        NEW.VERSAO_ALTERACAO = NEW.VERSAO_ALTERACAO + 1;
    END
END
^

SET TERM ; ^

SET TERM ^ ;

CREATE trigger ttbpdv_conferencia_item_b02d for tbpdv_conferencia_item
active before delete position 2
AS
BEGIN
    IF(OLD.PDV_CONFERENCIA_ID > 0) THEN
    BEGIN
        UPDATE TBPDV_CONFERENCIA T SET T.VERSAO_ALTERACAO = T.VERSAO_ALTERACAO + 1 WHERE T.ID = OLD.PDV_CONFERENCIA_ID;
    END
END
^

SET TERM ; ^


SET TERM ^ ;

CREATE trigger ttbpdv_conferencia_item_b04iu for tbpdv_conferencia_item
active before insert or update position 4
AS
BEGIN   
    IF(INSERTING) THEN
    BEGIN
        UPDATE TBPDV_CONFERENCIA T SET T.VERSAO_ALTERACAO = T.VERSAO_ALTERACAO + 1 WHERE T.ID = NEW.PDV_CONFERENCIA_ID;

    END

    IF(UPDATING) THEN
    BEGIN
        IF(OLD.SEQUENCIA IS DISTINCT FROM NEW.SEQUENCIA
        OR OLD.PRODUTO_ID IS DISTINCT FROM NEW.PRODUTO_ID
        OR OLD.QUANTIDADE IS DISTINCT FROM NEW.QUANTIDADE
        OR OLD.VALOR_UNITARIO IS DISTINCT FROM NEW.VALOR_UNITARIO
        OR OLD.VALOR_DESCONTO IS DISTINCT FROM NEW.VALOR_DESCONTO
        OR OLD.VALOR_TOTAL IS DISTINCT FROM NEW.VALOR_TOTAL
        OR OLD.VALOR_LIQUIDO IS DISTINCT FROM NEW.VALOR_LIQUIDO
        OR OLD.TAMANHO IS DISTINCT FROM NEW.TAMANHO) THEN
        BEGIN
            UPDATE TBPDV_CONFERENCIA T SET T.VERSAO_ALTERACAO = T.VERSAO_ALTERACAO + 1 WHERE T.ID = OLD.PDV_CONFERENCIA_ID;
        END

    END

END
^

SET TERM ; ^

