CREATE OR ALTER procedure SPD_NF (
    NF_ID integer,
    ORIGEM varchar(3),
    ESTABELECIMENTO integer)
as
BEGIN

IF (ORIGEM = 'NFE') THEN
   BEGIN
       DELETE FROM TBNFE_ITEM_SALDO     WHERE NFE_CONTROLE = :NF_ID;
       DELETE FROM TBNFE_ITEM           WHERE NFE_CONTROLE = :NF_ID;
       DELETE FROM TBNFE_PARCELAMENTO   WHERE NFE_CONTROLE = :NF_ID;
       DELETE FROM TBNFE_TRANSPORTADORA WHERE NFE_CONTROLE = :NF_ID;
       DELETE FROM TBNFE_OBSERVACAO     WHERE NFE_CONTROLE = :NF_ID;
       DELETE FROM TBNFE_TOTAIS         WHERE NFE_CONTROLE = :NF_ID;
       DELETE FROM TBNFE_REFERENCIADA   WHERE NFE_CONTROLE = :NF_ID;
       DELETE FROM TBNF_REFERENCIADA    WHERE ID = :NF_ID;
       DELETE FROM TBNF_LOTE
        WHERE ESTABELECIMENTO_CODIGO = :ESTABELECIMENTO
          AND NFE_CONTROLE = :NF_ID AND NFS_CONTROLE =  0;
       DELETE FROM TBNF_VINCULO_CONTABIL  
        WHERE ESTABELECIMENTO_ID = :ESTABELECIMENTO
          AND NFE_ID = :NF_ID AND NFS_ID =  0;
   END ELSE
   IF(ORIGEM = 'NFS') THEN
   BEGIN
       DELETE FROM TBNFS_ITEM_SALDO     WHERE NFS_CONTROLE = :NF_ID;
       DELETE FROM TBNFS_ITEM           WHERE NFS_CONTROLE = :NF_ID;
       DELETE FROM TBNFS_PARCELAMENTO   WHERE NFS_CONTROLE = :NF_ID;
       DELETE FROM TBNFS_TRANSPORTADORA WHERE NFS_CONTROLE = :NF_ID;
       DELETE FROM TBNFS_OBSERVACAO     WHERE NFS_CONTROLE = :NF_ID;
       DELETE FROM TBNFS_TOTAIS         WHERE NFS_CONTROLE = :NF_ID;
       DELETE FROM TBNFS_REFERENCIADA   WHERE NFS_CONTROLE = :NF_ID;
       DELETE FROM TBNF_REFERENCIADA    WHERE ID = :NF_ID;
       DELETE FROM TBNF_LOTE
        WHERE ESTABELECIMENTO_CODIGO = :ESTABELECIMENTO
          AND NFS_CONTROLE = :NF_ID AND NFS_CONTROLE =  0;
       DELETE FROM TBNF_VINCULO_CONTABIL  
        WHERE ESTABELECIMENTO_ID = :ESTABELECIMENTO
          AND NFE_ID = 0 AND NFS_ID = :NF_ID;
   END

END;