SET TERM ^ ;

CREATE OR ALTER TRIGGER TTBPDV_CONFERENCIA_ITEM_B01I FOR TBPDV_CONFERENCIA_ITEM
ACTIVE BEFORE INSERT POSITION 0
AS
DECLARE VARIABLE NUMERO_CFE VARCHAR(20);
BEGIN
  NUMERO_CFE = COALESCE((SELECT FIRST 1 FN_LPAD(C.NUMERO_CFE,6,0) AS NUMERO_CFE FROM TBPDV_CFE_ITEM CI, TBPDV_CFE C, TBPDV_CONFERENCIA CONF
                WHERE C.ID = CI.PDV_CFE_ID AND CI.CONFERENCIA_ID = NEW.PDV_CONFERENCIA_ID AND CONF.ID = CI.CONFERENCIA_ID AND C.SITUACAO = 2),'');

  IF(:NUMERO_CFE <> '')THEN
  BEGIN
    EXCEPTION "..." 'PRE-PEDIDO JA FATURADO.<BR> OPERACAO CANCELADA.';
  END

  IF (NEW.ID IS NULL) THEN
  BEGIN
    NEW.ID = GEN_ID(GTBPDV_CONFERENCIA_ITEM,1);
  END
  IF (NEW.QUANTIDADE_ORIGINAL IS NULL) THEN
  BEGIN
    NEW.QUANTIDADE_ORIGINAL = NEW.QUANTIDADE;
  END
END^

SET TERM ; ^